@voctiv/agent-sdk 0.2.7 → 0.2.9

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.
Files changed (38) hide show
  1. package/README.md +156 -13
  2. package/dist/define-script.d.ts +7 -334
  3. package/dist/define-script.d.ts.map +1 -1
  4. package/dist/define-script.js +4 -3
  5. package/dist/define-script.js.map +1 -1
  6. package/dist/index.d.ts +10 -5
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/index.js.map +1 -1
  10. package/dist/types/asr-handle.d.ts +23 -10
  11. package/dist/types/asr-handle.d.ts.map +1 -1
  12. package/dist/types/errors.d.ts +19 -0
  13. package/dist/types/errors.d.ts.map +1 -0
  14. package/dist/types/errors.js +3 -0
  15. package/dist/types/errors.js.map +1 -0
  16. package/dist/types/legacy-phrase.d.ts +10 -9
  17. package/dist/types/legacy-phrase.d.ts.map +1 -1
  18. package/dist/types/llm.d.ts +78 -0
  19. package/dist/types/llm.d.ts.map +1 -0
  20. package/dist/types/llm.js +3 -0
  21. package/dist/types/llm.js.map +1 -0
  22. package/dist/types/media-channel.d.ts +32 -567
  23. package/dist/types/media-channel.d.ts.map +1 -1
  24. package/dist/types/mixer.d.ts +40 -9
  25. package/dist/types/mixer.d.ts.map +1 -1
  26. package/dist/types/platform.d.ts +164 -0
  27. package/dist/types/platform.d.ts.map +1 -0
  28. package/dist/types/platform.js +3 -0
  29. package/dist/types/platform.js.map +1 -0
  30. package/dist/types/script-context.d.ts +170 -0
  31. package/dist/types/script-context.d.ts.map +1 -0
  32. package/dist/types/script-context.js +3 -0
  33. package/dist/types/script-context.js.map +1 -0
  34. package/dist/types/sip.d.ts +485 -0
  35. package/dist/types/sip.d.ts.map +1 -0
  36. package/dist/types/sip.js +3 -0
  37. package/dist/types/sip.js.map +1 -0
  38. package/package.json +1 -1
