@aiqa/sdk 2.1.0-develop.3 → 2.1.0-develop.4
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 +184 -52
- package/dist/browser/browser.d.ts +64 -31
- package/dist/browser/browser.js +17 -1
- package/dist/browser/browser.js.map +1 -1
- package/dist/node/node.d.ts +64 -31
- package/dist/node/node.js +17 -1
- package/dist/node/node.js.map +1 -1
- package/package.json +1 -1
package/dist/node/node.d.ts
CHANGED
|
@@ -1,5 +1,41 @@
|
|
|
1
1
|
import { Socket } from 'socket.io-client';
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* Rolled-up verdict over the *answers*: `critical_errors` if any critical fact
|
|
5
|
+
* failed, otherwise `errors` if any fact failed, otherwise `no_errors`.
|
|
6
|
+
* Questions that were never asked do not raise it, so a call where everything
|
|
7
|
+
* was skipped and nothing was wrong reads `no_errors`.
|
|
8
|
+
*
|
|
9
|
+
* Distinct from the per-fact `VerificationStatus` — this one describes the
|
|
10
|
+
* call, not an answer.
|
|
11
|
+
*/
|
|
12
|
+
type ApplicationVerificationStatus = "no_errors" | "errors" | "critical_errors";
|
|
13
|
+
/** Verification tally for the application at the moment it was requested. */
|
|
14
|
+
type ApplicationVerificationSummary = {
|
|
15
|
+
status: ApplicationVerificationStatus;
|
|
16
|
+
/** Facts whose answer did not match the expected one. */
|
|
17
|
+
count_errors: number;
|
|
18
|
+
/** Subset of `count_errors` whose question is marked critical. */
|
|
19
|
+
count_critical_errors: number;
|
|
20
|
+
/**
|
|
21
|
+
* Facts on the application, full stop — verdict or not. Not a pass count and
|
|
22
|
+
* not a count of what has been evaluated: `count_not_asked` and
|
|
23
|
+
* `count_pending` are subsets of it, not separate buckets.
|
|
24
|
+
*/
|
|
25
|
+
count_total: number;
|
|
26
|
+
/** Facts with a verdict of never-asked. Excludes the still-pending ones. */
|
|
27
|
+
count_not_asked: number;
|
|
28
|
+
/** Subset of `count_not_asked` whose question is marked critical. */
|
|
29
|
+
count_critical_not_asked: number;
|
|
30
|
+
/**
|
|
31
|
+
* Facts still awaiting a verdict — added, but not resolved yet. During a live
|
|
32
|
+
* call most facts sit here, and they drain into the other counters as the
|
|
33
|
+
* call proceeds.
|
|
34
|
+
*/
|
|
35
|
+
count_pending: number;
|
|
36
|
+
/** Facts the conduct review flagged; a matched fact can still be suspicious. */
|
|
37
|
+
count_suspicious: number;
|
|
38
|
+
};
|
|
3
39
|
type Application = {
|
|
4
40
|
application_id: string;
|
|
5
41
|
client_name: string;
|
|
@@ -7,10 +43,17 @@ type Application = {
|
|
|
7
43
|
agent_id: string;
|
|
8
44
|
agent_first_name: string;
|
|
9
45
|
agent_last_name: string;
|
|
46
|
+
/**
|
|
47
|
+
* Absent only when the server predates this field, in which case
|
|
48
|
+
* `getApplication()` served its cached authentication snapshot. Treat the
|
|
49
|
+
* absence as "no live data", never as a zeroed summary.
|
|
50
|
+
*/
|
|
51
|
+
verification?: ApplicationVerificationSummary;
|
|
10
52
|
};
|
|
11
53
|
declare enum Methods {
|
|
12
54
|
AUTHENTICATE = "AUTHENTICATE",
|
|
13
55
|
GET_FACTS = "GET_FACTS",
|
|
56
|
+
GET_APPLICATION = "GET_APPLICATION",
|
|
14
57
|
START_RECORDING = "START_RECORDING",
|
|
15
58
|
STOP_RECORDING = "STOP_RECORDING",
|
|
16
59
|
IS_RECORDING = "IS_RECORDING",
|
|
@@ -156,24 +199,23 @@ interface AddFactResult {
|
|
|
156
199
|
question_match_score?: number;
|
|
157
200
|
/**
|
|
158
201
|
* 0–1 score derived from how well the customer's answer matched expected.
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
*
|
|
202
|
+
* Derived from partial-match heuristics (numeric-prefix ratio,
|
|
203
|
+
* matched-components ratio). Undefined when no partial signal exists,
|
|
204
|
+
* or on older server versions.
|
|
162
205
|
*/
|
|
163
206
|
answer_match_score?: number;
|
|
164
207
|
metadata?: Record<string, string>;
|
|
165
208
|
/**
|
|
166
209
|
* Top-level state at terminal resolution. Always one of `matched`
|
|
167
210
|
* or `unmatched` because the `addFact()` Promise only
|
|
168
|
-
* resolves on terminals. Optional
|
|
169
|
-
*
|
|
211
|
+
* resolves on terminals. Optional for compatibility with older
|
|
212
|
+
* server versions.
|
|
170
213
|
*/
|
|
171
214
|
verification_status?: VerificationStatus;
|
|
172
215
|
/**
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
* generalise to addresses, names, dates, etc.
|
|
216
|
+
* Component labels describing which parts of the expected answer
|
|
217
|
+
* matched. Currently `["prefix"]` / `["suffix"]` for numeric facts;
|
|
218
|
+
* treat the set as open-ended.
|
|
177
219
|
*/
|
|
178
220
|
matched_components?: string[];
|
|
179
221
|
missing_components?: string[];
|
|
@@ -181,7 +223,7 @@ interface AddFactResult {
|
|
|
181
223
|
/**
|
|
182
224
|
* Payload of the `FACT_VERIFIED` broadcast event.
|
|
183
225
|
*
|
|
184
|
-
* Fires on EVERY state transition the
|
|
226
|
+
* Fires on EVERY state transition the server produces —
|
|
185
227
|
* non-terminal (`partial`, `awaiting_question`, `awaiting_answer`,
|
|
186
228
|
* `pending_confirmation_matched`, `pending_confirmation_unmatched`,
|
|
187
229
|
* `processing`) AND terminal (`matched`, `unmatched`).
|
|
@@ -213,33 +255,24 @@ type FlagFactResult = {
|
|
|
213
255
|
success: boolean;
|
|
214
256
|
};
|
|
215
257
|
/**
|
|
216
|
-
* Coarse dialog-act label
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
* Mirrors `DialogAct` in
|
|
222
|
-
* `libs/types/src/utterance-enrichment.ts` on the backend.
|
|
258
|
+
* Coarse dialog-act label classified server-side. Advisory only — do
|
|
259
|
+
* not gate production behaviour on this value; it is a best-effort
|
|
260
|
+
* categorical guess, paired with a separate `dialog_act_confidence`
|
|
261
|
+
* band.
|
|
223
262
|
*/
|
|
224
263
|
type DialogAct = "question" | "answer" | "acknowledgement" | "filler" | "other";
|
|
225
264
|
/**
|
|
226
265
|
* Categorical confidence band for `dialog_act` ONLY. Named distinctly
|
|
227
266
|
* from the numeric STT `confidence` field on the same utterance — the
|
|
228
|
-
* two are unrelated
|
|
229
|
-
* the backend.
|
|
230
|
-
*
|
|
231
|
-
* Mirrors `DialogActConfidence` in
|
|
232
|
-
* `libs/types/src/utterance-enrichment.ts` on the backend.
|
|
267
|
+
* two are unrelated, so do not compare or conflate them.
|
|
233
268
|
*/
|
|
234
269
|
type DialogActConfidence = "high" | "medium" | "low";
|
|
235
270
|
/**
|
|
236
|
-
* Persisted utterance shape
|
|
237
|
-
*
|
|
238
|
-
* and the `Utterance` interface in `libs/types/src/common.ts` field for
|
|
239
|
-
* field. Sent over the wire by the `TRANSCRIPTION_UPDATED` broadcast.
|
|
271
|
+
* Persisted utterance shape, sent over the wire by the
|
|
272
|
+
* `TRANSCRIPTION_UPDATED` broadcast.
|
|
240
273
|
*
|
|
241
|
-
* The 7
|
|
242
|
-
*
|
|
274
|
+
* The 7 classification fields are all optional because utterances
|
|
275
|
+
* persisted by older server versions lack them.
|
|
243
276
|
* Treat any missing or nullish value as "unknown" — NOT as a deliberate
|
|
244
277
|
* negative signal. `is_ivr_filler_candidate === false` in particular
|
|
245
278
|
* does NOT round-trip through `undefined`, so consumer logic that wants
|
|
@@ -251,8 +284,8 @@ type Utterance = {
|
|
|
251
284
|
id: string;
|
|
252
285
|
call_id: number;
|
|
253
286
|
/**
|
|
254
|
-
*
|
|
255
|
-
*
|
|
287
|
+
* Reserved — currently always 0. Do not use for sorting; sort by `id`
|
|
288
|
+
* (UUIDv7) instead.
|
|
256
289
|
*/
|
|
257
290
|
order: number;
|
|
258
291
|
is_agent: boolean | null;
|
|
@@ -328,4 +361,4 @@ declare class AiQaSdk implements IAiqaSdk {
|
|
|
328
361
|
private isManagerEvent;
|
|
329
362
|
}
|
|
330
363
|
|
|
331
|
-
export { type AddFactResult, AiQaSdk, type Application, type ApplicationFact, type ApplicationFactAnswerChoice, type ApplicationFactAnswerFormat, type ApplicationFactInput, ConversationLanguage, type DialogAct, type DialogActConfidence, FactAnswerFormatType, type FactVerifiedPayload, type FlagFactResult, IAiqaSdk, Methods, type QuestionStatus, type SdkError, type SdkEvent, type SetConversationLanguageResult, type SetConversationProductResult, type TranscriptionUpdate, type UpdateConversationInput, type UpdateConversationResult, type Utterance, type VerificationStatus };
|
|
364
|
+
export { type AddFactResult, AiQaSdk, type Application, type ApplicationFact, type ApplicationFactAnswerChoice, type ApplicationFactAnswerFormat, type ApplicationFactInput, type ApplicationVerificationStatus, type ApplicationVerificationSummary, ConversationLanguage, type DialogAct, type DialogActConfidence, FactAnswerFormatType, type FactVerifiedPayload, type FlagFactResult, IAiqaSdk, Methods, type QuestionStatus, type SdkError, type SdkEvent, type SetConversationLanguageResult, type SetConversationProductResult, type TranscriptionUpdate, type UpdateConversationInput, type UpdateConversationResult, type Utterance, type VerificationStatus };
|
package/dist/node/node.js
CHANGED
|
@@ -5,6 +5,7 @@ import { io } from "socket.io-client";
|
|
|
5
5
|
var Methods = /* @__PURE__ */ ((Methods2) => {
|
|
6
6
|
Methods2["AUTHENTICATE"] = "AUTHENTICATE";
|
|
7
7
|
Methods2["GET_FACTS"] = "GET_FACTS";
|
|
8
|
+
Methods2["GET_APPLICATION"] = "GET_APPLICATION";
|
|
8
9
|
Methods2["START_RECORDING"] = "START_RECORDING";
|
|
9
10
|
Methods2["STOP_RECORDING"] = "STOP_RECORDING";
|
|
10
11
|
Methods2["IS_RECORDING"] = "IS_RECORDING";
|
|
@@ -61,7 +62,7 @@ var compareVersions = (left, right) => {
|
|
|
61
62
|
// package.json
|
|
62
63
|
var package_default = {
|
|
63
64
|
name: "@aiqa/sdk",
|
|
64
|
-
version: "2.1.0-develop.
|
|
65
|
+
version: "2.1.0-develop.4",
|
|
65
66
|
main: "dist/node/node.js",
|
|
66
67
|
module: "dist/node/node.js",
|
|
67
68
|
types: "dist/node/node.d.ts",
|
|
@@ -145,6 +146,9 @@ var DEFAULT_URL = "ws://localhost:3025/ws";
|
|
|
145
146
|
var DEFAULT_TIMEOUT_MS = 6e4;
|
|
146
147
|
var RUNTIME = typeof window !== "undefined" && typeof window.document !== "undefined" ? "browser" : "node";
|
|
147
148
|
var USER_AGENT = RUNTIME === "browser" ? typeof navigator !== "undefined" ? navigator.userAgent : "browser/unknown" : typeof process !== "undefined" ? `node ${process.version} ${process.platform}` : "node/unknown";
|
|
149
|
+
function isRequestTimeout(error, method) {
|
|
150
|
+
return error instanceof Error && error.message === `Request timed out for ${method}`;
|
|
151
|
+
}
|
|
148
152
|
function isThenable(value) {
|
|
149
153
|
return value !== null && typeof value === "object" && typeof value.then === "function";
|
|
150
154
|
}
|
|
@@ -352,6 +356,18 @@ var AiQaSdk = class {
|
|
|
352
356
|
});
|
|
353
357
|
}
|
|
354
358
|
async getApplication() {
|
|
359
|
+
try {
|
|
360
|
+
const result = await this.sendMessage("GET_APPLICATION" /* GET_APPLICATION */);
|
|
361
|
+
const application = result && result.data !== void 0 ? result.data : result;
|
|
362
|
+
if (application && application.application_id !== void 0) {
|
|
363
|
+
return application;
|
|
364
|
+
}
|
|
365
|
+
throw new Error("GET_APPLICATION returned no application");
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (!isRequestTimeout(error, "GET_APPLICATION" /* GET_APPLICATION */)) {
|
|
368
|
+
throw error;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
355
371
|
if (this.cachedApplication) {
|
|
356
372
|
return this.cachedApplication;
|
|
357
373
|
}
|
package/dist/node/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/shared.ts","../../src/types.ts","../../src/utils/compareVersions.ts","../../package.json"],"sourcesContent":["import { io, Socket } from \"socket.io-client\";\nimport {\n Methods,\n Application,\n ApplicationFact,\n ApplicationFactInput,\n SdkEvent,\n IAiqaSdk,\n AddFactResult,\n FlagFactResult,\n SetConversationProductResult,\n SetConversationLanguageResult,\n UpdateConversationInput,\n UpdateConversationResult,\n ConversationLanguage,\n} from \"./types.js\";\nimport { compareVersions } from \"./utils/compareVersions.js\";\n// @ts-ignore - compiled builds resolve this at build time\nimport pkg from \"../package.json\";\n\nconst SDK_VERSION = (pkg as { version?: string }).version ?? \"0.0.1\";\nconst DEFAULT_URL = \"ws://localhost:3025/ws\";\nconst DEFAULT_TIMEOUT_MS = 60000; // 1 minute\n\nconst RUNTIME: \"browser\" | \"node\" =\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n ? \"browser\"\n : \"node\";\n\nconst USER_AGENT: string =\n RUNTIME === \"browser\"\n ? typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : \"browser/unknown\"\n : typeof process !== \"undefined\"\n ? `node ${process.version} ${process.platform}`\n : \"node/unknown\";\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\n// Fires the trailing ack callback (when present) after delivering the\n// payload to user code. Throws and async rejections are routed to\n// console.error — propagating them would skip subsequent listeners in\n// @socket.io/component-emitter's untryCatched loop.\n//\n// Auto-parses string args as JSON. The backend's broadcast emits\n// (`FACT_VERIFIED`, `TRANSCRIPTION_UPDATED`, `CALL_STATUS_UPDATED`) all\n// send `JSON.stringify(...)` payloads, but `FactVerifiedPayload` and\n// friends are typed as plain objects. Without this parse, a consumer\n// writing `payload.factId` would read a property off a string and get\n// `undefined`. Strings that don't parse (e.g. a primitive event name)\n// pass through unchanged.\nexport function wrapEventHandler(\n callback: (...args: any[]) => any,\n): (...args: any[]) => void {\n return (...args: any[]) => {\n const last = args[args.length - 1];\n const hasAck = typeof last === \"function\";\n const rawPayload = hasAck ? args.slice(0, -1) : args;\n const payload = rawPayload.map((arg) => {\n if (typeof arg !== \"string\") return arg;\n try {\n return JSON.parse(arg);\n } catch {\n return arg;\n }\n });\n try {\n const handlerResult = callback(...payload);\n if (isThenable(handlerResult)) {\n handlerResult.then(undefined, (err) => {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] async event handler rejected:\", err);\n });\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] event handler threw:\", err);\n } finally {\n if (hasAck) {\n try {\n last();\n } catch {\n /* swallow */\n }\n }\n }\n };\n}\n\nclass AiQaSdk implements IAiqaSdk {\n socket: Socket | null = null;\n url: string;\n applicationId: string;\n applicationSecretKey: string;\n cachedApplication?: Application;\n internalListeners: Map<SdkEvent, Set<(...args: any[]) => void>>;\n internalEvents: Set<SdkEvent>;\n // event → originalCallback → Set<wrappedCallback> registered on\n // socket.io. A Set per (event, callback) so that subscribing the\n // same fn twice registers two wrappers and two off() calls clear\n // both.\n private wrappersByEvent: Map<\n SdkEvent,\n Map<(...args: any[]) => any, Set<(...args: any[]) => void>>\n > = new Map();\n\n constructor(applicationId: string, applicationSecret: string, url?: string) {\n this.url = url ?? DEFAULT_URL;\n this.internalListeners = new Map();\n this.internalEvents = new Set([\"authenticated\"]);\n\n if (applicationId && applicationSecret) {\n this.applicationId = applicationId;\n this.applicationSecretKey = applicationSecret;\n } else {\n throw new Error(\"Application id and application secret are required\");\n }\n }\n\n on(name: SdkEvent, callback: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!this.internalListeners.has(name)) {\n this.internalListeners.set(name, new Set());\n }\n this.internalListeners.get(name)!.add(callback);\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.on(name, callback);\n } else {\n const wrapped = wrapEventHandler(callback);\n let wrappersByCallback = this.wrappersByEvent.get(name);\n if (!wrappersByCallback) {\n wrappersByCallback = new Map();\n this.wrappersByEvent.set(name, wrappersByCallback);\n }\n let wrappers = wrappersByCallback.get(callback);\n if (!wrappers) {\n wrappers = new Set();\n wrappersByCallback.set(callback, wrappers);\n }\n wrappers.add(wrapped);\n this.socket.on(name, wrapped);\n }\n }\n\n off(name: SdkEvent, callback?: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!callback) {\n this.internalListeners.delete(name);\n return;\n }\n const handlers = this.internalListeners.get(name);\n if (handlers) {\n handlers.delete(callback);\n if (handlers.size === 0) {\n this.internalListeners.delete(name);\n }\n }\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.off(name, callback);\n return;\n }\n\n if (!callback) {\n this.socket.off(name);\n this.wrappersByEvent.delete(name);\n return;\n }\n\n const wrappersByCallback = this.wrappersByEvent.get(name);\n const wrappers = wrappersByCallback?.get(callback);\n if (wrappers && wrappers.size > 0) {\n const wrapped = wrappers.values().next().value as (\n ...args: any[]\n ) => void;\n wrappers.delete(wrapped);\n this.socket.off(name, wrapped);\n if (wrappers.size === 0) {\n wrappersByCallback!.delete(callback);\n if (wrappersByCallback!.size === 0) {\n this.wrappersByEvent.delete(name);\n }\n }\n } else {\n this.socket.off(name, callback);\n }\n }\n\n connect() {\n if (!this.url) {\n return;\n }\n\n const url = new URL(this.url);\n\n const socketOptions: any = {\n reconnectionDelayMax: 10000,\n path: url.pathname,\n // WebSocket only, skipping engine.io's default HTTP long-polling phase.\n // Some embedders sit behind proxies/security gateways that duplicate the\n // polling GETs across a fleet; the concurrent polls violate engine.io's\n // one-inflight-poll-per-session rule and tear the session down, so every\n // poll then returns \"Session ID unknown\" (HTTP 400) and the client never\n // authenticates. A single WebSocket has no repeated requests to duplicate.\n transports: [\"websocket\"],\n };\n\n this.socket = io(url.origin, socketOptions);\n\n this.socket.on(\"connect\", () => {\n this.authenticate();\n });\n\n this.socket.on(\n \"app_version\",\n wrapEventHandler((payload: any) => {\n const minVersion = payload?.min;\n const maxVersion = payload?.max;\n\n if (minVersion || maxVersion) {\n const tooLow = minVersion\n ? compareVersions(SDK_VERSION, minVersion) < 0\n : false;\n const tooHigh = maxVersion\n ? compareVersions(SDK_VERSION, maxVersion) > 0\n : false;\n if (tooLow || tooHigh) {\n const error = new Error(\n `SDK version ${SDK_VERSION} is not supported. Supported range: ${minVersion || \"-\"} to ${maxVersion || \"-\"}.`,\n );\n this.socket!.disconnect();\n this.socket!.emit(\"error\", error);\n }\n }\n }),\n );\n }\n\n disconnect() {\n if (this.socket) {\n this.socket.disconnect();\n }\n this.wrappersByEvent.clear();\n }\n\n sendMessage(method: Methods, data?: any): Promise<any> {\n return new Promise((resolve, reject) => {\n if (!this.socket || !this.socket.connected) {\n reject(new Error(\"Socket is not connected\"));\n return;\n }\n\n const requestId = this.createRequestId();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const handler = (payload: any) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n this.socket!.off(requestId, handler);\n let parsed = payload;\n if (typeof payload === \"string\") {\n try {\n parsed = JSON.parse(payload);\n } catch (error) {\n parsed = payload;\n }\n }\n\n if (parsed && parsed.error !== undefined) {\n reject(parsed.error);\n return;\n }\n\n // Return the full parsed envelope. Every caller below\n // (addFact, getFacts, flagFact, set*) already does its own\n // `result.data !== undefined ? result.data : result` unwrap,\n // so removing the unwrap here is behaviourally a no-op for\n // them — but it exposes top-level envelope fields like\n // `verification_status` to addFact() so the terminal\n // resolution can carry them alongside the inner data block.\n resolve(parsed);\n };\n\n this.socket.on(requestId, handler);\n\n const payload =\n data && typeof data === \"object\"\n ? { ...data, requestId }\n : { requestId, data };\n this.socket.emit(method, JSON.stringify(payload));\n\n timeout = setTimeout(() => {\n this.socket!.off(requestId, handler);\n reject(new Error(`Request timed out for ${method}`));\n }, DEFAULT_TIMEOUT_MS);\n });\n }\n\n async getApplication(): Promise<Application> {\n if (this.cachedApplication) {\n return this.cachedApplication;\n }\n throw new Error(\n \"Application is not available yet. Wait for authentication to complete.\",\n );\n }\n\n async getFacts(): Promise<ApplicationFact[]> {\n const result = await this.sendMessage(Methods.GET_FACTS);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async addFact(fact: ApplicationFactInput): Promise<AddFactResult> {\n const payload = {\n ...fact,\n critical: fact.critical ?? false,\n is_skipped: fact.is_skipped ?? false,\n };\n const result = await this.sendMessage(Methods.ADD_FACT, payload);\n if (!result) return result;\n const inner = result.data !== undefined ? result.data : result;\n\n // Older backends emit only `data` (or even a primitive like\n // `true`). New backends emit a `FactVerifiedResponseDto` envelope\n // carrying `verification_status` / `matched_components` /\n // `missing_components` at the top level ALONGSIDE the inner\n // `FactVerifiedDataDto`. Merge the envelope onto the resolved\n // value so callers awaiting addFact() see the full terminal\n // shape without subscribing to the broadcast `FACT_VERIFIED`\n // event. Skip the merge when the envelope is absent OR when inner\n // is not an object — spreading a primitive (`{ ...true }`) would\n // silently turn the resolution into `{}`.\n const hasEnvelope =\n result.verification_status !== undefined ||\n result.matched_components !== undefined ||\n result.missing_components !== undefined;\n if (!hasEnvelope || typeof inner !== \"object\" || inner === null) {\n return inner;\n }\n const merged = { ...inner } as AddFactResult;\n if (result.verification_status !== undefined) {\n merged.verification_status = result.verification_status;\n }\n if (result.matched_components !== undefined) {\n merged.matched_components = result.matched_components;\n }\n if (result.missing_components !== undefined) {\n merged.missing_components = result.missing_components;\n }\n return merged;\n }\n\n async flagFact(factId: string): Promise<FlagFactResult> {\n const result = await this.sendMessage(Methods.FLAG_FACT, {\n factId,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_PRODUCT, {\n product,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_LANGUAGE, {\n language,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult> {\n const result = await this.sendMessage(Methods.UPDATE_CONVERSATION, input);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async authenticate(): Promise<void> {\n try {\n const result = await this.sendMessage(Methods.AUTHENTICATE, {\n applicationId: this.applicationId,\n applicationSecretKey: this.applicationSecretKey,\n sdkVersion: SDK_VERSION,\n runtime: RUNTIME,\n userAgent: USER_AGENT,\n });\n\n const application =\n result && result.data !== undefined ? result.data : result;\n\n this.cachedApplication = application;\n\n this.emitInternal(\"authenticated\", application);\n } catch (error) {\n this.socket!.emit(\"error\", error);\n }\n }\n\n async startRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.START_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async stopRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.STOP_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async isRecordingNow(): Promise<boolean> {\n // @TODO: track it from the server, should be sent on successfull connect\n const result = await this.sendMessage(Methods.IS_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n private emitInternal(name: SdkEvent, ...args: any[]) {\n const handlers = this.internalListeners.get(name);\n if (!handlers) {\n return;\n }\n handlers.forEach((handler) => handler(...args));\n }\n\n private createRequestId() {\n return `req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n }\n\n private isManagerEvent(name: SdkEvent) {\n return (\n name === \"reconnect_attempt\" ||\n name === \"reconnect_error\" ||\n name === \"reconnect_failed\" ||\n name === \"error\"\n );\n }\n}\n\nexport default AiQaSdk;\n","export type Application = {\n application_id: string;\n client_name: string;\n client_phone_number: string;\n agent_id: string;\n agent_first_name: string;\n agent_last_name: string;\n};\n\nexport enum Methods {\n AUTHENTICATE = \"AUTHENTICATE\",\n GET_FACTS = \"GET_FACTS\",\n START_RECORDING = \"START_RECORDING\",\n STOP_RECORDING = \"STOP_RECORDING\",\n IS_RECORDING = \"IS_RECORDING\",\n ADD_FACT = \"ADD_FACT\",\n FLAG_FACT = \"FLAG_FACT\",\n SET_CONVERSATION_PRODUCT = \"SET_CONVERSATION_PRODUCT\",\n SET_CONVERSATION_LANGUAGE = \"SET_CONVERSATION_LANGUAGE\",\n UPDATE_CONVERSATION = \"UPDATE_CONVERSATION\",\n}\n\nexport type SetConversationProductResult = {\n success: boolean;\n product: string;\n};\n\nexport type SetConversationLanguageResult = {\n success: boolean;\n language: string;\n};\n\nexport type UpdateConversationInput = {\n policyNumber?: string;\n insuredPhone?: string;\n clientName?: string;\n clientPhone?: string;\n clientEmail?: string;\n clientId?: string;\n agentId?: string;\n agentName?: string;\n advisorId?: string;\n advisorName?: string;\n agentGroups?: string[];\n};\n\n/** Echo of the patched subset — only the fields you sent come back. */\nexport type UpdateConversationResult = {\n success: boolean;\n conversation: {\n policy_number?: string;\n insured_phone?: string;\n client_name?: string;\n client_phone?: string;\n client_email?: string;\n client_id?: string;\n agent_id?: string;\n agent_name?: string;\n advisor_id?: string;\n advisor_name?: string;\n agent_groups?: string[];\n };\n};\n\nexport enum ConversationLanguage {\n EN = \"en\",\n ES = \"es\",\n FR = \"fr\",\n}\n\nexport type SdkEvent =\n | Methods\n | \"connect\"\n | \"disconnect\"\n | \"close\"\n | \"error\"\n | \"reconnect_attempt\"\n | \"reconnect_error\"\n | \"reconnect_failed\"\n | \"authenticated\"\n | \"app_version\"\n // Broadcast channel for every server-side verification event,\n // non-terminal OR terminal. Subscribe with\n // `sdk.on(\"FACT_VERIFIED\", cb)` to receive progress\n // (`awaiting_question`, `awaiting_answer`, `partial`,\n // `pending_confirmation_matched`, `pending_confirmation_unmatched`)\n // alongside the terminal (`matched`, `unmatched`)\n // verdicts. `addFact()`'s Promise resolves only on the terminal —\n // this event stream is the way to render progress.\n //\n // Uppercase matches the backend's `SocketEvents.FACT_VERIFIED`\n // constant (`apps/realtime-verification/src/socket/utils.ts`).\n | \"FACT_VERIFIED\"\n // Broadcast channel for every persisted utterance, real-time.\n // Subscribe with `sdk.on(\"TRANSCRIPTION_UPDATED\", cb)` to receive\n // `TranscriptionUpdate` payloads as transcripts land.\n //\n // Uppercase matches the backend's `SocketEvents.TRANSCRIPTION_UPDATED`\n // constant (`apps/realtime-verification/src/socket/utils.ts`).\n | \"TRANSCRIPTION_UPDATED\";\n\nexport enum FactAnswerFormatType {\n string = \"STRING\",\n number = \"NUMBER\",\n integer = \"INT\",\n float = \"FLOAT\",\n bool = \"BOOL\",\n list = \"LIST\",\n strict = \"STRICT\",\n single_choice = \"SINGLE_CHOICE\",\n multiple_choices = \"MULTIPLE_CHOICES\",\n}\n\nexport type ApplicationFactAnswerChoice = {\n key: string;\n text: string;\n};\n\nexport type ApplicationFactAnswerFormat = {\n type: FactAnswerFormatType;\n choices?: ApplicationFactAnswerChoice[];\n};\n\nexport type ApplicationFactInput = {\n id: string;\n /**\n * Stable identifier for the underlying question, shared across applications and\n * conversations. When provided it is used to look up (or create) the matching\n * question row in the database instead of `id`. Keep this consistent across\n * calls — accuracy improvements and remaps configured in the management\n * dashboard are scoped per `questionId`.\n */\n questionId?: string;\n question: string;\n expected_answer: any;\n answer_format: ApplicationFactAnswerFormat;\n\n category_id?: string;\n category_name?: string;\n language?: string;\n\n critical?: boolean;\n is_skipped?: boolean;\n metadata?: Record<string, string>;\n};\n\nexport type QuestionStatus = \"searching\" | \"asked\" | \"not_asked\";\n\n/**\n * Per-fact verification state.\n *\n * Extended from the original three-state shape to carry progress signals\n * the backend already detects but previously could not express. Consumers\n * that switch on this value MUST treat unknown strings as \"processing\"\n * (default fall-through) so older SDK builds keep working after the\n * backend starts emitting the additive states.\n *\n * Semantics:\n * - `processing` generic, just queued or transcription not ready\n * - `awaiting_question` agent hasn't asked the question yet\n * - `awaiting_answer` question asked, customer hasn't answered yet\n * - `partial` partial evidence; backend still working on it\n * - `pending_confirmation_matched` backend has a matching answer but is\n * holding a settling window for mid-answer\n * clarifications (e.g. spellings, \"I mean…\");\n * resolves to `matched`/`unmatched`\n * - `pending_confirmation_unmatched` same as above but the held verdict is\n * `unmatched`; UI can show \"we heard X but it\n * doesn't match, waiting to confirm\" instead\n * of a hard red verdict\n * - `matched` terminal: answer matched expected\n * - `unmatched` terminal: budget exhausted with no match\n */\nexport type VerificationStatus =\n | \"processing\"\n | \"awaiting_question\"\n | \"awaiting_answer\"\n | \"partial\"\n | \"pending_confirmation_matched\"\n | \"pending_confirmation_unmatched\"\n | \"matched\"\n | \"unmatched\";\n\nexport type ApplicationFact = ApplicationFactInput & {\n ai_answer?: any;\n question_status: QuestionStatus;\n verification_status: VerificationStatus;\n /** True once `flagFact(factId)` has been called for this fact. */\n flagged: boolean;\n};\n\nexport interface AddFactResult {\n /** Conversation the fact was attached to. Useful for cross-fact correlation in agent UIs. */\n conversation_id?: string;\n /** Echo of the original question text from the fact input. */\n question?: string;\n /** Echo of the resolved `answer_format.type` (e.g. \"STRING\", \"NUMBER\", \"SINGLE_CHOICE\"). */\n answer_type?: string;\n agent_answer?: string;\n ai_answer?: string;\n is_valid_answer: boolean;\n question_asked?: boolean;\n /**\n * 0–1 (or 0–100 — scale matches the configured similarity method).\n * Similarity between the agent's utterance and the expected question.\n * Renamed from `match_score` to disambiguate from the answer-side score.\n */\n question_match_score?: number;\n /**\n * 0–1 score derived from how well the customer's answer matched expected.\n * Populated by the verification queue from partial-match heuristics\n * (numeric-prefix ratio, matched-components ratio). Undefined when no\n * partial signal exists or for terminal results before this rolls out.\n */\n answer_match_score?: number;\n metadata?: Record<string, string>;\n /**\n * Top-level state at terminal resolution. Always one of `matched`\n * or `unmatched` because the `addFact()` Promise only\n * resolves on terminals. Optional during the rollout window for\n * backwards compatibility with older backends.\n */\n verification_status?: VerificationStatus;\n /**\n * Per-fact partial-match breakdown carried through from the\n * verification queue's component-wise comparators. For numeric-prefix\n * facts these are `[\"prefix\"]` / `[\"suffix\"]`; future work will\n * generalise to addresses, names, dates, etc.\n */\n matched_components?: string[];\n missing_components?: string[];\n}\n\n/**\n * Payload of the `FACT_VERIFIED` broadcast event.\n *\n * Fires on EVERY state transition the verification queue produces —\n * non-terminal (`partial`, `awaiting_question`, `awaiting_answer`,\n * `pending_confirmation_matched`, `pending_confirmation_unmatched`,\n * `processing`) AND terminal (`matched`, `unmatched`).\n *\n * Subscribe with:\n * sdk.on(\"FACT_VERIFIED\", (payload: FactVerifiedPayload) => {...});\n *\n * `addFact()`'s Promise resolves only on terminals; this event stream\n * is the channel for rendering live progress in the agent UI.\n */\nexport interface FactVerifiedPayload {\n factId: string;\n success: boolean;\n verification_status?: VerificationStatus;\n question_match_score?: number;\n answer_match_score?: number;\n matched_components?: string[];\n missing_components?: string[];\n /**\n * Inner data payload. Shape matches `AddFactResult` (minus the\n * top-level envelope fields) so consumers can reuse the same\n * rendering code for the terminal addFact() resolution and the\n * broadcast event.\n */\n data?: AddFactResult;\n error?: string;\n}\n\nexport type FlagFactResult = {\n success: boolean;\n};\n\n/**\n * Coarse dialog-act label produced by the backend's `UtteranceEnricher`.\n * Advisory only — do not gate production behaviour on this value; the\n * enricher emits its best-effort categorical guess plus a separate\n * `dialog_act_confidence` band.\n *\n * Mirrors `DialogAct` in\n * `libs/types/src/utterance-enrichment.ts` on the backend.\n */\nexport type DialogAct =\n | \"question\"\n | \"answer\"\n | \"acknowledgement\"\n | \"filler\"\n | \"other\";\n\n/**\n * Categorical confidence band for `dialog_act` ONLY. Named distinctly\n * from the numeric STT `confidence` field on the same utterance — the\n * two are unrelated and conflating them is a documented drift hazard on\n * the backend.\n *\n * Mirrors `DialogActConfidence` in\n * `libs/types/src/utterance-enrichment.ts` on the backend.\n */\nexport type DialogActConfidence = \"high\" | \"medium\" | \"low\";\n\n/**\n * Persisted utterance shape — matches `TranscriptionUtteranceDto` on the\n * gateway (`apps/realtime-verification/src/socket/realtimeVerification.gateway.output.dto.ts`)\n * and the `Utterance` interface in `libs/types/src/common.ts` field for\n * field. Sent over the wire by the `TRANSCRIPTION_UPDATED` broadcast.\n *\n * The 7 enricher classification fields are all optional because\n * pre-cutover utterances (persisted before backend PR #234) lack them.\n * Treat any missing or nullish value as \"unknown\" — NOT as a deliberate\n * negative signal. `is_ivr_filler_candidate === false` in particular\n * does NOT round-trip through `undefined`, so consumer logic that wants\n * \"definitely not a filler\" must check `=== false` after confirming the\n * field is present.\n */\nexport type Utterance = {\n /** UUIDv7 — chronologically sortable. Use `id` (NOT `order`) for sorting. */\n id: string;\n call_id: number;\n /**\n * NOT YET IMPLEMENTED — currently hardcoded to 0 at write sites on\n * the backend. Do not use for sorting; sort by `id` (UUIDv7) instead.\n */\n order: number;\n is_agent: boolean | null;\n speaker: number;\n text: string;\n text_en: string | null;\n start_time: number;\n end_time: number;\n dialog_act?: DialogAct;\n dialog_act_confidence?: DialogActConfidence;\n confidence?: number | null;\n top_alt_margin?: number | null;\n is_ivr_filler_candidate?: boolean;\n spoken_digits_normalized?: string | null;\n vendor?: string | null;\n};\n\n/**\n * Payload of the `TRANSCRIPTION_UPDATED` broadcast event. Mirrors\n * `TranscriptionUpdateResponseDto` on the gateway.\n */\nexport type TranscriptionUpdate = {\n policyNumber: string;\n conversationId: string;\n utterance: Utterance;\n};\n\nexport type SdkError = {\n code:\n | \"INVALID_CONFIG\"\n | \"CONNECTION_ERROR\"\n | \"TIMEOUT\"\n | \"SERVER_ERROR\"\n | \"UNEXPECTED_RESPONSE\";\n message: string;\n details?: any;\n};\n\nexport abstract class IAiqaSdk {\n abstract connect(): void;\n abstract disconnect(): void;\n\n abstract on(eventName: string, callback: (...args: any[]) => any): void;\n abstract off(eventName: string, callback?: (...args: any[]) => any): void;\n\n abstract getApplication(): Promise<Application>;\n abstract addFact(fact: ApplicationFactInput): Promise<AddFactResult>;\n abstract flagFact(factId: string): Promise<FlagFactResult>;\n abstract getFacts(): Promise<ApplicationFact[]>;\n abstract setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult>;\n abstract setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult>;\n abstract updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult>;\n}\n","const splitVersion = (value: string) => {\n const [core] = value.split(\"-\", 2);\n return core.split(\".\").map((part) => Number(part));\n};\n\nexport const compareVersions = (left: string, right: string): number => {\n const leftParts = splitVersion(left);\n const rightParts = splitVersion(right);\n const maxLength = Math.max(leftParts.length, rightParts.length);\n\n for (let i = 0; i < maxLength; i += 1) {\n const l = leftParts[i] ?? 0;\n const r = rightParts[i] ?? 0;\n if (l > r) {\n return 1;\n }\n if (l < r) {\n return -1;\n }\n }\n\n return 0;\n};\n","{\n \"name\": \"@aiqa/sdk\",\n \"version\": \"2.1.0-develop.2\",\n \"main\": \"dist/node/node.js\",\n \"module\": \"dist/node/node.js\",\n \"types\": \"dist/node/node.d.ts\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup && node -e \\\"const fs=require('fs');['dist/node/node','dist/browser/browser'].forEach(f=>{const mts=f+'.d.mts';const ts=f+'.d.ts';if(fs.existsSync(mts)){fs.renameSync(mts,ts);}});\\\"\",\n \"commitlint\": \"commitlint\",\n \"dev:node\": \"tsx src/node.ts\",\n \"lint\": \"tsc --noEmit -p tsconfig.json\",\n \"format\": \"prettier --check \\\"{src,tests}/**/*.{ts,tsx,js,json,md,yml,yaml}\\\" \\\"*.{js,json,md,yml,yaml,ts}\\\" --ignore-path .prettierignore\",\n \"release\": \"semantic-release\",\n \"start:node\": \"node dist/node/node.js\",\n \"serve:browser\": \"serve .\",\n \"test\": \"jest\",\n \"prepare\": \"husky\",\n \"lint-staged\": \"lint-staged\"\n },\n \"lint-staged\": {\n \"*.{ts,tsx,js,json,md,yml,yaml}\": [\n \"prettier --write\"\n ]\n },\n \"exports\": {\n \".\": {\n \"node\": {\n \"import\": \"./dist/node/node.js\",\n \"types\": \"./dist/node/node.d.ts\"\n },\n \"browser\": {\n \"import\": \"./dist/browser/browser.js\",\n \"types\": \"./dist/browser/browser.d.ts\"\n },\n \"default\": \"./dist/node/node.js\"\n }\n },\n \"private\": false,\n \"license\": \"MIT\",\n \"author\": \"AIQA\",\n \"description\": \"TypeScript/JavaScript SDK for interacting with the AIQA.\",\n \"keywords\": [\n \"aiqa\",\n \"sdk\"\n ],\n \"files\": [\n \"dist\"\n ],\n \"devDependencies\": {\n \"@commitlint/cli\": \"^20.4.4\",\n \"@commitlint/config-conventional\": \"^20.4.4\",\n \"@jest/globals\": \"^29.7.0\",\n \"@semantic-release/commit-analyzer\": \"^13.0.1\",\n \"@semantic-release/git\": \"^10.0.1\",\n \"@semantic-release/npm\": \"^12.0.2\",\n \"@semantic-release/release-notes-generator\": \"^14.1.0\",\n \"@types/node\": \"^22.0.0\",\n \"conventional-changelog-conventionalcommits\": \"^9.3.0\",\n \"esbuild\": \"^0.23.0\",\n \"husky\": \"^9.1.7\",\n \"jest\": \"^29.7.0\",\n \"lint-staged\": \"^16.4.0\",\n \"prettier\": \"^3.8.1\",\n \"semantic-release\": \"^24.2.9\",\n \"serve\": \"^14.2.3\",\n \"socket.io\": \"^4.7.5\",\n \"ts-jest\": \"^29.2.3\",\n \"ts-node\": \"^10.9.2\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.7.0\"\n },\n \"dependencies\": {\n \"socket.io-client\": \"^4.7.5\"\n }\n}\n"],"mappings":";AAAA,SAAS,UAAkB;;;ACSpB,IAAK,UAAL,kBAAKA,aAAL;AACL,EAAAA,SAAA,kBAAe;AACf,EAAAA,SAAA,eAAY;AACZ,EAAAA,SAAA,qBAAkB;AAClB,EAAAA,SAAA,oBAAiB;AACjB,EAAAA,SAAA,kBAAe;AACf,EAAAA,SAAA,cAAW;AACX,EAAAA,SAAA,eAAY;AACZ,EAAAA,SAAA,8BAA2B;AAC3B,EAAAA,SAAA,+BAA4B;AAC5B,EAAAA,SAAA,yBAAsB;AAVZ,SAAAA;AAAA,GAAA;AAuDL,IAAK,uBAAL,kBAAKC,0BAAL;AACL,EAAAA,sBAAA,QAAK;AACL,EAAAA,sBAAA,QAAK;AACL,EAAAA,sBAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AAqCL,IAAK,uBAAL,kBAAKC,0BAAL;AACL,EAAAA,sBAAA,YAAS;AACT,EAAAA,sBAAA,YAAS;AACT,EAAAA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AAAA,IACF;AACA,aAAS,QAAQ,CAAC,YAAY,QAAQ,GAAG,IAAI,CAAC;AAAA,EAChD;AAAA,EAEQ,kBAAkB;AACxB,WAAO,OAAO,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AAAA,EAClF;AAAA,EAEQ,eAAe,MAAgB;AACrC,WACE,SAAS,uBACT,SAAS,qBACT,SAAS,sBACT,SAAS;AAAA,EAEb;AACF;AAEA,IAAO,iBAAQ;","names":["Methods","ConversationLanguage","FactAnswerFormatType","payload"]}
|
|
1
|
+
{"version":3,"sources":["../../src/shared.ts","../../src/types.ts","../../src/utils/compareVersions.ts","../../package.json"],"sourcesContent":["import { io, Socket } from \"socket.io-client\";\nimport {\n Methods,\n Application,\n ApplicationFact,\n ApplicationFactInput,\n SdkEvent,\n IAiqaSdk,\n AddFactResult,\n FlagFactResult,\n SetConversationProductResult,\n SetConversationLanguageResult,\n UpdateConversationInput,\n UpdateConversationResult,\n ConversationLanguage,\n} from \"./types.js\";\nimport { compareVersions } from \"./utils/compareVersions.js\";\n// @ts-ignore - compiled builds resolve this at build time\nimport pkg from \"../package.json\";\n\nconst SDK_VERSION = (pkg as { version?: string }).version ?? \"0.0.1\";\nconst DEFAULT_URL = \"ws://localhost:3025/ws\";\nconst DEFAULT_TIMEOUT_MS = 60000; // 1 minute\n\nconst RUNTIME: \"browser\" | \"node\" =\n typeof window !== \"undefined\" && typeof window.document !== \"undefined\"\n ? \"browser\"\n : \"node\";\n\nconst USER_AGENT: string =\n RUNTIME === \"browser\"\n ? typeof navigator !== \"undefined\"\n ? navigator.userAgent\n : \"browser/unknown\"\n : typeof process !== \"undefined\"\n ? `node ${process.version} ${process.platform}`\n : \"node/unknown\";\n\nfunction isRequestTimeout(error: unknown, method: Methods): boolean {\n return (\n error instanceof Error &&\n error.message === `Request timed out for ${method}`\n );\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n typeof (value as PromiseLike<unknown>).then === \"function\"\n );\n}\n\n// Fires the trailing ack callback (when present) after delivering the\n// payload to user code. Throws and async rejections are routed to\n// console.error — propagating them would skip subsequent listeners in\n// @socket.io/component-emitter's untryCatched loop.\n//\n// Auto-parses string args as JSON. The backend's broadcast emits\n// (`FACT_VERIFIED`, `TRANSCRIPTION_UPDATED`, `CALL_STATUS_UPDATED`) all\n// send `JSON.stringify(...)` payloads, but `FactVerifiedPayload` and\n// friends are typed as plain objects. Without this parse, a consumer\n// writing `payload.factId` would read a property off a string and get\n// `undefined`. Strings that don't parse (e.g. a primitive event name)\n// pass through unchanged.\nexport function wrapEventHandler(\n callback: (...args: any[]) => any,\n): (...args: any[]) => void {\n return (...args: any[]) => {\n const last = args[args.length - 1];\n const hasAck = typeof last === \"function\";\n const rawPayload = hasAck ? args.slice(0, -1) : args;\n const payload = rawPayload.map((arg) => {\n if (typeof arg !== \"string\") return arg;\n try {\n return JSON.parse(arg);\n } catch {\n return arg;\n }\n });\n try {\n const handlerResult = callback(...payload);\n if (isThenable(handlerResult)) {\n handlerResult.then(undefined, (err) => {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] async event handler rejected:\", err);\n });\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[AiQaSdk] event handler threw:\", err);\n } finally {\n if (hasAck) {\n try {\n last();\n } catch {\n /* swallow */\n }\n }\n }\n };\n}\n\nclass AiQaSdk implements IAiqaSdk {\n socket: Socket | null = null;\n url: string;\n applicationId: string;\n applicationSecretKey: string;\n cachedApplication?: Application;\n internalListeners: Map<SdkEvent, Set<(...args: any[]) => void>>;\n internalEvents: Set<SdkEvent>;\n // event → originalCallback → Set<wrappedCallback> registered on\n // socket.io. A Set per (event, callback) so that subscribing the\n // same fn twice registers two wrappers and two off() calls clear\n // both.\n private wrappersByEvent: Map<\n SdkEvent,\n Map<(...args: any[]) => any, Set<(...args: any[]) => void>>\n > = new Map();\n\n constructor(applicationId: string, applicationSecret: string, url?: string) {\n this.url = url ?? DEFAULT_URL;\n this.internalListeners = new Map();\n this.internalEvents = new Set([\"authenticated\"]);\n\n if (applicationId && applicationSecret) {\n this.applicationId = applicationId;\n this.applicationSecretKey = applicationSecret;\n } else {\n throw new Error(\"Application id and application secret are required\");\n }\n }\n\n on(name: SdkEvent, callback: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!this.internalListeners.has(name)) {\n this.internalListeners.set(name, new Set());\n }\n this.internalListeners.get(name)!.add(callback);\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.on(name, callback);\n } else {\n const wrapped = wrapEventHandler(callback);\n let wrappersByCallback = this.wrappersByEvent.get(name);\n if (!wrappersByCallback) {\n wrappersByCallback = new Map();\n this.wrappersByEvent.set(name, wrappersByCallback);\n }\n let wrappers = wrappersByCallback.get(callback);\n if (!wrappers) {\n wrappers = new Set();\n wrappersByCallback.set(callback, wrappers);\n }\n wrappers.add(wrapped);\n this.socket.on(name, wrapped);\n }\n }\n\n off(name: SdkEvent, callback?: (...args: any[]) => any) {\n if (this.internalEvents.has(name)) {\n if (!callback) {\n this.internalListeners.delete(name);\n return;\n }\n const handlers = this.internalListeners.get(name);\n if (handlers) {\n handlers.delete(callback);\n if (handlers.size === 0) {\n this.internalListeners.delete(name);\n }\n }\n return;\n }\n\n if (!this.socket) {\n throw new Error(\"Not connected\");\n }\n\n if (this.isManagerEvent(name)) {\n this.socket.io.off(name, callback);\n return;\n }\n\n if (!callback) {\n this.socket.off(name);\n this.wrappersByEvent.delete(name);\n return;\n }\n\n const wrappersByCallback = this.wrappersByEvent.get(name);\n const wrappers = wrappersByCallback?.get(callback);\n if (wrappers && wrappers.size > 0) {\n const wrapped = wrappers.values().next().value as (\n ...args: any[]\n ) => void;\n wrappers.delete(wrapped);\n this.socket.off(name, wrapped);\n if (wrappers.size === 0) {\n wrappersByCallback!.delete(callback);\n if (wrappersByCallback!.size === 0) {\n this.wrappersByEvent.delete(name);\n }\n }\n } else {\n this.socket.off(name, callback);\n }\n }\n\n connect() {\n if (!this.url) {\n return;\n }\n\n const url = new URL(this.url);\n\n const socketOptions: any = {\n reconnectionDelayMax: 10000,\n path: url.pathname,\n // WebSocket only, skipping engine.io's default HTTP long-polling phase.\n // Some embedders sit behind proxies/security gateways that duplicate the\n // polling GETs across a fleet; the concurrent polls violate engine.io's\n // one-inflight-poll-per-session rule and tear the session down, so every\n // poll then returns \"Session ID unknown\" (HTTP 400) and the client never\n // authenticates. A single WebSocket has no repeated requests to duplicate.\n transports: [\"websocket\"],\n };\n\n this.socket = io(url.origin, socketOptions);\n\n this.socket.on(\"connect\", () => {\n this.authenticate();\n });\n\n this.socket.on(\n \"app_version\",\n wrapEventHandler((payload: any) => {\n const minVersion = payload?.min;\n const maxVersion = payload?.max;\n\n if (minVersion || maxVersion) {\n const tooLow = minVersion\n ? compareVersions(SDK_VERSION, minVersion) < 0\n : false;\n const tooHigh = maxVersion\n ? compareVersions(SDK_VERSION, maxVersion) > 0\n : false;\n if (tooLow || tooHigh) {\n const error = new Error(\n `SDK version ${SDK_VERSION} is not supported. Supported range: ${minVersion || \"-\"} to ${maxVersion || \"-\"}.`,\n );\n this.socket!.disconnect();\n this.socket!.emit(\"error\", error);\n }\n }\n }),\n );\n }\n\n disconnect() {\n if (this.socket) {\n this.socket.disconnect();\n }\n this.wrappersByEvent.clear();\n }\n\n sendMessage(method: Methods, data?: any): Promise<any> {\n return new Promise((resolve, reject) => {\n if (!this.socket || !this.socket.connected) {\n reject(new Error(\"Socket is not connected\"));\n return;\n }\n\n const requestId = this.createRequestId();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const handler = (payload: any) => {\n if (timeout) {\n clearTimeout(timeout);\n }\n this.socket!.off(requestId, handler);\n let parsed = payload;\n if (typeof payload === \"string\") {\n try {\n parsed = JSON.parse(payload);\n } catch (error) {\n parsed = payload;\n }\n }\n\n if (parsed && parsed.error !== undefined) {\n reject(parsed.error);\n return;\n }\n\n // Return the full parsed envelope. Every caller below\n // (addFact, getFacts, flagFact, set*) already does its own\n // `result.data !== undefined ? result.data : result` unwrap,\n // so removing the unwrap here is behaviourally a no-op for\n // them — but it exposes top-level envelope fields like\n // `verification_status` to addFact() so the terminal\n // resolution can carry them alongside the inner data block.\n resolve(parsed);\n };\n\n this.socket.on(requestId, handler);\n\n const payload =\n data && typeof data === \"object\"\n ? { ...data, requestId }\n : { requestId, data };\n this.socket.emit(method, JSON.stringify(payload));\n\n timeout = setTimeout(() => {\n this.socket!.off(requestId, handler);\n reject(new Error(`Request timed out for ${method}`));\n }, DEFAULT_TIMEOUT_MS);\n });\n }\n\n async getApplication(): Promise<Application> {\n try {\n const result = await this.sendMessage(Methods.GET_APPLICATION);\n const application =\n result && result.data !== undefined ? result.data : result;\n if (application && application.application_id !== undefined) {\n return application;\n }\n throw new Error(\"GET_APPLICATION returned no application\");\n } catch (error) {\n // Only a server that predates GET_APPLICATION is worth absorbing: it\n // never answers, so the request can only end in a timeout. Anything else\n // — a rejected request, a dropped socket, a server-side failure — is a\n // real error, and swallowing it would hand back the authentication\n // snapshot as though it were live.\n if (!isRequestTimeout(error, Methods.GET_APPLICATION)) {\n throw error;\n }\n }\n\n // Never overwritten by this method, so it stays the snapshot taken at\n // authentication: identity fields only, no `verification`. That absence is\n // the signal the caller reads — a stale summary would be indistinguishable\n // from a live one.\n if (this.cachedApplication) {\n return this.cachedApplication;\n }\n throw new Error(\n \"Application is not available yet. Wait for authentication to complete.\",\n );\n }\n\n async getFacts(): Promise<ApplicationFact[]> {\n const result = await this.sendMessage(Methods.GET_FACTS);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async addFact(fact: ApplicationFactInput): Promise<AddFactResult> {\n const payload = {\n ...fact,\n critical: fact.critical ?? false,\n is_skipped: fact.is_skipped ?? false,\n };\n const result = await this.sendMessage(Methods.ADD_FACT, payload);\n if (!result) return result;\n const inner = result.data !== undefined ? result.data : result;\n\n // Older backends emit only `data` (or even a primitive like\n // `true`). New backends emit a `FactVerifiedResponseDto` envelope\n // carrying `verification_status` / `matched_components` /\n // `missing_components` at the top level ALONGSIDE the inner\n // `FactVerifiedDataDto`. Merge the envelope onto the resolved\n // value so callers awaiting addFact() see the full terminal\n // shape without subscribing to the broadcast `FACT_VERIFIED`\n // event. Skip the merge when the envelope is absent OR when inner\n // is not an object — spreading a primitive (`{ ...true }`) would\n // silently turn the resolution into `{}`.\n const hasEnvelope =\n result.verification_status !== undefined ||\n result.matched_components !== undefined ||\n result.missing_components !== undefined;\n if (!hasEnvelope || typeof inner !== \"object\" || inner === null) {\n return inner;\n }\n const merged = { ...inner } as AddFactResult;\n if (result.verification_status !== undefined) {\n merged.verification_status = result.verification_status;\n }\n if (result.matched_components !== undefined) {\n merged.matched_components = result.matched_components;\n }\n if (result.missing_components !== undefined) {\n merged.missing_components = result.missing_components;\n }\n return merged;\n }\n\n async flagFact(factId: string): Promise<FlagFactResult> {\n const result = await this.sendMessage(Methods.FLAG_FACT, {\n factId,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_PRODUCT, {\n product,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult> {\n const result = await this.sendMessage(Methods.SET_CONVERSATION_LANGUAGE, {\n language,\n });\n return result && result.data !== undefined ? result.data : result;\n }\n\n async updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult> {\n const result = await this.sendMessage(Methods.UPDATE_CONVERSATION, input);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async authenticate(): Promise<void> {\n try {\n const result = await this.sendMessage(Methods.AUTHENTICATE, {\n applicationId: this.applicationId,\n applicationSecretKey: this.applicationSecretKey,\n sdkVersion: SDK_VERSION,\n runtime: RUNTIME,\n userAgent: USER_AGENT,\n });\n\n const application =\n result && result.data !== undefined ? result.data : result;\n\n this.cachedApplication = application;\n\n this.emitInternal(\"authenticated\", application);\n } catch (error) {\n this.socket!.emit(\"error\", error);\n }\n }\n\n async startRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.START_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async stopRecording(): Promise<boolean> {\n const result = await this.sendMessage(Methods.STOP_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n async isRecordingNow(): Promise<boolean> {\n // @TODO: track it from the server, should be sent on successfull connect\n const result = await this.sendMessage(Methods.IS_RECORDING);\n return result && result.data !== undefined ? result.data : result;\n }\n\n private emitInternal(name: SdkEvent, ...args: any[]) {\n const handlers = this.internalListeners.get(name);\n if (!handlers) {\n return;\n }\n handlers.forEach((handler) => handler(...args));\n }\n\n private createRequestId() {\n return `req_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n }\n\n private isManagerEvent(name: SdkEvent) {\n return (\n name === \"reconnect_attempt\" ||\n name === \"reconnect_error\" ||\n name === \"reconnect_failed\" ||\n name === \"error\"\n );\n }\n}\n\nexport default AiQaSdk;\n","/**\n * Rolled-up verdict over the *answers*: `critical_errors` if any critical fact\n * failed, otherwise `errors` if any fact failed, otherwise `no_errors`.\n * Questions that were never asked do not raise it, so a call where everything\n * was skipped and nothing was wrong reads `no_errors`.\n *\n * Distinct from the per-fact `VerificationStatus` — this one describes the\n * call, not an answer.\n */\nexport type ApplicationVerificationStatus =\n | \"no_errors\"\n | \"errors\"\n | \"critical_errors\";\n\n/** Verification tally for the application at the moment it was requested. */\nexport type ApplicationVerificationSummary = {\n status: ApplicationVerificationStatus;\n /** Facts whose answer did not match the expected one. */\n count_errors: number;\n /** Subset of `count_errors` whose question is marked critical. */\n count_critical_errors: number;\n /**\n * Facts on the application, full stop — verdict or not. Not a pass count and\n * not a count of what has been evaluated: `count_not_asked` and\n * `count_pending` are subsets of it, not separate buckets.\n */\n count_total: number;\n /** Facts with a verdict of never-asked. Excludes the still-pending ones. */\n count_not_asked: number;\n /** Subset of `count_not_asked` whose question is marked critical. */\n count_critical_not_asked: number;\n /**\n * Facts still awaiting a verdict — added, but not resolved yet. During a live\n * call most facts sit here, and they drain into the other counters as the\n * call proceeds.\n */\n count_pending: number;\n /** Facts the conduct review flagged; a matched fact can still be suspicious. */\n count_suspicious: number;\n};\n\nexport type Application = {\n application_id: string;\n client_name: string;\n client_phone_number: string;\n agent_id: string;\n agent_first_name: string;\n agent_last_name: string;\n /**\n * Absent only when the server predates this field, in which case\n * `getApplication()` served its cached authentication snapshot. Treat the\n * absence as \"no live data\", never as a zeroed summary.\n */\n verification?: ApplicationVerificationSummary;\n};\n\nexport enum Methods {\n AUTHENTICATE = \"AUTHENTICATE\",\n GET_FACTS = \"GET_FACTS\",\n GET_APPLICATION = \"GET_APPLICATION\",\n START_RECORDING = \"START_RECORDING\",\n STOP_RECORDING = \"STOP_RECORDING\",\n IS_RECORDING = \"IS_RECORDING\",\n ADD_FACT = \"ADD_FACT\",\n FLAG_FACT = \"FLAG_FACT\",\n SET_CONVERSATION_PRODUCT = \"SET_CONVERSATION_PRODUCT\",\n SET_CONVERSATION_LANGUAGE = \"SET_CONVERSATION_LANGUAGE\",\n UPDATE_CONVERSATION = \"UPDATE_CONVERSATION\",\n}\n\nexport type SetConversationProductResult = {\n success: boolean;\n product: string;\n};\n\nexport type SetConversationLanguageResult = {\n success: boolean;\n language: string;\n};\n\nexport type UpdateConversationInput = {\n policyNumber?: string;\n insuredPhone?: string;\n clientName?: string;\n clientPhone?: string;\n clientEmail?: string;\n clientId?: string;\n agentId?: string;\n agentName?: string;\n advisorId?: string;\n advisorName?: string;\n agentGroups?: string[];\n};\n\n/** Echo of the patched subset — only the fields you sent come back. */\nexport type UpdateConversationResult = {\n success: boolean;\n conversation: {\n policy_number?: string;\n insured_phone?: string;\n client_name?: string;\n client_phone?: string;\n client_email?: string;\n client_id?: string;\n agent_id?: string;\n agent_name?: string;\n advisor_id?: string;\n advisor_name?: string;\n agent_groups?: string[];\n };\n};\n\nexport enum ConversationLanguage {\n EN = \"en\",\n ES = \"es\",\n FR = \"fr\",\n}\n\nexport type SdkEvent =\n | Methods\n | \"connect\"\n | \"disconnect\"\n | \"close\"\n | \"error\"\n | \"reconnect_attempt\"\n | \"reconnect_error\"\n | \"reconnect_failed\"\n | \"authenticated\"\n | \"app_version\"\n // Broadcast channel for every server-side verification event,\n // non-terminal OR terminal. Subscribe with\n // `sdk.on(\"FACT_VERIFIED\", cb)` to receive progress\n // (`awaiting_question`, `awaiting_answer`, `partial`,\n // `pending_confirmation_matched`, `pending_confirmation_unmatched`)\n // alongside the terminal (`matched`, `unmatched`)\n // verdicts. `addFact()`'s Promise resolves only on the terminal —\n // this event stream is the way to render progress.\n | \"FACT_VERIFIED\"\n // Broadcast channel for every persisted utterance, real-time.\n // Subscribe with `sdk.on(\"TRANSCRIPTION_UPDATED\", cb)` to receive\n // `TranscriptionUpdate` payloads as transcripts land.\n | \"TRANSCRIPTION_UPDATED\";\n\nexport enum FactAnswerFormatType {\n string = \"STRING\",\n number = \"NUMBER\",\n integer = \"INT\",\n float = \"FLOAT\",\n bool = \"BOOL\",\n list = \"LIST\",\n strict = \"STRICT\",\n single_choice = \"SINGLE_CHOICE\",\n multiple_choices = \"MULTIPLE_CHOICES\",\n}\n\nexport type ApplicationFactAnswerChoice = {\n key: string;\n text: string;\n};\n\nexport type ApplicationFactAnswerFormat = {\n type: FactAnswerFormatType;\n choices?: ApplicationFactAnswerChoice[];\n};\n\nexport type ApplicationFactInput = {\n id: string;\n /**\n * Stable identifier for the underlying question, shared across applications and\n * conversations. When provided it is used to look up (or create) the matching\n * question row in the database instead of `id`. Keep this consistent across\n * calls — accuracy improvements and remaps configured in the management\n * dashboard are scoped per `questionId`.\n */\n questionId?: string;\n question: string;\n expected_answer: any;\n answer_format: ApplicationFactAnswerFormat;\n\n category_id?: string;\n category_name?: string;\n language?: string;\n\n critical?: boolean;\n is_skipped?: boolean;\n metadata?: Record<string, string>;\n};\n\nexport type QuestionStatus = \"searching\" | \"asked\" | \"not_asked\";\n\n/**\n * Per-fact verification state.\n *\n * Extended from the original three-state shape to carry progress signals\n * the backend already detects but previously could not express. Consumers\n * that switch on this value MUST treat unknown strings as \"processing\"\n * (default fall-through) so older SDK builds keep working after the\n * backend starts emitting the additive states.\n *\n * Semantics:\n * - `processing` generic, just queued or transcription not ready\n * - `awaiting_question` agent hasn't asked the question yet\n * - `awaiting_answer` question asked, customer hasn't answered yet\n * - `partial` partial evidence; backend still working on it\n * - `pending_confirmation_matched` backend has a matching answer but is\n * holding a settling window for mid-answer\n * clarifications (e.g. spellings, \"I mean…\");\n * resolves to `matched`/`unmatched`\n * - `pending_confirmation_unmatched` same as above but the held verdict is\n * `unmatched`; UI can show \"we heard X but it\n * doesn't match, waiting to confirm\" instead\n * of a hard red verdict\n * - `matched` terminal: answer matched expected\n * - `unmatched` terminal: budget exhausted with no match\n */\nexport type VerificationStatus =\n | \"processing\"\n | \"awaiting_question\"\n | \"awaiting_answer\"\n | \"partial\"\n | \"pending_confirmation_matched\"\n | \"pending_confirmation_unmatched\"\n | \"matched\"\n | \"unmatched\";\n\nexport type ApplicationFact = ApplicationFactInput & {\n ai_answer?: any;\n question_status: QuestionStatus;\n verification_status: VerificationStatus;\n /** True once `flagFact(factId)` has been called for this fact. */\n flagged: boolean;\n};\n\nexport interface AddFactResult {\n /** Conversation the fact was attached to. Useful for cross-fact correlation in agent UIs. */\n conversation_id?: string;\n /** Echo of the original question text from the fact input. */\n question?: string;\n /** Echo of the resolved `answer_format.type` (e.g. \"STRING\", \"NUMBER\", \"SINGLE_CHOICE\"). */\n answer_type?: string;\n agent_answer?: string;\n ai_answer?: string;\n is_valid_answer: boolean;\n question_asked?: boolean;\n /**\n * 0–1 (or 0–100 — scale matches the configured similarity method).\n * Similarity between the agent's utterance and the expected question.\n * Renamed from `match_score` to disambiguate from the answer-side score.\n */\n question_match_score?: number;\n /**\n * 0–1 score derived from how well the customer's answer matched expected.\n * Derived from partial-match heuristics (numeric-prefix ratio,\n * matched-components ratio). Undefined when no partial signal exists,\n * or on older server versions.\n */\n answer_match_score?: number;\n metadata?: Record<string, string>;\n /**\n * Top-level state at terminal resolution. Always one of `matched`\n * or `unmatched` because the `addFact()` Promise only\n * resolves on terminals. Optional for compatibility with older\n * server versions.\n */\n verification_status?: VerificationStatus;\n /**\n * Component labels describing which parts of the expected answer\n * matched. Currently `[\"prefix\"]` / `[\"suffix\"]` for numeric facts;\n * treat the set as open-ended.\n */\n matched_components?: string[];\n missing_components?: string[];\n}\n\n/**\n * Payload of the `FACT_VERIFIED` broadcast event.\n *\n * Fires on EVERY state transition the server produces —\n * non-terminal (`partial`, `awaiting_question`, `awaiting_answer`,\n * `pending_confirmation_matched`, `pending_confirmation_unmatched`,\n * `processing`) AND terminal (`matched`, `unmatched`).\n *\n * Subscribe with:\n * sdk.on(\"FACT_VERIFIED\", (payload: FactVerifiedPayload) => {...});\n *\n * `addFact()`'s Promise resolves only on terminals; this event stream\n * is the channel for rendering live progress in the agent UI.\n */\nexport interface FactVerifiedPayload {\n factId: string;\n success: boolean;\n verification_status?: VerificationStatus;\n question_match_score?: number;\n answer_match_score?: number;\n matched_components?: string[];\n missing_components?: string[];\n /**\n * Inner data payload. Shape matches `AddFactResult` (minus the\n * top-level envelope fields) so consumers can reuse the same\n * rendering code for the terminal addFact() resolution and the\n * broadcast event.\n */\n data?: AddFactResult;\n error?: string;\n}\n\nexport type FlagFactResult = {\n success: boolean;\n};\n\n/**\n * Coarse dialog-act label classified server-side. Advisory only — do\n * not gate production behaviour on this value; it is a best-effort\n * categorical guess, paired with a separate `dialog_act_confidence`\n * band.\n */\nexport type DialogAct =\n | \"question\"\n | \"answer\"\n | \"acknowledgement\"\n | \"filler\"\n | \"other\";\n\n/**\n * Categorical confidence band for `dialog_act` ONLY. Named distinctly\n * from the numeric STT `confidence` field on the same utterance — the\n * two are unrelated, so do not compare or conflate them.\n */\nexport type DialogActConfidence = \"high\" | \"medium\" | \"low\";\n\n/**\n * Persisted utterance shape, sent over the wire by the\n * `TRANSCRIPTION_UPDATED` broadcast.\n *\n * The 7 classification fields are all optional because utterances\n * persisted by older server versions lack them.\n * Treat any missing or nullish value as \"unknown\" — NOT as a deliberate\n * negative signal. `is_ivr_filler_candidate === false` in particular\n * does NOT round-trip through `undefined`, so consumer logic that wants\n * \"definitely not a filler\" must check `=== false` after confirming the\n * field is present.\n */\nexport type Utterance = {\n /** UUIDv7 — chronologically sortable. Use `id` (NOT `order`) for sorting. */\n id: string;\n call_id: number;\n /**\n * Reserved — currently always 0. Do not use for sorting; sort by `id`\n * (UUIDv7) instead.\n */\n order: number;\n is_agent: boolean | null;\n speaker: number;\n text: string;\n text_en: string | null;\n start_time: number;\n end_time: number;\n dialog_act?: DialogAct;\n dialog_act_confidence?: DialogActConfidence;\n confidence?: number | null;\n top_alt_margin?: number | null;\n is_ivr_filler_candidate?: boolean;\n spoken_digits_normalized?: string | null;\n vendor?: string | null;\n};\n\n/**\n * Payload of the `TRANSCRIPTION_UPDATED` broadcast event. Mirrors\n * `TranscriptionUpdateResponseDto` on the gateway.\n */\nexport type TranscriptionUpdate = {\n policyNumber: string;\n conversationId: string;\n utterance: Utterance;\n};\n\nexport type SdkError = {\n code:\n | \"INVALID_CONFIG\"\n | \"CONNECTION_ERROR\"\n | \"TIMEOUT\"\n | \"SERVER_ERROR\"\n | \"UNEXPECTED_RESPONSE\";\n message: string;\n details?: any;\n};\n\nexport abstract class IAiqaSdk {\n abstract connect(): void;\n abstract disconnect(): void;\n\n abstract on(eventName: string, callback: (...args: any[]) => any): void;\n abstract off(eventName: string, callback?: (...args: any[]) => any): void;\n\n abstract getApplication(): Promise<Application>;\n abstract addFact(fact: ApplicationFactInput): Promise<AddFactResult>;\n abstract flagFact(factId: string): Promise<FlagFactResult>;\n abstract getFacts(): Promise<ApplicationFact[]>;\n abstract setConversationProduct(\n product: string,\n ): Promise<SetConversationProductResult>;\n abstract setConversationLanguage(\n language: ConversationLanguage,\n ): Promise<SetConversationLanguageResult>;\n abstract updateConversation(\n input: UpdateConversationInput,\n ): Promise<UpdateConversationResult>;\n}\n","const splitVersion = (value: string) => {\n const [core] = value.split(\"-\", 2);\n return core.split(\".\").map((part) => Number(part));\n};\n\nexport const compareVersions = (left: string, right: string): number => {\n const leftParts = splitVersion(left);\n const rightParts = splitVersion(right);\n const maxLength = Math.max(leftParts.length, rightParts.length);\n\n for (let i = 0; i < maxLength; i += 1) {\n const l = leftParts[i] ?? 0;\n const r = rightParts[i] ?? 0;\n if (l > r) {\n return 1;\n }\n if (l < r) {\n return -1;\n }\n }\n\n return 0;\n};\n","{\n \"name\": \"@aiqa/sdk\",\n \"version\": \"2.1.0-develop.4\",\n \"main\": \"dist/node/node.js\",\n \"module\": \"dist/node/node.js\",\n \"types\": \"dist/node/node.d.ts\",\n \"engines\": {\n \"node\": \">=18\"\n },\n \"scripts\": {\n \"build\": \"tsup && node -e \\\"const fs=require('fs');['dist/node/node','dist/browser/browser'].forEach(f=>{const mts=f+'.d.mts';const ts=f+'.d.ts';if(fs.existsSync(mts)){fs.renameSync(mts,ts);}});\\\"\",\n \"commitlint\": \"commitlint\",\n \"dev:node\": \"tsx src/node.ts\",\n \"lint\": \"tsc --noEmit -p tsconfig.json\",\n \"format\": \"prettier --check \\\"{src,tests}/**/*.{ts,tsx,js,json,md,yml,yaml}\\\" \\\"*.{js,json,md,yml,yaml,ts}\\\" --ignore-path .prettierignore\",\n \"release\": \"semantic-release\",\n \"start:node\": \"node dist/node/node.js\",\n \"serve:browser\": \"serve .\",\n \"test\": \"jest\",\n \"prepare\": \"husky\",\n \"lint-staged\": \"lint-staged\"\n },\n \"lint-staged\": {\n \"*.{ts,tsx,js,json,md,yml,yaml}\": [\n \"prettier --write\"\n ]\n },\n \"exports\": {\n \".\": {\n \"node\": {\n \"import\": \"./dist/node/node.js\",\n \"types\": \"./dist/node/node.d.ts\"\n },\n \"browser\": {\n \"import\": \"./dist/browser/browser.js\",\n \"types\": \"./dist/browser/browser.d.ts\"\n },\n \"default\": \"./dist/node/node.js\"\n }\n },\n \"private\": false,\n \"license\": \"MIT\",\n \"author\": \"AIQA\",\n \"description\": \"TypeScript/JavaScript SDK for interacting with the AIQA.\",\n \"keywords\": [\n \"aiqa\",\n \"sdk\"\n ],\n \"files\": [\n \"dist\"\n ],\n \"devDependencies\": {\n \"@commitlint/cli\": \"^20.4.4\",\n \"@commitlint/config-conventional\": \"^20.4.4\",\n \"@jest/globals\": \"^29.7.0\",\n \"@semantic-release/commit-analyzer\": \"^13.0.1\",\n \"@semantic-release/git\": \"^10.0.1\",\n \"@semantic-release/npm\": \"^12.0.2\",\n \"@semantic-release/release-notes-generator\": \"^14.1.0\",\n \"@types/node\": \"^22.0.0\",\n \"conventional-changelog-conventionalcommits\": \"^9.3.0\",\n \"esbuild\": \"^0.23.0\",\n \"husky\": \"^9.1.7\",\n \"jest\": \"^29.7.0\",\n \"lint-staged\": \"^16.4.0\",\n \"prettier\": \"^3.8.1\",\n \"semantic-release\": \"^24.2.9\",\n \"serve\": \"^14.2.3\",\n \"socket.io\": \"^4.7.5\",\n \"ts-jest\": \"^29.2.3\",\n \"ts-node\": \"^10.9.2\",\n \"tsup\": \"^8.0.0\",\n \"tsx\": \"^4.0.0\",\n \"typescript\": \"^5.7.0\"\n },\n \"dependencies\": {\n \"socket.io-client\": \"^4.7.5\"\n }\n}\n"],"mappings":";AAAA,SAAS,UAAkB;;;ACwDpB,IAAK,UAAL,kBAAKA,aAAL;AACL,EAAAA,SAAA,kBAAe;AACf,EAAAA,SAAA,eAAY;AACZ,EAAAA,SAAA,qBAAkB;AAClB,EAAAA,SAAA,qBAAkB;AAClB,EAAAA,SAAA,oBAAiB;AACjB,EAAAA,SAAA,kBAAe;AACf,EAAAA,SAAA,cAAW;AACX,EAAAA,SAAA,eAAY;AACZ,EAAAA,SAAA,8BAA2B;AAC3B,EAAAA,S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