@onereach/step-voice 7.0.45 → 7.0.46-deskphoneintegration.2

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.
@@ -1,10 +1,19 @@
1
1
  import VoiceStep from './voice';
2
- export default class ConferenceDial extends VoiceStep<{
2
+ type ConferenceDialInput = {
3
3
  stayInConference: boolean;
4
4
  sourceConf: string;
5
5
  botNumber: string;
6
6
  headers?: Record<string, string>;
7
7
  hearOnly: boolean;
8
- }> {
8
+ /**
9
+ * Set `true` only on the step instance that dials the desk phone. When true (and `botNumber`
10
+ * trims to a non-empty SIP username), the step records a desk-phone correlation entry on
11
+ * `conference-start` and clears it on `hangup`/`conference-end`. Default `false` — every existing
12
+ * use leaves it absent, so their behavior is unchanged.
13
+ */
14
+ isDeskPhone?: boolean;
15
+ };
16
+ export default class ConferenceDial extends VoiceStep<ConferenceDialInput> {
9
17
  runStep(): Promise<void>;
10
18
  }
19
+ export {};
@@ -3,6 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  const lodash_1 = tslib_1.__importDefault(require("lodash"));
5
5
  const voice_1 = tslib_1.__importDefault(require("./voice"));
6
+ const deskphoneCorrelation_1 = require("./deskphoneCorrelation");
7
+ /** The gate shared by the correlation write and both clears (identical gate + trimmed key). */
8
+ function isDeskPhoneSipUser(data) {
9
+ return data.isDeskPhone === true && lodash_1.default.trim(String(data.botNumber ?? '')) !== '';
10
+ }
6
11
  class ConferenceDial extends voice_1.default {
7
12
  async runStep() {
8
13
  const call = await this.fetchData();
@@ -10,9 +15,27 @@ class ConferenceDial extends voice_1.default {
10
15
  .local(`in/voice/${call.id}`, async (event) => {
11
16
  switch (event.params.type) {
12
17
  case 'hangup':
18
+ if (isDeskPhoneSipUser(this.data)) {
19
+ await (0, deskphoneCorrelation_1.clearDeskphoneConference)(this, this.helpers.providersAccountId, lodash_1.default.trim(String(this.data.botNumber ?? '')));
20
+ }
13
21
  await this.handleHangup(call);
14
22
  return await this.waitConvEnd();
15
23
  case 'conference-start':
24
+ if (isDeskPhoneSipUser(this.data)) {
25
+ const sipUser = lodash_1.default.trim(String(this.data.botNumber ?? ''));
26
+ const owningCall = await this.fetchData();
27
+ const accountId = this.helpers.providersAccountId;
28
+ await (0, deskphoneCorrelation_1.writeDeskphoneConference)(this, accountId, sipUser, {
29
+ accountId,
30
+ room: this.data.sourceConf,
31
+ memberId: event.params.user,
32
+ callerId: owningCall.botNumber,
33
+ callId: owningCall.id,
34
+ callType: owningCall.type,
35
+ callback: owningCall.callback,
36
+ bConvId: this.conversationId
37
+ });
38
+ }
16
39
  if (this.data.stayInConference) {
17
40
  return this.exitFlow();
18
41
  }
@@ -20,6 +43,9 @@ class ConferenceDial extends voice_1.default {
20
43
  return this.exitStep('next', lodash_1.default.omit(event.params, ['type']));
21
44
  }
22
45
  case 'conference-end':
46
+ if (isDeskPhoneSipUser(this.data)) {
47
+ await (0, deskphoneCorrelation_1.clearDeskphoneConference)(this, this.helpers.providersAccountId, lodash_1.default.trim(String(this.data.botNumber ?? '')));
48
+ }
23
49
  return this.data.stayInConference ? this.exitStep('next') : this.exitFlow();
24
50
  case 'error':
25
51
  return this.throwError(event.params.error);
@@ -0,0 +1,52 @@
1
+ import VoiceStep, { CallStartEvent, TODO, VoiceEvent } from './voice';
2
+ import { IEvent } from '@onereach/flow-sdk/dst/types/event';
3
+ import { DeskphoneConferenceEntry } from './deskphoneCorrelation';
4
+ /** The in-flight attended-transfer state machine stashed on `this.state.deskphoneXfer`. */
5
+ interface DeskphoneXferState {
6
+ /** trimmed desk-phone SIP username (the correlation key), e.g. `desk-2001`. */
7
+ fromUser: string;
8
+ /** the correlation entry recorded by Conference Dial at B's join. */
9
+ entry: DeskphoneConferenceEntry;
10
+ /** the transfer target (PSTN C) captured from the consult INVITE `channel.to`. */
11
+ C: string;
12
+ /** the consult-leg call id — delivers the BYE; NOT the command carrier. */
13
+ consultCallId: string;
14
+ /** the LIVE A-leg call id — the completion command carrier + result stream. */
15
+ carrierCallId: string;
16
+ /** completion phase: `await-bye` -> (consult BYE) -> `await-cjoin` -> (C conference-start). */
17
+ phase: 'await-bye' | 'await-cjoin';
18
+ }
19
+ /** Minimal routable envelope for carrying a command on the live A-leg. */
20
+ interface CarrierEnvelope {
21
+ id: string;
22
+ type: string;
23
+ callback: unknown;
24
+ }
25
+ export default class WaitForDeskPhoneCall extends VoiceStep<TODO, TODO, TODO> {
26
+ get conversation(): string | import("@onereach/flow-sdk/types").IMergeField;
27
+ runStep(): Promise<any>;
28
+ onCall(event: IEvent<CallStartEvent>): Promise<any>;
29
+ /**
30
+ * Named waiting state (resolves MEDIUM-1). Re-armed on every entry so the thread parks here across
31
+ * events: the consult-leg BYE surfaces on `in/voice/<consultCallId>`; C's join/list results surface
32
+ * on the A-leg stream `in/voice/<carrierCallId>`. Returns without exitStep/exitFlow so the step
33
+ * stays alive (mirrors Initiate Call.waitForCall).
34
+ */
35
+ awaitConsultComplete(): Promise<void>;
36
+ /** Minimal routable envelope that carries completion commands on the LIVE A-leg. */
37
+ carrierEnvelope(x: DeskphoneXferState): CarrierEnvelope;
38
+ /**
39
+ * Issue a single command on the carrier envelope and resolve with its result payload. The command
40
+ * result surfaces on the armed `in/voice/<carrierCallId>` stream (result routing); `sendCommands`
41
+ * returns it on this build.
42
+ */
43
+ sendCommandsAwait(envelope: CarrierEnvelope, commands: TODO[]): Promise<TODO>;
44
+ onConsultEvent(event: IEvent<VoiceEvent>): Promise<any>;
45
+ /**
46
+ * The ordered completion sequence — every command carried on the LIVE A-leg carrier envelope.
47
+ * No new INVITE toward the phone anywhere; does NOT route through Leave Conference.ts. On any
48
+ * failure before the kick, abort leaving A+B intact and clear nothing.
49
+ */
50
+ completeDeskphoneTransfer(x: DeskphoneXferState): Promise<any>;
51
+ }
52
+ export {};
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ /* eslint-disable
3
+ @typescript-eslint/strict-boolean-expressions,
4
+ @typescript-eslint/explicit-function-return-type,
5
+ @typescript-eslint/no-misused-promises
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ const tslib_1 = require("tslib");
9
+ const voice_1 = tslib_1.__importDefault(require("./voice"));
10
+ const lodash_1 = tslib_1.__importDefault(require("lodash"));
11
+ const deskphoneCorrelation_1 = require("./deskphoneCorrelation");
12
+ const defaultSessionTimeout = 5 * 60 * 1000;
13
+ class WaitForDeskPhoneCall extends voice_1.default {
14
+ get conversation() {
15
+ if (this.step.dataOut == null)
16
+ throw new Error('missing step.dataOut');
17
+ return this.step.dataOut;
18
+ }
19
+ async runStep() {
20
+ const sipUsername = String(this.data.sipUsername ?? '').trim();
21
+ if (sipUsername) {
22
+ this.triggers.on(`in/voice/deskphone/${sipUsername}/call`, this.onCall);
23
+ }
24
+ // Resume guard: a consult is already in flight (persisted across a thread resume) -> go straight
25
+ // back to the waiting state and re-arm the completion listeners (named-state re-arm pattern).
26
+ if (this.state.deskphoneXfer?.carrierCallId) {
27
+ return this.gotoState('awaitConsultComplete');
28
+ }
29
+ }
30
+ async onCall(event) {
31
+ const { asr, tts, endOfInputTimeout } = this.data;
32
+ const accountId = this.helpers.providersAccountId;
33
+ const dialedNumber = event.params.channel.to;
34
+ // Trimming fromUser here is DELIBERATE and REQUIRED for the key match — the breakout emits the
35
+ // key trimmed but surfaces fromUser untrimmed. Do NOT simplify back to the untrimmed form.
36
+ const fromUser = String(event.params.fromUser ?? '').trim();
37
+ const entry = await (0, deskphoneCorrelation_1.readDeskphoneConference)(this, accountId, fromUser);
38
+ const call = {
39
+ headers: event.params.headers,
40
+ // @ts-expect-error
41
+ botNumber: event.params.channel.to ?? 'unknown',
42
+ // For a breakout the "caller" is the desk phone, not an owned bot number.
43
+ // @ts-expect-error
44
+ endUserNumber: fromUser ?? event.params.channel?.from ?? 'unknown',
45
+ ...event.params.channel,
46
+ asr: asr.getSettings(),
47
+ tts: tts.getVoice()
48
+ };
49
+ delete call.from;
50
+ delete call.to;
51
+ call.dialedNumber = dialedNumber;
52
+ call.fromUser = fromUser;
53
+ // Ordinary breakout (no correlation entry) OR cross-account mismatch -> UNCHANGED existing path.
54
+ // A mismatch degrades safely to the ordinary breakout (A+B left intact); it is logged, not thrown.
55
+ if (!entry || entry.accountId !== accountId) {
56
+ if (entry && entry.accountId !== accountId) {
57
+ this.log.warn('deskphone transfer: account mismatch, ordinary breakout', { entryAccountId: entry.accountId, accountId });
58
+ }
59
+ const presetTime = (Number(endOfInputTimeout) || 0) * 60 * 1000;
60
+ const { sessionId: previousSessionId = '', beginningSessionId = '', } = event?.reporting ?? {};
61
+ await this.session.start({
62
+ timeout: presetTime || defaultSessionTimeout,
63
+ reporting: {
64
+ settingsKey: 'session',
65
+ startedBy: 'Visitor',
66
+ sessionType: 'Phone',
67
+ previousSessionId,
68
+ beginningSessionId
69
+ },
70
+ reportingSessions: [{
71
+ previousSessionId,
72
+ beginningSessionId
73
+ }]
74
+ });
75
+ await this.startConversation(call);
76
+ await this.transcript(call, {
77
+ action: 'Call Start',
78
+ reportingSettingsKey: 'transcript',
79
+ actionFromBot: false
80
+ });
81
+ return this.exitStep('trigger');
82
+ }
83
+ // TRANSFER. C = the dialed PSTN target (never the desk phone, never oct25sip).
84
+ // Stash the state machine and transition to the named waiting state (re-arm pattern).
85
+ // Do NOT splice, do NOT startConversation, do NOT arm a mid-handler local + bare return.
86
+ this.state.deskphoneXfer = {
87
+ fromUser,
88
+ entry,
89
+ C: event.params.channel.to,
90
+ consultCallId: call.id,
91
+ carrierCallId: entry.callId,
92
+ phase: 'await-bye'
93
+ };
94
+ return this.gotoState('awaitConsultComplete');
95
+ }
96
+ /**
97
+ * Named waiting state (resolves MEDIUM-1). Re-armed on every entry so the thread parks here across
98
+ * events: the consult-leg BYE surfaces on `in/voice/<consultCallId>`; C's join/list results surface
99
+ * on the A-leg stream `in/voice/<carrierCallId>`. Returns without exitStep/exitFlow so the step
100
+ * stays alive (mirrors Initiate Call.waitForCall).
101
+ */
102
+ async awaitConsultComplete() {
103
+ const { carrierCallId, consultCallId } = this.state.deskphoneXfer;
104
+ this.triggers.local(`in/voice/${carrierCallId}`, this.onConsultEvent);
105
+ this.triggers.local(`in/voice/${consultCallId}`, this.onConsultEvent);
106
+ }
107
+ /** Minimal routable envelope that carries completion commands on the LIVE A-leg. */
108
+ carrierEnvelope(x) {
109
+ return { id: x.carrierCallId, type: x.entry.callType, callback: x.entry.callback };
110
+ }
111
+ /**
112
+ * Issue a single command on the carrier envelope and resolve with its result payload. The command
113
+ * result surfaces on the armed `in/voice/<carrierCallId>` stream (result routing); `sendCommands`
114
+ * returns it on this build.
115
+ */
116
+ async sendCommandsAwait(envelope, commands) {
117
+ return await this.sendCommands(envelope, commands);
118
+ }
119
+ async onConsultEvent(event) {
120
+ const x = this.state.deskphoneXfer;
121
+ if (!x)
122
+ return;
123
+ switch (event.params.type) {
124
+ case 'hangup': {
125
+ // Consult-leg BYE = COMPLETION START. Only act once, while awaiting the BYE.
126
+ if (x.phase !== 'await-bye')
127
+ return;
128
+ x.phase = 'await-cjoin';
129
+ // Dial C into room R on the LIVE A-leg carrier, with the OWNED DID (never oct25sip / SIP user).
130
+ await this.sendCommands(this.carrierEnvelope(x), [{
131
+ name: 'conference.joinBot',
132
+ params: {
133
+ accountId: x.entry.accountId,
134
+ room: x.entry.room,
135
+ botNumber: x.C,
136
+ fromNumber: x.entry.callerId,
137
+ headers: {},
138
+ hearOnly: undefined
139
+ }
140
+ }]);
141
+ // Re-arm and park for C's conference-start on the A-leg stream.
142
+ return this.gotoState('awaitConsultComplete');
143
+ }
144
+ case 'conference-start': {
145
+ // C is in R. Resolve C's member id, un-isolate A<->C, kick B, then clear.
146
+ if (x.phase !== 'await-cjoin')
147
+ return;
148
+ return await this.completeDeskphoneTransfer(x);
149
+ }
150
+ case 'error': {
151
+ this.log.error('deskphone transfer consult/join error; leaving A+B intact', { error: event.params.error });
152
+ return this.exitStep('trigger');
153
+ }
154
+ default:
155
+ return;
156
+ }
157
+ }
158
+ /**
159
+ * The ordered completion sequence — every command carried on the LIVE A-leg carrier envelope.
160
+ * No new INVITE toward the phone anywhere; does NOT route through Leave Conference.ts. On any
161
+ * failure before the kick, abort leaving A+B intact and clear nothing.
162
+ */
163
+ async completeDeskphoneTransfer(x) {
164
+ const envelope = this.carrierEnvelope(x);
165
+ // (1) Resolve C's member id deterministically from the live member list.
166
+ const membersResult = await this.sendCommandsAwait(envelope, [{
167
+ name: 'conference.listMembers',
168
+ params: { accountId: x.entry.accountId, room: x.entry.room }
169
+ }]);
170
+ const members = (membersResult?.members ?? membersResult ?? []);
171
+ const cRow = lodash_1.default.find(members, m => m.to === x.C || m.from === x.C);
172
+ if (!cRow) {
173
+ this.log.error('deskphone transfer: C not found in member list; aborting, A+B intact', { C: x.C, members });
174
+ return this.exitStep('trigger');
175
+ }
176
+ const cMemberId = cRow.id;
177
+ // (2) Clear the consult nohear relation whose SUBJECT is C's member id (NOT B's entry.memberId).
178
+ await this.sendCommands(envelope, [{
179
+ name: 'conference.relate',
180
+ params: { accountId: x.entry.accountId, room: x.entry.room, member: cMemberId, others: 'all', mode: 'clear' }
181
+ }]);
182
+ // (3) Deterministic video-unmute (vmute all off) — the inverse of the join's `vmute all`.
183
+ await this.sendCommands(envelope, [{
184
+ name: 'conference.unvmute',
185
+ params: { accountId: x.entry.accountId, room: x.entry.room, user: 'all' }
186
+ }]);
187
+ // (4) Kick B (desk-2001) by its stored member id.
188
+ await this.sendCommands(envelope, [{
189
+ name: 'conference.kick',
190
+ params: { accountId: x.entry.accountId, room: x.entry.room, user: x.entry.memberId }
191
+ }]);
192
+ // (5) Clear the correlation entry.
193
+ await (0, deskphoneCorrelation_1.clearDeskphoneConference)(this, x.entry.accountId, x.fromUser);
194
+ return this.exitStep('trigger');
195
+ }
196
+ }
197
+ exports.default = WaitForDeskPhoneCall;
@@ -0,0 +1,46 @@
1
+ import { TODO } from './voice';
2
+ /**
3
+ * Correlation entry recorded when the platform dials the desk phone into a conference.
4
+ *
5
+ * Keyed, in the store, by the TRIMMED desk-phone SIP username (e.g. `desk-2001`) so it matches the
6
+ * breakout emit `in/voice/deskphone/${_.trim(variable_sip_from_user)}/call`. The `callId`/`callType`/
7
+ * `callback` fields identify the LIVE A-leg (the conference-owning channel) that carries the
8
+ * completion commands — a hung-up consult leg cannot execute `out/voice` commands — so they are
9
+ * load-bearing, not debug-only.
10
+ */
11
+ export interface DeskphoneConferenceEntry {
12
+ /** `this.helpers.providersAccountId` at write time (the conference-owning flow). */
13
+ accountId: string;
14
+ /** The un-prefixed conference room (Conference Dial's `this.data.sourceConf`). */
15
+ room: string;
16
+ /** desk-2001's (B's) conference member id (`conference-start` `event.params.user`). */
17
+ memberId: string;
18
+ /**
19
+ * OWNED outbound DID to dial C with — the conference-owning `call.botNumber`.
20
+ * NEVER the desk-phone SIP user, NEVER `oct25sip`.
21
+ */
22
+ callerId: string;
23
+ /** conference-owning (A-leg) `call.id` — the completion command CARRIER channel id. */
24
+ callId: string;
25
+ /** conference-owning `call.type` — carrier envelope `type` for `sendCommands`. */
26
+ callType: string;
27
+ /** conference-owning `call.callback` — carrier envelope `callback` for `sendCommands`. */
28
+ callback: unknown;
29
+ /** the conversation id that owns desk-2001's membership (debug/lifecycle). */
30
+ bConvId: string;
31
+ }
32
+ /**
33
+ * Record (or overwrite) the correlation entry for a desk-phone SIP username.
34
+ *
35
+ * Last-write-wins. The get->mutate->set runs within a single awaited critical section; the map is
36
+ * never held across an await to a FreeSWITCH command.
37
+ */
38
+ export declare function writeDeskphoneConference(self: TODO, accountId: string, sipUser: string, entry: DeskphoneConferenceEntry): Promise<void>;
39
+ /** Read the correlation entry for a desk-phone SIP username, or `undefined` if none exists. */
40
+ export declare function readDeskphoneConference(self: TODO, accountId: string, sipUser: string): Promise<DeskphoneConferenceEntry | undefined>;
41
+ /**
42
+ * Delete the correlation entry for a desk-phone SIP username.
43
+ *
44
+ * Idempotent: two concurrent clears converge on absent (the safe terminal state).
45
+ */
46
+ export declare function clearDeskphoneConference(self: TODO, accountId: string, sipUser: string): Promise<void>;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clearDeskphoneConference = exports.readDeskphoneConference = exports.writeDeskphoneConference = void 0;
4
+ /** Fixed, account-scoped thread name both flows compute identically. */
5
+ const THREAD = (accountId) => `deskphone-xfer:${accountId}`;
6
+ /** The single fixed key under which the correlation map lives on that thread. */
7
+ const KEY = 'deskphoneConference';
8
+ /**
9
+ * Record (or overwrite) the correlation entry for a desk-phone SIP username.
10
+ *
11
+ * Last-write-wins. The get->mutate->set runs within a single awaited critical section; the map is
12
+ * never held across an await to a FreeSWITCH command.
13
+ */
14
+ async function writeDeskphoneConference(self, accountId, sipUser, entry) {
15
+ const t = self.process.getSafeThread(THREAD(accountId));
16
+ const map = (await t.get(KEY)) ?? {};
17
+ map[sipUser] = entry;
18
+ await t.set(KEY, map);
19
+ }
20
+ exports.writeDeskphoneConference = writeDeskphoneConference;
21
+ /** Read the correlation entry for a desk-phone SIP username, or `undefined` if none exists. */
22
+ async function readDeskphoneConference(self, accountId, sipUser) {
23
+ const t = self.process.getSafeThread(THREAD(accountId));
24
+ const map = (await t.get(KEY)) ?? {};
25
+ return map[sipUser];
26
+ }
27
+ exports.readDeskphoneConference = readDeskphoneConference;
28
+ /**
29
+ * Delete the correlation entry for a desk-phone SIP username.
30
+ *
31
+ * Idempotent: two concurrent clears converge on absent (the safe terminal state).
32
+ */
33
+ async function clearDeskphoneConference(self, accountId, sipUser) {
34
+ const t = self.process.getSafeThread(THREAD(accountId));
35
+ const map = (await t.get(KEY)) ?? {};
36
+ delete map[sipUser];
37
+ await t.set(KEY, map);
38
+ }
39
+ exports.clearDeskphoneConference = clearDeskphoneConference;
package/dst/voice.d.ts CHANGED
@@ -33,7 +33,7 @@ export interface IVoiceCall extends IConversationData {
33
33
  user: string;
34
34
  };
35
35
  }
36
- export type EventType = 'hangup' | 'ack' | 'error' | 'cancel' | 'background' | 'avm-detected' | 'recognition' | 'digit' | 'digits' | 'conference-start' | 'conference-end' | 'playback' | 'timeout' | 'record' | 'bridge' | 'bridge/ended' | 'is_flow_ready' | 'call' | 'dtmf-sent';
36
+ export type EventType = 'hangup' | 'ack' | 'error' | 'cancel' | 'background' | 'avm-detected' | 'recognition' | 'digit' | 'digits' | 'conference-start' | 'conference-end' | 'members' | 'playback' | 'timeout' | 'record' | 'bridge' | 'bridge/ended' | 'is_flow_ready' | 'call' | 'dtmf-sent';
37
37
  export declare class VoiceStepError extends BasicError {
38
38
  }
39
39
  export type VoicerError = Error & {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onereach/step-voice",
3
- "version": "7.0.45",
3
+ "version": "7.0.46-deskphoneintegration.2",
4
4
  "author": "Roman Zolotarov <roman.zolotarov@onereach.com>",
5
5
  "contributors": [
6
6
  "Roman Zolotarov",