package/README.md CHANGED
@@ -89,7 +89,7 @@ export default defineScript(async ({ channel, logger, context }) => {
89
89
  - `channel.audio` controls TTS, raw playback, pre-synthesis, and mixer queues.
90
90
  - `channel.sip` controls SIP state, pre-answer media, DTMF, hold/mute/hangup, outbound calls, and bridging.
91
91
  - `channel.llm` talks to the Omni LLM backend.
92
- - `channel.events` exposes speech, interrupt, termination, and WS data message observables.
92
+ - `channel.events` exposes speech, interrupt, termination, WS data message, and media error observables.
93
93
  - `channel.textInput` injects synthetic ASR results for tests and debug clients.
94
94
 
95
95
  ## SIP And Pre-Answer Media
@@ -194,7 +194,7 @@ Create ASR with `channel.createAsr(config?)`.
194
194
 
195
195
  ```ts
196
196
  const asr = await channel.createAsr({
197
- vendor: 'Y',
197
+ vendor: 'yandex',
198
198
  name: 'main-yandex-key',
199
199
  language: 'ru-RU',
200
200
  vad: {
@@ -217,19 +217,50 @@ const asr = await channel.createAsr({
217
217
  - `speechStart$` / `speechEnd$`: VAD speech boundaries.
218
218
  - `interrupt$`: barge-in / interrupt events where the host supports them.
219
219
  - `vadProbability$`: normalized VAD probability when available.
220
+ - `error$`: runtime errors from the ASR provider (see [Error Handling](#error-handling)).
220
221
  - `pause()` / `resume()` to stop or resume forwarding new audio frames.
221
222
  - `finalize()` to force the current utterance to flush.
222
223
  - `destroy()` to close connector streams and subscriptions.
223
224
 
224
225
  SIP sessions use the call-level telephony VAD when it is available. WS sessions create one VAD/SmartTurn instance for the socket session on the first `createAsr()` call. Headless sessions return an inert ASR handle with empty observables.
225
226
 
226
- If ASR connector creation fails, SIP/WS return a degraded handle. VAD observables still mirror the channel where possible, but no real STT results are emitted.
227
+ If ASR connector creation fails, SIP/WS return a degraded handle. VAD observables still mirror the channel where possible, but no real STT results are emitted. The creation failure is reported on `channel.events.error$`.
227
228
 
228
229
  ## ASR Credentials And Vendors
229
230
 
230
- `AsrConfig.vendor` is an engine hint, for example `"Y"`, `"D"`, `"yandex"`, or `"neuro_v3"`, resolved by the host vendor alias mapping.
231
+ `AsrConfig.vendor` is an engine hint, for example `"yandex"`, `"deepgram"`, `"azure"`, `"elevenlabs"`, or `"neuro_v3"`, resolved by the host vendor alias mapping.
231
232
 
232
- In Voctiv legacy compatibility mode, ASR credentials can be selected by logic-executor `key_storage.name`:
233
+ ### Direct ASR Vendor Parameters
234
+
235
+ Pass vendor-native credentials and settings directly through `AsrConfig.data`. These values are forwarded to the connector as-is and override any defaults or platform-resolved credentials.
236
+
237
+ ```ts
238
+ const asr = await channel.createAsr({
239
+ vendor: 'azure',
240
+ language: 'ru-RU',
241
+ data: {
242
+ subscription_key: 'your-azure-key',
243
+ region: 'swedencentral',
244
+ },
245
+ });
246
+ ```
247
+
248
+ Each vendor connector accepts its native parameter names:
249
+
250
+ | Vendor | Accepted `data` keys |
251
+ | --- | --- |
252
+ | **Azure** | `subscription_key` or `api_key`, `region` |
253
+ | **Yandex** | `api_key` or `token`, `folder_id` |
254
+ | **ElevenLabs** | `api_key` (or `xi_api_key`), `model` |
255
+ | **Deepgram** | `api_key` |
256
+ | **Google** | `email`, `private_key`, `project_id` |
257
+ | **Whisper** | `url`, `rate`, `toFloat` |
258
+
259
+ All vendors also accept the env-style names (`AZURE_SPEECH_KEY`, `ELEVENLABS_API_KEY`, etc.) for backwards compatibility, but vendor-native names are checked first and are preferred.
260
+
261
+ ### Voctiv Platform ASR Key Selection
262
+
263
+ In Voctiv legacy compatibility mode, ASR credentials can also be selected by logic-executor `key_storage.name`:
233
264
 
234
265
  ```ts
235
266
  const asr = await channel.createAsr({
@@ -238,7 +269,9 @@ const asr = await channel.createAsr({
238
269
  });
239
270
  ```
240
271
 
241
- The runtime looks in `channel.params.authentication_data.legacyAsrKeysByName[name]` for the current dialog agent and company. If `name` is omitted, `channel.params.defaultAsrName` may be used. Vendor-specific overrides go into `data`; primitives are stringified and objects/arrays are JSON-serialized before connector config is built.
272
+ The runtime looks in `channel.params.authentication_data.legacyAsrKeysByName[name]` for the current dialog agent and company. If `name` is omitted, `channel.params.defaultAsrName` may be used.
273
+
274
+ When both `name` (platform key) and explicit `data` are provided, `data` values win — they are applied last and override anything resolved from the platform.
242
275
 
243
276
  ## TTS, Playback, And Mixer Queues
244
277
 
@@ -248,15 +281,22 @@ The runtime looks in `channel.params.authentication_data.legacyAsrKeysByName[nam
248
281
  await channel.audio.say('Please wait while I check that.', {
249
282
  queue: 0,
250
283
  alias: 'main-response',
251
- ttsVendor: 'E',
284
+ ttsVendor: 'elevenlabs',
252
285
  ttsStrategy: 'sentence',
253
286
  ttsConfig: {
254
- voice_id: 'voice-id',
287
+ api_key: 'sk_your-key',
288
+ voice_id: 'bBLRWT6MSWBFAm76ZWXY',
289
+ model_id: 'eleven_turbo_v2_5',
290
+ base_url: 'https://api.eu.residency.elevenlabs.io',
255
291
  output_format: 'pcm_16000',
256
292
  },
257
293
  });
258
294
  ```
259
295
 
296
+ Use full vendor names for `ttsVendor`. Dedicated TTS vendors include `"elevenlabs"`, `"google"`, and `"voctiv"`. The default TTS path can also accept compatible aliases such as `"azure"` or `"neuro_v3"`, depending on how ScriptEngine is configured.
297
+
298
+ Vendor-native parameter names (`api_key`, `voice_id`, `model_id`, `base_url`) are passed directly to the connector and override any platform defaults. See [TTS Credentials And Vendor Parameters](#tts-credentials-and-vendor-parameters) for the full list of accepted keys per vendor.
299
+
260
300
  `channel.audio.play(source, options?)` plays raw audio from a URL/path or a `LegacyPhraseRecord`.
261
301
 
262
302
  ```ts
@@ -301,9 +341,37 @@ channel.audio.stop(2);
301
341
 
302
342
  For sentence-split TTS, queue item aliases are suffixed as `alias-0`, `alias-1`, and so on. Raw `play()` and direct streaming TTS use the alias exactly.
303
343
 
304
- ## TTS Credentials And Saved Phrases
344
+ ## TTS Credentials And Vendor Parameters
305
345
 
306
- In Voctiv legacy compatibility mode, TTS credentials can be selected by `PlayOptions.name` or `ttsConfig.name`.
346
+ ### Direct TTS Vendor Parameters
347
+
348
+ Pass vendor-native credentials and settings directly through `PlayOptions.ttsConfig`. These values are forwarded to the TTS connector as-is and override any defaults or platform-resolved credentials.
349
+
350
+ ```ts
351
+ await channel.audio.say('Hello!', {
352
+ ttsVendor: 'elevenlabs',
353
+ ttsStrategy: 'streaming',
354
+ ttsConfig: {
355
+ api_key: 'sk_your-elevenlabs-key',
356
+ voice_id: 'bBLRWT6MSWBFAm76ZWXY',
357
+ model_id: 'eleven_turbo_v2_5',
358
+ base_url: 'https://api.eu.residency.elevenlabs.io',
359
+ },
360
+ });
361
+ ```
362
+
363
+ Each TTS vendor connector accepts its native parameter names:
364
+
365
+ | Vendor | Accepted `ttsConfig` keys |
366
+ | --- | --- |
367
+ | **ElevenLabs** | `api_key` (or `xi_api_key`), `voice_id`, `model_id` (or `model`), `base_url`, `output_format`, `language_code`, `voice_settings_stability`, `voice_settings_similarity_boost`, `voice_settings_style`, `voice_settings_speed` |
368
+ | **Voctiv** | `url`, `voice_id`, `language`, `emotion`, `speaking_rate`, `chunk_schedule` |
369
+
370
+ All vendors also accept the env-style names (`ELEVENLABS_API_KEY`, `ELEVENLABS_VOICE_ID`, etc.) for backwards compatibility, but vendor-native names are checked first and are preferred.
371
+
372
+ ### Voctiv Platform TTS Key Selection
373
+
374
+ In Voctiv legacy compatibility mode, TTS credentials can also be selected by `PlayOptions.name` or `ttsConfig.name`.
307
375
 
308
376
  ```ts
309
377
  await channel.audio.say('Здравствуйте!', {
@@ -316,11 +384,20 @@ await channel.audio.say('Здравствуйте!', {
316
384
 
317
385
  The runtime looks in `channel.params.authentication_data.legacyTtsKeysByName[name]`. If `name` is omitted, `channel.params.defaultTtsName` may be used.
318
386
 
319
- `legacySavePhrase` stores synthesized audio under the Voctiv record phrase storage root and inserts phrase metadata so it can later be loaded with `platform.getRecords()`.
387
+ When both `name` (platform key) and explicit `ttsConfig` values are provided, `ttsConfig` values win they are applied last and override anything resolved from the platform.
388
+
389
+ `cache` enables TTS result caching for `say()` and `presay()`:
390
+
391
+ - **`cache: true`** — read/write TTS file cache only (Redis + filesystem + DB).
392
+ - **`cache: { phraseName, flag?, language? }`** — TTS cache **plus** persist into Voctiv platform `record_phrase` / `record_phrase_file` so `platform.getRecords()` can retrieve the audio later.
320
393
 
321
394
  ```ts
395
+ // Cache only (no platform persist):
396
+ await channel.audio.say('Hello!', { cache: true });
397
+
398
+ // Cache + persist to platform phrase storage:
322
399
  await channel.audio.say('Welcome back.', {
323
- legacySavePhrase: {
400
+ cache: {
324
401
  phraseName: 'welcome_back',
325
402
  flag: context.flag,
326
403
  language: context.language,
@@ -340,6 +417,72 @@ if (records?.[0]) {
340
417
 
341
418
  This requires legacy compatibility mode, a trusted LE agent id/UUID, TTS cache, and `LEGACY_V3_RECORD_PHRASE_ROOT`.
342
419
 
420
+ ## Error Handling
421
+
422
+ ASR and TTS errors are propagated to the script. Unhandled errors are always logged server-side, but scripts can catch them to react: fall back to a different vendor, notify the caller, or abort the dialog.
423
+
424
+ ### TTS Errors — Promise Rejection
425
+
426
+ `say()` and `play()` reject their promises when TTS/playback fails:
427
+
428
+ ```ts
429
+ try {
430
+ await channel.audio.say('Hello!', {
431
+ ttsVendor: 'elevenlabs',
432
+ ttsConfig: { api_key: 'invalid-key', voice_id: 'abc' },
433
+ });
434
+ } catch (err) {
435
+ logger.error('TTS failed', { error: String(err) });
436
+ await channel.audio.say('Fallback message.'); // try default TTS
437
+ }
438
+ ```
439
+
440
+ ### ASR Errors — `error$` Observable
441
+
442
+ Runtime ASR errors (gRPC disconnect, auth failure, quota exceeded) are emitted on `AsrHandle.error$`:
443
+
444
+ ```ts
445
+ const asr = await channel.createAsr({
446
+ vendor: 'yandex',
447
+ data: { api_key: 'my-key' },
448
+ });
449
+
450
+ asr.error$.subscribe((err) => {
451
+ logger.error('ASR provider error', {
452
+ message: err.message,
453
+ code: err.code,
454
+ vendor: err.vendor,
455
+ });
456
+ });
457
+ ```
458
+
459
+ A degraded handle (returned when connector creation itself failed) has an inert `error$` that never emits — the creation failure is reported on `channel.events.error$` instead.
460
+
461
+ ### Channel Error Stream
462
+
463
+ `channel.events.error$` is a unified stream of all media errors — both ASR and TTS:
464
+
465
+ ```ts
466
+ channel.events.error$.subscribe((err) => {
467
+ logger.warn(`[${err.source}] ${err.message}`, {
468
+ code: err.code,
469
+ vendor: err.vendor,
470
+ });
471
+ });
472
+ ```
473
+
474
+ `MediaError` fields:
475
+
476
+ | Field | Type | Description |
477
+ | --- | --- | --- |
478
+ | `source` | `'asr' \| 'tts' \| 'sip' \| 'channel'` | Which subsystem produced the error. |
479
+ | `message` | `string` | Human-readable description. |
480
+ | `code` | `number?` | HTTP status, gRPC status, or WebSocket close code. |
481
+ | `vendor` | `string?` | Vendor identifier, e.g. `"yandex"`, `"elevenlabs"`, `"azure"`. |
482
+ | `details` | `unknown?` | Arbitrary provider-specific payload. |
483
+
484
+ Subscribing to `error$` is optional. Old scripts that do not subscribe are not affected — the observables simply go unobserved.
485
+
343
486
  ## LLM API
344
487
 
345
488
  `channel.llm` talks to the Omni LLM backend.
@@ -693,5 +836,5 @@ npm run build
693
836
  The package exports only the public SDK entry point:
694
837
 
695
838
  ```ts
696
- import { defineScript, type MediaChannel, type AsrHandle } from '@voctiv/agent-sdk';
839
+ import { defineScript, type MediaChannel, type AsrHandle, type MediaError } from '@voctiv/agent-sdk';
697
840
  ```
@@ -1,335 +1,7 @@
1
- import type { BehaviorSubject, Observable } from 'rxjs';
2
1
  import type { MediaChannel } from './types/media-channel';
3
- import { ScriptLogger } from './types/logger';
4
- import type { NluExtractOptions, NluInferResult } from './types/nlu';
5
- import type { LegacyGetRecordsParams, LegacyPhraseRecord } from './types/legacy-phrase';
6
- /**
7
- * NLU (Natural Language Understanding) API.
8
- *
9
- * Provides intent/entity extraction through the legacy NLU v3 `/infer` endpoint.
10
- * ScriptEngine allows this API when `context.legacyV3Compat` is `true` and NLU
11
- * runtime settings are configured (`NLU_V3_BASE_URL` plus a resolved numeric
12
- * agent id). Calls fail fast with a descriptive error otherwise.
13
- *
14
- * Compatible with logic-executor `nn.extract()` request/response shape.
15
- */
16
- export interface NluScriptApi {
17
- /**
18
- * Extract intents and entities from one user utterance.
19
- *
20
- * The runtime sends `{ phrase, context, agent_id }` to NLU v3. If
21
- * `options.context` is omitted, it serializes the current dialog params
22
- * (`context.dialogParams`, then legacy fallbacks) as the request context.
23
- *
24
- * @param utterance - User input text to analyze.
25
- * @param options - Optional NLU filters and flags. `entities`, `intents`,
26
- * `use_neuro_api`, and `use_synonyms` are forwarded by ScriptEngine.
27
- * @returns Raw parsed JSON response from the NLU `/infer` endpoint.
28
- */
29
- extract(utterance: string, options?: NluExtractOptions): Promise<NluInferResult>;
30
- /**
31
- * Observable wrapper around {@link extract}.
32
- *
33
- * This is not a streaming NLU session: every subscription performs one
34
- * `extract()` call and emits exactly one result or one error.
35
- */
36
- extract$(utterance: string, options?: NluExtractOptions): Observable<NluInferResult>;
37
- }
38
- /**
39
- * First-level **`context`** passed to every **`defineScript`** handler.
40
- *
41
- * Combines **identity** (dialog, script, agent), **telephony** (caller/destination),
42
- * **payload** (**`initialData`** vs **`dialogParams`**), **Voctiv platform** rows (**`dialogEntity`**),
43
- * and **runtime** (**`env$`**, **`runTime`**). The index signature allows extra host-specific keys.
44
- */
45
- export interface ScriptDialogContext {
46
- /** Short language code, e.g. `"ru"`, `"en"`. */
47
- lang: string;
48
- /** Full BCP-47 language tag, e.g. `"ru-RU"`, `"en-US"`. */
49
- language: string;
50
- /** Business flag for routing (e.g. `"default"`, `"vip"`). */
51
- flag: string;
52
- /** Unique dialog identifier (UUID). */
53
- dialogUuid: string;
54
- /** Caller phone number or messaging source ID. */
55
- msisdn: string;
56
- /** Inbound caller ID (same as msisdn for inbound calls). */
57
- callerId: string;
58
- /** Called number (DID / destination for inbound calls). */
59
- destinationNumber: string;
60
- /** Script record ID in the system. */
61
- scriptId: string;
62
- /** Human-readable script name. */
63
- scriptName: string;
64
- /** Agent UUID from Omni platform (links script to an NLU agent). */
65
- agentUuid?: string;
66
- /**
67
- * Numeric NLU agent id used for `platform.nlu.extract()` and legacy DB operations.
68
- *
69
- * Resolved by the server from Omni/LE mapping or env (`NLU_DEFAULT_AGENT_ID` /
70
- * `AGENT_ID`). Client/session params named `agent_id`, `agentId`, `agentUuid`,
71
- * and `agent_uuid` are stripped before context construction and cannot spoof it.
72
- * May be `0` when no agent id is configured; NLU and `platform.call()` will then fail.
73
- */
74
- agentId: number;
75
- /**
76
- * **Snapshot** of dialog/session payload when the script run started.
77
- *
78
- * Shallow copy of the merge **`channelParams` + `sessionParams`** after the server removes
79
- * untrusted keys (e.g. client cannot spoof **`agentUuid`** here). **Do not mutate** — use
80
- * **`dialogParams`** for the live map. Compare with **`dialogParams`** to see what changed
81
- * during the call (if the host updates the live object).
82
- */
83
- initialData: Record<string, unknown>;
84
- /**
85
- * **Live** dialog/session parameter map for this run (same merge as **`initialData`** at start).
86
- *
87
- * The host may add or overwrite keys while the session progresses. For media scripts this
88
- * aligns with {@link import('./types/media-channel').MediaChannel.params} (Omni defaults, route,
89
- * Voctiv platform ASR/TTS: **`defaultAsrName`**, **`defaultTtsName`**, **`asrVendor`**, **`ttsVendor`**,
90
- * **`asrConfig`**, **`ttsConfig`**, **`authentication_data`**, **`legacyAsrKeysByName`** /
91
- * **`legacyTtsKeysByName`**, etc.). **Read/write** according to your integration; scripts should
92
- * treat unknown keys as opaque.
93
- */
94
- dialogParams: Record<string, unknown>;
95
- /** Whether Voctiv platform compatibility mode is active. */
96
- legacyV3Compat: boolean;
97
- /**
98
- * `true` when the script runs without a real media channel (offline / queue / messaging).
99
- *
100
- * In this mode ASR/TTS/audio/SIP operations are inert or synthetic. Use text payloads,
101
- * `platform.nlu`, `platform.messaging`, `platform.call`, `channel.llm`, and `env$`
102
- * for background dialog logic.
103
- */
104
- headless: boolean;
105
- /**
106
- * Persisted dialog environment for this conversation. ScriptEngine converts the
107
- * plain persisted `env` snapshot into this `BehaviorSubject` before invoking the script.
108
- * On the first call the value is `undefined`.
109
- *
110
- * **Read/write only via `env$`:** use `env$.getValue()`, `env$.next(partialOrNext)`, or
111
- * `env$.subscribe(...)`. Do not use a plain `context.env` — it is not provided.
112
- *
113
- * **Persistence:** On script completion (success or error), the runtime snapshots `env$` and
114
- * attaches it to the persisted result; the script return value must not carry env
115
- * (see {@link ScriptResult}).
116
- *
117
- * Session runners decide where that snapshot is stored. In Voctiv platform compatibility
118
- * mode it is used as the LE-style dialog environment.
119
- */
120
- env$?: BehaviorSubject<Record<string, unknown> | undefined>;
121
- /** Raw `dialog` table row from the Voctiv platform database. */
122
- dialogEntity?: Record<string, unknown>;
123
- /** Raw `call` table row from the Voctiv platform database. */
124
- callEntity?: Record<string, unknown>;
125
- /**
126
- * Optional catalog of media keys exposed to the script (Voctiv platform / Omni), e.g. UUIDs or labels
127
- * for UI or logging. **Credentials** still come from **`dialogParams.authentication_data`**
128
- * (and the channel mirror); use **`name`** on {@link import('./types/asr-handle').AsrConfig} /
129
- * {@link import('./types/mixer').PlayOptions} to select **`key_storage.name`** when LE credential maps exist.
130
- */
131
- availableMediaKeys?: string[];
132
- /** Script entry point for routing (e.g. `"on_recall"`, `"on_message_api_received"`). */
133
- entryPoint?: string;
134
- /** Current recall attempt number (starts at 0). */
135
- attempt?: number;
136
- /** Max recall attempts configured for this dialog. */
137
- recallCount?: number;
138
- /** Delay in seconds between recall attempts. */
139
- recallDelay?: number;
140
- /**
141
- * Inbound message that triggered this headless session.
142
- *
143
- * Present for messaging-driven offline runs, commonly with
144
- * `entryPoint === "on_message_api_received"`. The `payload` field is the raw
145
- * provider payload; normalize text defensively because transports may use
146
- * different keys such as `text`, `message`, `body`, or `content`.
147
- */
148
- inboundMessage?: InboundMessage;
149
- /**
150
- * Async-phase execution budget: remaining time, extension pool, {@link ScriptRunTime.extend}.
151
- * Injected by the runtime; absent only in tests or non-standard hosts.
152
- */
153
- runTime?: ScriptRunTime;
154
- /** Opaque NLU runtime config managed by ScriptEngine. */
155
- _nlu?: unknown;
156
- [key: string]: unknown;
157
- }
158
- /**
159
- * Time budget for the script async phase (after VM load). Lets scripts check remaining time
160
- * and request limited extensions (capped by the runtime).
161
- */
162
- export interface ScriptRunTime {
163
- /** Initial budget in ms before any {@link extend}. */
164
- readonly budgetMs: number;
165
- /** Maximum total extra ms grantable across all {@link extend} calls for this session. */
166
- readonly maxExtendMs: number;
167
- /** Milliseconds left until the runtime stops the async script phase. */
168
- remainingMs(): number;
169
- /** Extension quota not yet granted (ms). */
170
- remainingExtendMs(): number;
171
- /**
172
- * Grants up to `requestedMs` additional runtime, limited by remaining extension quota.
173
- * @returns Granted milliseconds (0 if nothing could be granted).
174
- */
175
- extend(requestedMs: number): number;
176
- }
177
- /** Error info attached to {@link ScriptResult} when a script fails. */
178
- export interface ScriptError {
179
- /**
180
- * Machine-readable category, e.g. `script_error`, `script_load_failed`, `time_limit_exceeded`.
181
- */
182
- code: string;
183
- /** Human-readable error description. */
184
- message: string;
185
- /** Stack trace (when available). */
186
- stack?: string;
187
- }
188
- /**
189
- * Value returned by a script function. Only `output` and `error` are valid fields.
190
- * Session state is updated via `context.env$`; the runtime snapshots it separately.
191
- */
192
- export interface ScriptResult {
193
- /** Output data to store in dialog_stats. */
194
- output?: Record<string, unknown>;
195
- /** Error details (auto-populated on script crash, or set manually). */
196
- error?: ScriptError;
197
- }
198
- /**
199
- * Result after the runtime attaches the final `env$` snapshot (Voctiv platform persistence).
200
- * Scripts never construct this type — use {@link ScriptResult} from `defineScript` handlers.
201
- */
202
- export interface PersistedScriptResult extends ScriptResult {
203
- env?: Record<string, unknown>;
204
- }
205
- /** Options for scheduling an outbound call via {@link PlatformApi.call}. */
206
- export interface ScheduleCallOptions {
207
- /** When to place the call. Defaults to now. */
208
- date?: string | Date;
209
- /** Deadline — don't call after this time. */
210
- dateEnd?: string | Date;
211
- /**
212
- * Entry point to pass to the script when the call connects.
213
- *
214
- * Stored in the created call params as `entry_point`.
215
- */
216
- entryPoint?: string;
217
- /**
218
- * Legacy compatibility field for callers that schedule without a current `scriptId`.
219
- *
220
- * ScriptEngine uses this to allow scheduling when the current script id is not
221
- * available. It does not resolve script names or paths from this field.
222
- */
223
- script?: string;
224
- /** Reserved SIP channel/trunk hint. Not used by the default ScriptEngine scheduler. */
225
- channel?: string;
226
- /** How many times to retry on failure. Stored as `recall_count` in call params. */
227
- recallCount?: number;
228
- /** Delay in seconds between retries. Stored as `recall_delay` in call params. */
229
- recallDelay?: number;
230
- /** Entry point to use after a successful call. Stored as `on_success_call`. */
231
- onSuccessCall?: string;
232
- /** Entry point to use after a failed call. Stored as `on_failed_call`. */
233
- onFailedCall?: string;
234
- /** Call priority (higher = processed sooner by dialer). */
235
- priority?: number;
236
- /** Timezone offset passed to the legacy call row as `timeZone`. */
237
- timezone?: number;
238
- /** Extra SIP headers or protocol-level params. Stored as `proto_additional` in call params. */
239
- protoAdditional?: Record<string, string>;
240
- }
241
- /**
242
- * Dialog state API — read and update dialog routing metadata.
243
- *
244
- * Setting `entryPoint` or `result` updates the local value immediately and asks
245
- * the Voctiv platform database to persist the change asynchronously. In worker
246
- * sessions the setter sends an RPC to the main thread; in direct sessions errors
247
- * are logged. There is no awaitable setter, so do not use it for transactional flow.
248
- */
249
- export interface DialogApi {
250
- /** Current script entry point (e.g. `"on_recall"`). Set to change routing for the next call. */
251
- entryPoint: string | undefined;
252
- /** Dialog outcome (e.g. `"done"`, `"busy"`, `"no_answer"`). Set to finalize dialog. */
253
- result: string | undefined;
254
- /** Dialog UUID (read-only). */
255
- readonly uuid: string;
256
- /** Caller msisdn (read-only). */
257
- readonly msisdn: string;
258
- }
259
- /** Options for sending an outbound message via {@link MessagingApi.send}. */
260
- export interface SendMessageOptions {
261
- /** Sender identifier (service id, bot id, or phone number expected by the MA consumer). */
262
- src: string;
263
- /** Recipient identifier (phone number, user id, or channel-specific address). */
264
- destination: string;
265
- /** Text body of the message. When present in legacy mode, it is also mirrored to dialog stats. */
266
- text?: string;
267
- /** URL of an attachment (image, document, etc.). */
268
- attachment?: string;
269
- /** Quick-reply button labels. */
270
- buttons?: string[];
271
- }
272
- /** Inbound message received from an external messaging channel. */
273
- export interface InboundMessage {
274
- /** Sender identifier (who sent the message). */
275
- src: string;
276
- /** Recipient identifier (your service endpoint). */
277
- dst: string;
278
- /** Channel type, e.g. `"api"`. */
279
- channelType: string;
280
- /** Full raw payload from the messaging transport. */
281
- payload: Record<string, unknown>;
282
- }
283
- /**
284
- * Messaging API — send and receive messages through external channels.
285
- *
286
- * Outbound messages are transported via Redis Streams (`ma_send` / `ma_receive`),
287
- * compatible with the old LE messaging architecture. `message$` is currently a
288
- * one-shot replay of the inbound message that started a headless messaging script,
289
- * not a live subscription to all future Redis messages.
290
- */
291
- export interface MessagingApi {
292
- /**
293
- * Send an outbound message.
294
- * Published to Redis stream for delivery by external consumer.
295
- */
296
- send(options: SendMessageOptions): Promise<void>;
297
- /**
298
- * Observable of inbound messages.
299
- * Emits the triggering message when the script is started by an incoming message
300
- * (entry point `on_message_api_received`).
301
- */
302
- readonly message$: Observable<InboundMessage>;
303
- }
304
- /**
305
- * Platform API — Voctiv platform–compatible operations available to scripts.
306
- *
307
- * Provides access to NLU, dialog state management, outbound call scheduling,
308
- * phrase records, and messaging. These operations are legacy-platform backed and
309
- * require `context.legacyV3Compat === true`.
310
- */
311
- export interface PlatformApi {
312
- /** NLU intent/entity extraction API; throws outside legacy V3 compatibility mode. */
313
- readonly nlu: NluScriptApi;
314
- /** Dialog state — read/write entry point and result. */
315
- readonly dialog: DialogApi;
316
- /** Messaging API — send and receive external messages. */
317
- readonly messaging: MessagingApi;
318
- /**
319
- * Schedule an outbound call.
320
- * Creates a record in the `call` table; the dialer picks it up and originates the SIP call.
321
- * @param msisdn - Destination phone number (E.164).
322
- * @param options - Scheduling, routing, and retry options.
323
- */
324
- call(msisdn: string, options?: ScheduleCallOptions): Promise<void>;
325
- /**
326
- * Voctiv platform only: load `record_phrase` / `record_phrase_file` rows from the LE PostgreSQL database
327
- * (same filters as old `RecordPhrase.get_records`). Returns playable phrase record objects.
328
- * Requires numeric `agent_id` on the dialog (params or `NLU_DEFAULT_AGENT_ID`) and
329
- * `LEGACY_V3_RECORD_PHRASE_ROOT` pointing at the phrase file storage root.
330
- */
331
- getRecords?(params: LegacyGetRecordsParams): Promise<LegacyPhraseRecord[]>;
332
- }
2
+ import type { ScriptLogger } from './types/logger';
3
+ import type { ScriptDialogContext, ScriptResult } from './types/script-context';
4
+ import type { PlatformApi } from './types/platform';
333
5
  /**
334
6
  * Top-level context passed to every script function.
335
7
  *
@@ -374,7 +46,8 @@ export type ScriptFn = (ctx: ScriptContext) => void | ScriptResult | Promise<voi
374
46
  * Mark the default export as a typed script entry point (identity wrapper; no runtime transform).
375
47
  *
376
48
  * The host loads this module, invokes the function with {@link ScriptContext}, and persists
377
- * {@link ScriptResult} / {@link ScriptDialogContext.env$} according to Voctiv platform rules.
49
+ * {@link ScriptResult} / {@link import('./types/script-context').ScriptDialogContext.env$}
50
+ * according to Voctiv platform rules.
378
51
  *
379
52
  * @param fn - Handler receiving **`{ channel, logger, context, platform }`**.
380
53
  * - Use **`channel`** for ASR/TTS (see {@link import('./types/asr-handle').AsrConfig.name},
@@ -384,12 +57,12 @@ export type ScriptFn = (ctx: ScriptContext) => void | ScriptResult | Promise<voi
384
57
  *
385
58
  * @example
386
59
  * ```ts
387
- * import { defineScript } from '@lib/scripting-sdk';
60
+ * import { defineScript } from '@voctiv/agent-sdk';
388
61
  *
389
62
  * export default defineScript(async ({ channel, logger, context, platform }) => {
390
63
  * const asr = await channel.createAsr({
391
64
  * name: 'my-yandex-key',
392
- * vendor: 'Y',
65
+ * vendor: 'yandex',
393
66
  * language: 'ru-RU',
394
67
  * });
395
68
  * });
@@ -1 +1 @@
1
- {"version":3,"file":"define-script.d.ts","sourceRoot":"","sources":["../src/define-script.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,UAAU,EAAE,MAAM,MAAM,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC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;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,YAAY,CAAC,EAAE,EAAE,QAAQ,GAAG,QAAQ,CAEnD"}
@@ -5,7 +5,8 @@ exports.defineScript = defineScript;
5
5
  * Mark the default export as a typed script entry point (identity wrapper; no runtime transform).
6
6
  *
7
7
  * The host loads this module, invokes the function with {@link ScriptContext}, and persists
8
- * {@link ScriptResult} / {@link ScriptDialogContext.env$} according to Voctiv platform rules.
8
+ * {@link ScriptResult} / {@link import('./types/script-context').ScriptDialogContext.env$}
9
+ * according to Voctiv platform rules.
9
10
  *
10
11
  * @param fn - Handler receiving **`{ channel, logger, context, platform }`**.
11
12
  * - Use **`channel`** for ASR/TTS (see {@link import('./types/asr-handle').AsrConfig.name},
@@ -15,12 +16,12 @@ exports.defineScript = defineScript;
15
16
  *
16
17
  * @example
17
18
  * ```ts
18
- * import { defineScript } from '@lib/scripting-sdk';
19
+ * import { defineScript } from '@voctiv/agent-sdk';
19
20
  *
20
21
  * export default defineScript(async ({ channel, logger, context, platform }) => {
21
22
  * const asr = await channel.createAsr({
22
23
  * name: 'my-yandex-key',
23
- * vendor: 'Y',
24
+ * vendor: 'yandex',
24
25
  * language: 'ru-RU',
25
26
  * });
26
27
  * });
@@ -1 +1 @@
1
- {"version":3,"file":"define-script.js","sourceRoot":"","sources":["../src/define-script.ts"],"names":[],"mappings":";;AAobA,oCAEC;AA3BD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,SAAgB,YAAY,CAAC,EAAY;IACvC,OAAO,EAAE,CAAC;AACZ,CAAC"}
1
+ {"version":3,"file":"define-script.js","sourceRoot":"","sources":["../src/define-script.ts"],"names":[],"mappings":";;AA2EA,oCAEC;AA5BD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,SAAgB,YAAY,CAAC,EAAY;IACvC,OAAO,EAAE,CAAC;AACZ,CAAC"}