@cognitiv-traits/traitos-ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,199 @@
1
+ /**
2
+ * The settings forms, as data. Each section knows how to load a form model from the API, validate it with the server's own
3
+ * limits, and turn an edited form into the smallest patch (only what changed; a handoff update that sends everything would
4
+ * overwrite fields another admin just changed).
5
+ *
6
+ * { id, label, description, needsAgent, load(client, ctx) -> model, validate(model) -> {path: message}, toPatch(original, draft) -> patch|null, save(client, ctx, patch) }
7
+ */
8
+ import { isE164 } from './softphoneState.js';
9
+ import { listLines, getOutboundMode, setOutboundMode } from './api.js';
10
+ import { loadPrefs, savePrefs, normalizePrefs, MAX_RING_SECONDS, PREFS_EVENT } from './dialerPrefs.js';
11
+
12
+ export const SIP_HANDLE = /^[A-Za-z0-9._-]{3,64}$/;
13
+ export const MAX_STEPS = 4;
14
+ export const RING = { min: 5, max: 60, softphone: 15, phone: 30 };
15
+ export const RULE_OPS = ['gt', 'gte', 'lt', 'lte', 'eq', 'neq', 'contains'];
16
+ export const RULE_OP_LABEL = { gt: 'is more than', gte: 'is at least', lt: 'is less than', lte: 'is at most', eq: 'is', neq: 'is not', contains: 'contains' };
17
+
18
+ const clone = (v) => JSON.parse(JSON.stringify(v));
19
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
20
+ const intIn = (v, min, max) => Number.isInteger(Number(v)) && String(v).trim() !== '' && Number(v) >= min && Number(v) <= max;
21
+
22
+ // ── Human handoff ───────────────────────────────────────────────────────────
23
+
24
+ export const handoff = {
25
+ id: 'handoff',
26
+ label: 'Human handoff',
27
+ description: 'Who is rung, in order, when an agent passes a conversation to a person. If nobody answers, the AI carries on.',
28
+ needsAgent: true,
29
+ async load(client, { agentId }) {
30
+ const s = await client.agents.handoffSettings.get(agentId);
31
+ return {
32
+ transferNumber: s.transferNumber ?? '',
33
+ callerId: s.routing?.callerId ?? 'customer',
34
+ steps: (s.routing?.steps ?? []).map((x) => ({ kind: x.kind, target: x.target, ringSecs: x.ringSecs ?? RING[x.kind] ?? RING.phone })),
35
+ };
36
+ },
37
+ validate(m) {
38
+ const e = {};
39
+ if (m.transferNumber && !isE164(m.transferNumber)) e.transferNumber = 'Use + then country code and number, like +18765550100.';
40
+ if (m.steps.length > MAX_STEPS) e.steps = `At most ${MAX_STEPS} people can be rung.`;
41
+ m.steps.forEach((s, i) => {
42
+ if (s.kind !== 'softphone' && s.kind !== 'phone') e[`steps.${i}.kind`] = 'Choose softphone or phone.';
43
+ else if (s.kind === 'phone' && !isE164(s.target)) e[`steps.${i}.target`] = 'Use + then country code and number.';
44
+ else if (s.kind === 'softphone' && !SIP_HANDLE.test(String(s.target ?? ''))) e[`steps.${i}.target`] = 'A softphone name has 3 to 64 letters, numbers, dots, dashes or underscores.';
45
+ if (!intIn(s.ringSecs, RING.min, RING.max)) e[`steps.${i}.ringSecs`] = `Ring for ${RING.min} to ${RING.max} seconds.`;
46
+ });
47
+ if (m.callerId !== 'customer' && m.callerId !== 'platform') e.callerId = 'Choose which number the person sees.';
48
+ return e;
49
+ },
50
+ toPatch(orig, draft) {
51
+ const patch = {};
52
+ if (orig.transferNumber !== draft.transferNumber) patch.transferNumber = draft.transferNumber || null;
53
+ const routing = (m) => ({ steps: m.steps.map((s) => ({ kind: s.kind, target: String(s.target).trim(), ringSecs: Number(s.ringSecs) })), callerId: m.callerId });
54
+ if (!same(routing(orig), routing(draft))) patch.routing = draft.steps.length ? routing(draft) : null;
55
+ return Object.keys(patch).length ? patch : null;
56
+ },
57
+ save: (client, { agentId }, patch) => client.agents.handoffSettings.update(agentId, patch),
58
+ // edits
59
+ addStep(m, kind = 'phone') { if (m.steps.length < MAX_STEPS) m.steps.push({ kind, target: '', ringSecs: RING[kind] }); },
60
+ removeStep(m, i) { m.steps.splice(i, 1); },
61
+ moveStep(m, i, dir) { const j = i + dir; if (j >= 0 && j < m.steps.length) [m.steps[i], m.steps[j]] = [m.steps[j], m.steps[i]]; },
62
+ setStep(m, i, field, value) {
63
+ const s = m.steps[i];
64
+ if (!s) return;
65
+ s[field] = field === 'ringSecs' ? (value === '' ? '' : Number(value)) : value;
66
+ if (field === 'kind') s.ringSecs = RING[value] ?? s.ringSecs;
67
+ },
68
+ };
69
+
70
+ // ── Approvals ───────────────────────────────────────────────────────────────
71
+
72
+ export const approvals = {
73
+ id: 'approvals',
74
+ label: 'Approvals',
75
+ description: 'When an agent must ask a person first, how long it waits, and what happens if nobody answers.',
76
+ needsAgent: false,
77
+ async load(client, { agentId }) {
78
+ const [s, r] = await Promise.all([client.approvals.settings(), agentId ? client.approvals.rules.list(agentId) : Promise.resolve({ rules: [] })]);
79
+ return {
80
+ timeoutMinutes: s.timeoutMinutes ?? 60, onTimeout: s.onTimeout ?? 'escalate', liveWaitSeconds: s.liveWaitSeconds ?? 0, notifyEmail: Boolean(s.notifyEmail),
81
+ rules: (r.rules ?? []).map((x) => ({ tool: x.tool, action: x.action, note: x.note ?? '', ...(x.when ? { when: { ...x.when } } : {}) })),
82
+ };
83
+ },
84
+ validate(m) {
85
+ const e = {};
86
+ if (!intIn(m.timeoutMinutes, 1, 60 * 24 * 14)) e.timeoutMinutes = 'Choose between 1 minute and 14 days (20160).';
87
+ if (m.onTimeout !== 'escalate' && m.onTimeout !== 'deny') e.onTimeout = 'Choose what happens when nobody answers.';
88
+ if (!intIn(m.liveWaitSeconds, 0, 600)) e.liveWaitSeconds = 'Choose between 0 and 600 seconds.';
89
+ m.rules.forEach((r, i) => {
90
+ if (!String(r.tool ?? '').trim()) e[`rules.${i}.tool`] = 'Name a tool, like refund.create or refund.*.';
91
+ if (!['ask', 'allow', 'deny'].includes(r.action)) e[`rules.${i}.action`] = 'Choose ask, allow or deny.';
92
+ if (r.when) {
93
+ if (!String(r.when.field ?? '').trim()) e[`rules.${i}.when.field`] = 'Name the field to check.';
94
+ if (!RULE_OPS.includes(r.when.op)) e[`rules.${i}.when.op`] = 'Choose a comparison.';
95
+ if (String(r.when.value ?? '') === '') e[`rules.${i}.when.value`] = 'Give a value to compare with.';
96
+ }
97
+ });
98
+ return e;
99
+ },
100
+ toPatch(orig, draft) {
101
+ const patch = {};
102
+ const settings = {};
103
+ for (const k of ['timeoutMinutes', 'onTimeout', 'liveWaitSeconds', 'notifyEmail']) if (orig[k] !== draft[k]) settings[k] = k === 'onTimeout' || k === 'notifyEmail' ? draft[k] : Number(draft[k]);
104
+ if (Object.keys(settings).length) patch.settings = settings;
105
+ const rules = (m) => m.rules.map((r) => ({ tool: r.tool.trim(), action: r.action, ...(r.note ? { note: r.note } : {}), ...(r.when ? { when: { field: r.when.field.trim(), op: r.when.op, value: Number.isFinite(Number(r.when.value)) && String(r.when.value).trim() !== '' ? Number(r.when.value) : r.when.value } } : {}) }));
106
+ if (!same(rules(orig), rules(draft))) patch.rules = rules(draft);
107
+ return Object.keys(patch).length ? patch : null;
108
+ },
109
+ async save(client, { agentId }, patch) {
110
+ if (patch.settings) await client.approvals.updateSettings(patch.settings);
111
+ if (patch.rules) {
112
+ if (!agentId) throw new Error('Choose an agent to change its approval rules.');
113
+ await client.approvals.rules.set(agentId, patch.rules);
114
+ }
115
+ },
116
+ addRule(m) { m.rules.push({ tool: '', action: 'ask', note: '' }); },
117
+ removeRule(m, i) { m.rules.splice(i, 1); },
118
+ setRule(m, i, field, value) { if (m.rules[i]) m.rules[i][field] = value; },
119
+ toggleCondition(m, i, on) { const r = m.rules[i]; if (!r) return; if (on) r.when = r.when ?? { field: '', op: 'gt', value: '' }; else delete r.when; },
120
+ setCondition(m, i, field, value) { const r = m.rules[i]; if (r?.when) r.when[field] = value; },
121
+ };
122
+
123
+ // ── Usage and spend cap ─────────────────────────────────────────────────────
124
+
125
+ export const usage = {
126
+ id: 'usage',
127
+ label: 'Usage and spend cap',
128
+ description: 'This month against your plan. Set a cap and conversations pause (with your message) instead of running up overage.',
129
+ needsAgent: false,
130
+ async load(client) {
131
+ const u = await client.usage.current();
132
+ const cap = u.overage?.spendCapCents;
133
+ return {
134
+ meters: u.meters ?? [], period: u.period, status: u.status, plan: u.plan?.name ?? '', overageCents: u.overage?.cents ?? 0,
135
+ spendCap: cap === null || cap === undefined ? '' : String(cap / 100),
136
+ fallbackMessage: u.fallbackMessage ?? '',
137
+ };
138
+ },
139
+ validate(m) {
140
+ const e = {};
141
+ if (m.spendCap !== '' && !(Number.isFinite(Number(m.spendCap)) && Number(m.spendCap) >= 0)) e.spendCap = 'Enter an amount in dollars, or leave blank for no cap.';
142
+ if (String(m.fallbackMessage).length > 500) e.fallbackMessage = 'Keep this under 500 characters.';
143
+ return e;
144
+ },
145
+ toPatch(orig, draft) {
146
+ const patch = {};
147
+ if (orig.spendCap !== draft.spendCap) patch.spendCapCents = draft.spendCap === '' ? null : Math.round(Number(draft.spendCap) * 100);
148
+ if (orig.fallbackMessage !== draft.fallbackMessage) patch.fallbackMessage = draft.fallbackMessage || null;
149
+ return Object.keys(patch).length ? patch : null;
150
+ },
151
+ save: (client, _ctx, patch) => client.usage.updateSettings(patch),
152
+ };
153
+
154
+
155
+ // ── Dialer ──────────────────────────────────────────────────────────────────
156
+ // Real endpoints only: lines come from GET /telephony/numbers, the outbound call mode from GET|PUT /telephony/outbound-call-settings
157
+ // (changing it needs an org admin). The server stores no ring timeout or caller ID, so those are kept in this browser.
158
+
159
+ export const OUTBOUND_MODES = [{ id: 'direct', label: 'Direct', hint: 'Place the call straight to the customer.' }, { id: 'agent-first', label: 'Agent first', hint: 'Ring the agent first, then connect the customer.' }];
160
+
161
+ export const dialer = {
162
+ id: 'dialer',
163
+ label: 'Dialer',
164
+ description: 'Your phone lines, how outbound calls are placed, and how this browser rings.',
165
+ needsAgent: false,
166
+ async load(client, { storage }) {
167
+ const [lines, mode] = await Promise.allSettled([listLines(client), getOutboundMode(client)]);
168
+ if (lines.status === 'rejected' && mode.status === 'rejected') throw mode.reason;
169
+ const p = loadPrefs(storage);
170
+ const ls = lines.status === 'fulfilled' ? lines.value : [];
171
+ const ch = (l) => (Array.isArray(l.channels) ? l.channels : []);
172
+ return {
173
+ mode: mode.status === 'fulfilled' ? mode.value : null,
174
+ lines: ls.map((l) => ({ number: l.number, name: l.name ?? '', whatsapp: ch(l).includes('whatsapp_calling'), phone: ch(l).includes('voice') })),
175
+ whatsappEnabled: ls.some((l) => ch(l).includes('whatsapp_calling')), phoneEnabled: ls.some((l) => ch(l).includes('voice')),
176
+ ringTimeoutSeconds: p.ringTimeoutSeconds, ringWhatsapp: p.ringChannels.whatsapp, ringPhone: p.ringChannels.phone, callerId: p.callerId ?? '',
177
+ };
178
+ },
179
+ validate(m) {
180
+ const e = {};
181
+ if (m.mode !== null && !OUTBOUND_MODES.some((x) => x.id === m.mode)) e.mode = 'Choose how outbound calls are placed.';
182
+ if (!intIn(m.ringTimeoutSeconds, 0, MAX_RING_SECONDS)) e.ringTimeoutSeconds = `Ring for 0 to ${MAX_RING_SECONDS} seconds.`;
183
+ return e;
184
+ },
185
+ toPatch(orig, draft) {
186
+ const patch = {};
187
+ if (draft.mode !== null && orig.mode !== draft.mode) patch.mode = draft.mode;
188
+ const prefs = (m) => normalizePrefs({ ringTimeoutSeconds: m.ringTimeoutSeconds, ringChannels: { whatsapp: m.ringWhatsapp, phone: m.ringPhone }, callerId: m.callerId });
189
+ if (!same(prefs(orig), prefs(draft))) patch.prefs = prefs(draft);
190
+ return Object.keys(patch).length ? patch : null;
191
+ },
192
+ async save(client, { storage }, patch) {
193
+ if (patch.mode) await setOutboundMode(client, patch.mode);
194
+ if (patch.prefs) { savePrefs(storage, patch.prefs); globalThis.dispatchEvent?.(new CustomEvent(PREFS_EVENT)); }
195
+ },
196
+ };
197
+
198
+ export const SECTIONS = Object.freeze({ handoff, approvals, usage, dialer });
199
+ export { clone };
@@ -0,0 +1,233 @@
1
+ import { stateForCall, callerLabel, SOFTPHONE_HEARTBEAT_MS, isE164 } from './softphoneState.js';
2
+ import { CallLog } from './callLog.js';
3
+ import { DEFAULT_STRINGS, t } from './strings.js';
4
+
5
+ const PLACING_MS = 45_000;
6
+ const DTMF = /^[0-9A-D*#]$/i;
7
+ const isMicDenied = (e) => e?.name === 'NotAllowedError' || e?.name === 'SecurityError' || /permission denied|microphone.*(denied|blocked)|not allowed/i.test(e?.message || '');
8
+
9
+ /**
10
+ * Runs a browser softphone. It owns the state; an element only renders `snapshot()` and calls the methods.
11
+ *
12
+ * The WebRTC part is an adapter you pass in (see telnyxAdapter.js), so this file has no browser or vendor dependency:
13
+ * adapter.connect({ token, sipUsername }) adapter.disconnect()
14
+ * adapter.on('ready' | 'error' | 'close' | 'call', fn) 'call' gets a call object:
15
+ * call = { direction, state, remoteCallerName?, remoteCallerNumber?, answer(), hangup(), mute(on), hold?(on), dtmf?(digit) }
16
+ *
17
+ * The browser token needs the `softphone` scope (and `events` if you turn on `liveEvents`).
18
+ */
19
+ export class SoftphoneController {
20
+ /**
21
+ * @param {{client: object, adapter: object, numbers?: string[], ringTimeoutSeconds?: number, liveEvents?: boolean, heartbeatMs?: number,
22
+ * timers?: {setInterval: Function, clearInterval: Function, setTimeout?: Function, clearTimeout?: Function}, now?: () => number,
23
+ * whatsapp?: object, log?: CallLog, media?: {getUserMedia: Function}|null, strings?: object}} options
24
+ * `whatsapp` holds what a WhatsApp call needs (`from`, `sipHostname`, `sipPassword`, ...); without it only phone calls can be placed.
25
+ */
26
+ constructor({ client, adapter, numbers, ringTimeoutSeconds, liveEvents = false, heartbeatMs = SOFTPHONE_HEARTBEAT_MS, timers, now = Date.now, whatsapp, log, media, strings }) {
27
+ this.client = client;
28
+ this.adapter = adapter;
29
+ this.numbers = numbers;
30
+ this.ringTimeoutSeconds = ringTimeoutSeconds;
31
+ this.liveEvents = liveEvents;
32
+ this.heartbeatMs = heartbeatMs;
33
+ this.timers = { setTimeout: (f, ms) => setTimeout(f, ms), clearTimeout: (h) => clearTimeout(h), ...(timers ?? { setInterval: (f, ms) => setInterval(f, ms), clearInterval: (h) => clearInterval(h) }) };
34
+ this.now = now;
35
+ this.whatsapp = whatsapp;
36
+ this.log = log ?? new CallLog({ now });
37
+ this.media = media === undefined ? (globalThis.navigator?.mediaDevices ?? null) : media;
38
+ this.S = { ...DEFAULT_STRINGS, ...(strings || {}) };
39
+ this.state = { status: 'off', caller: null, muted: false, held: false, error: null, errorCode: null, warning: null, sipUsername: null, startedAt: null, dialing: false, placing: null, lastCall: null, recent: [] };
40
+ this._call = null; this._listeners = new Set(); this._heartbeat = null; this._sub = null; this._wired = false;
41
+ this._gen = 0; this._failures = 0; this._placingTimer = null; this._current = null;
42
+ }
43
+
44
+ snapshot() { return { ...this.state, recent: [...this.state.recent] }; }
45
+
46
+ /** Subscribe to state changes. Returns an unsubscribe function. */
47
+ subscribe(fn) { this._listeners.add(fn); return () => this._listeners.delete(fn); }
48
+
49
+ _set(patch) {
50
+ this.state = { ...this.state, ...patch };
51
+ for (const fn of [...this._listeners]) { try { fn(this.snapshot()); } catch { /* a listener must not break the phone */ } }
52
+ }
53
+
54
+ _wire() {
55
+ if (this._wired) return; // handlers are added once, however many times the phone goes online
56
+ this._wired = true;
57
+ this.adapter.on('ready', () => { if (this.state.status === 'connecting') this._set({ status: 'ready' }); });
58
+ this.adapter.on('error', (e) => this._fail(e));
59
+ this.adapter.on('close', () => { if (this.state.status !== 'off' && this.state.status !== 'error') { this._teardown(); this._fail(Object.assign(new Error(this.S.connectionLost), { code: 'connection-lost' })); } });
60
+ this.adapter.on('call', (call) => this._onCall(call));
61
+ }
62
+
63
+ async _checkMic() {
64
+ if (!this.media?.getUserMedia) return;
65
+ const stream = await this.media.getUserMedia({ audio: true });
66
+ stream?.getTracks?.().forEach((tr) => tr.stop());
67
+ }
68
+
69
+ async start() {
70
+ if (this.state.status !== 'off' && this.state.status !== 'error') return;
71
+ const gen = ++this._gen;
72
+ this._set({ status: 'connecting', error: null, errorCode: null, warning: null });
73
+ try {
74
+ await this._checkMic();
75
+ const { token, sipUsername } = await this.client.softphone.token();
76
+ if (gen !== this._gen) return;
77
+ if (!token || !sipUsername) throw new Error(this.S.noIdentity);
78
+ this._wire();
79
+ this._set({ sipUsername });
80
+ await this.adapter.connect({ token, sipUsername });
81
+ if (gen !== this._gen) return;
82
+ await this._register();
83
+ if (gen !== this._gen) return;
84
+ this._failures = 0;
85
+ this._heartbeat = this.timers.setInterval(() => this._beat(), this.heartbeatMs);
86
+ if (this.liveEvents) this._watchEvents();
87
+ } catch (error) {
88
+ if (gen !== this._gen) return;
89
+ this._teardown();
90
+ try { await this.adapter.disconnect(); } catch { /* never connected */ }
91
+ this._fail(error);
92
+ }
93
+ }
94
+
95
+ async stop() {
96
+ this._gen++; // abandons a start that is still waiting
97
+ const sip = this.state.sipUsername;
98
+ this._teardown();
99
+ try { this._call?.hangup?.(); } catch { /* already gone */ }
100
+ try { await this.adapter.disconnect(); } catch { /* already gone */ }
101
+ if (sip) await this.client.softphone.unregister(sip).catch(() => {});
102
+ this._call = null; this._current = null;
103
+ this._set({ status: 'off', caller: null, muted: false, held: false, startedAt: null, placing: null, warning: null });
104
+ }
105
+
106
+ /** Stop the timers and the live feed (used by stop, by a failed start and by a dropped connection). */
107
+ _teardown() {
108
+ if (this._heartbeat) this.timers.clearInterval(this._heartbeat);
109
+ this._heartbeat = null;
110
+ this._sub?.close?.(); this._sub = null;
111
+ this._clearPlacing();
112
+ }
113
+
114
+ _register() {
115
+ const n = this.numbers;
116
+ return this.client.softphone.register({ sipUsername: this.state.sipUsername, ...(n && n.length ? { numbers: n } : {}), ...(this.ringTimeoutSeconds ? { ringTimeoutSeconds: this.ringTimeoutSeconds } : {}) });
117
+ }
118
+
119
+ /** Renews the registration. An expired token ends the session loudly; a flaky network warns after three misses. */
120
+ async _beat() {
121
+ try { await this._register(); this._failures = 0; if (this.state.warning) this._set({ warning: null }); } catch (error) {
122
+ if (error?.status === 401 || error?.status === 403) {
123
+ this._teardown();
124
+ try { await this.adapter.disconnect(); } catch { /* ignore */ }
125
+ this._fail(Object.assign(new Error(this.S.sessionExpired), { code: 'session-expired' }));
126
+ } else if (++this._failures >= 3 && !this.state.warning) this._set({ warning: this.S.unstable });
127
+ }
128
+ }
129
+
130
+ _watchEvents() {
131
+ this._sub = this.client.events.subscribe((e) => {
132
+ const recent = [{ type: e.type, at: e.created_at, id: e.id }, ...this.state.recent].slice(0, 5);
133
+ this._set({ recent });
134
+ }, { types: ['call.*'], onError: () => {} });
135
+ }
136
+
137
+ _fail(error) {
138
+ const denied = isMicDenied(error);
139
+ this._set({ status: 'error', error: denied ? this.S.micBlocked : (error?.message || this.S.error), errorCode: denied ? 'mic-denied' : (error?.code ?? null), caller: null, held: false, muted: false, startedAt: null, dialing: false });
140
+ }
141
+
142
+ _clearPlacing() { if (this._placingTimer) this.timers.clearTimeout(this._placingTimer); this._placingTimer = null; if (this.state.placing) this.state = { ...this.state, placing: null }; }
143
+
144
+ _finish(outcome) {
145
+ const c = this._current;
146
+ this._current = null;
147
+ if (!c) return;
148
+ const durationMs = c.answeredAt ? this.now() - c.answeredAt : 0;
149
+ const result = c.answeredAt ? 'answered' : 'missed';
150
+ this.log.add({ who: c.who, number: c.number, direction: c.direction === 'inbound' ? 'in' : 'out', outcome: outcome ?? result, durationMs });
151
+ this._set({ lastCall: { who: c.who, durationMs, outcome: outcome ?? result, at: this.now() } });
152
+ }
153
+
154
+ _onCall(call) {
155
+ this._call = call;
156
+ const next = stateForCall(call.direction, call.state);
157
+ if (!next) return;
158
+ if (this.state.placing) { this._clearPlacing(); }
159
+ if (next === 'ringing') {
160
+ this._current = { who: callerLabel(call), number: call.remoteCallerNumber || null, direction: 'inbound', answeredAt: null };
161
+ this._set({ status: 'ringing', caller: callerLabel(call), muted: false, held: false, lastCall: null, placing: null });
162
+ } else if (next === 'in-call') {
163
+ this._current ??= { who: callerLabel(call), number: call.remoteCallerNumber || null, direction: call.direction, answeredAt: null };
164
+ this._current.answeredAt ??= this.now();
165
+ this._set({ status: 'in-call', startedAt: this.state.startedAt ?? this.now(), caller: this.state.caller ?? callerLabel(call), held: call.state === 'held', lastCall: null, placing: null });
166
+ } else {
167
+ this._call = null;
168
+ this._finish();
169
+ this._set({ status: 'ready', caller: null, muted: false, held: false, startedAt: null });
170
+ }
171
+ }
172
+
173
+ /** Feed a call update by hand (adapters usually do this through the 'call' event). */
174
+ applyCallUpdate(call) { this._onCall(call); }
175
+
176
+ answer() { if (this.state.status === 'ringing') this._call?.answer?.(); }
177
+ hangup() { this._call?.hangup?.(); }
178
+
179
+ mute() {
180
+ if (!this._call) return;
181
+ const muted = !this.state.muted;
182
+ try { this._call.mute?.(muted); } catch { return; }
183
+ this._set({ muted });
184
+ }
185
+
186
+ /** Hold or resume. Needs an adapter whose call object has `hold(on)`; returns false when it cannot. */
187
+ hold() {
188
+ if (!this._call || typeof this._call.hold !== 'function' || this.state.status !== 'in-call') return false;
189
+ const held = !this.state.held;
190
+ try { this._call.hold(held); } catch { return false; }
191
+ this._set({ held });
192
+ return true;
193
+ }
194
+
195
+ /** Send a keypad tone on the live call (0–9, *, #, A–D). */
196
+ dtmf(digit) {
197
+ const d = String(digit ?? '');
198
+ if (!DTMF.test(d) || this.state.status !== 'in-call' || typeof this._call?.dtmf !== 'function') return false;
199
+ try { this._call.dtmf(d.toUpperCase()); return true; } catch { return false; }
200
+ }
201
+
202
+ get canHold() { return typeof this._call?.hold === 'function'; }
203
+ get canDtmf() { return typeof this._call?.dtmf === 'function'; }
204
+
205
+ /**
206
+ * Ring a customer from the company line and bridge them to this softphone when they pick up.
207
+ * @param {string} to digits or E.164 ("18765550100" and "+18765550100" are the same)
208
+ * @param {'phone'|'whatsapp'} [channel]
209
+ */
210
+ async dial(to, channel = 'phone') {
211
+ const num = String(to ?? '');
212
+ const e164 = /^\d+$/.test(num) ? `+${num}` : num;
213
+ if (this.state.dialing) return false; // a double click must not place two calls
214
+ if (!isE164(e164)) { this._set({ error: this.S.badNumber, errorCode: 'bad-number' }); return false; }
215
+ if (this.state.status !== 'ready') { this._set({ error: this.S.goOnlineFirst, errorCode: 'offline' }); return false; }
216
+ if (channel === 'whatsapp' && !this.whatsapp) { this._set({ error: this.S.whatsappNotConfigured, errorCode: 'whatsapp-not-configured' }); return false; }
217
+ this._set({ dialing: true, error: null, errorCode: null });
218
+ try {
219
+ await this.client.calls.create(channel === 'whatsapp'
220
+ ? { channel: 'whatsapp', to: e164, agentSipUsername: this.state.sipUsername, ...this.whatsapp }
221
+ : { channel: 'phone', to: e164, agentSipUsername: this.state.sipUsername });
222
+ this._set({ placing: { number: e164, channel } });
223
+ this._placingTimer = this.timers.setTimeout(() => { this._placingTimer = null; if (this.state.placing) this._set({ placing: null }); }, PLACING_MS);
224
+ return true;
225
+ } catch (error) {
226
+ this._set({ error: error?.message || this.S.couldNotCall, errorCode: error?.code ?? null });
227
+ return false;
228
+ } finally {
229
+ this._set({ dialing: false });
230
+ }
231
+ }
232
+ }
233
+ export { t };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Pure softphone helpers (no DOM, no WebRTC library). Same states and labels as the TraitOS dashboard's softphone.
3
+ * Telnyx call states: new, trying, requesting, recovering, ringing, answering, early, active, held, hangup, destroy, done.
4
+ */
5
+ export const SOFTPHONE_HEARTBEAT_MS = 60_000; // registration lasts 120s on the server; renew well inside it
6
+
7
+ /** The softphone state a call update means, or null to leave the current state alone. */
8
+ export function stateForCall(direction, callState) {
9
+ switch (callState) {
10
+ case 'ringing': return direction === 'inbound' ? 'ringing' : null;
11
+ case 'answering': case 'active': case 'held': case 'early': return 'in-call';
12
+ case 'hangup': case 'destroy': case 'done': return 'ready';
13
+ default: return null;
14
+ }
15
+ }
16
+
17
+ export const softphoneLabel = {
18
+ off: 'Softphone off', connecting: 'Connecting…', ready: 'Ready for calls', ringing: 'Incoming call', 'in-call': 'On a call', error: 'Softphone error',
19
+ };
20
+
21
+ /** Who is calling, for display. */
22
+ export function callerLabel(opts) {
23
+ const name = (opts?.remoteCallerName || opts?.callerName || '').trim();
24
+ const num = (opts?.remoteCallerNumber || opts?.callerNumber || '').trim();
25
+ if (name && num && name !== num) return `${name} (${num})`;
26
+ return name || num || 'Unknown caller';
27
+ }
28
+
29
+ /** 0:07, 12:03, 1:02:03 */
30
+ export function formatDuration(ms) {
31
+ const s = Math.max(0, Math.floor(ms / 1000));
32
+ const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
33
+ const mm = h ? String(m).padStart(2, '0') : String(m);
34
+ return `${h ? `${h}:` : ''}${mm}:${String(sec).padStart(2, '0')}`;
35
+ }
36
+
37
+ /** Keep digits and a leading "+", for a dial box. */
38
+ export function cleanDialInput(value) {
39
+ const v = String(value ?? '').replace(/[^\d+]/g, '');
40
+ return (v.startsWith('+') ? '+' : '') + v.replace(/\+/g, '');
41
+ }
42
+
43
+ /** `+` then 7 to 15 digits. */
44
+ export const isE164 = (n) => /^\+[1-9]\d{6,14}$/.test(String(n ?? ''));
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Phone sounds with no audio files: real DTMF key tones (the standard two-frequency pairs), a soft click, a ringtone, an
3
+ * end-of-call beep, and optional spoken digits in a voice you choose. Built on Web Audio and speechSynthesis, both injectable
4
+ * so the logic is testable. Settings are per browser (localStorage). Audio only starts after a user gesture, as browsers require.
5
+ */
6
+ export const DTMF_FREQ = Object.freeze({
7
+ 1: [697, 1209], 2: [697, 1336], 3: [697, 1477], 4: [770, 1209], 5: [770, 1336], 6: [770, 1477],
8
+ 7: [852, 1209], 8: [852, 1336], 9: [852, 1477], '*': [941, 1209], 0: [941, 1336], '#': [941, 1477],
9
+ });
10
+ export const KEY_TONES = Object.freeze(['dtmf', 'click', 'off']);
11
+ export const RINGTONES = Object.freeze({ classic: [[440, 480], 2000, 4000], soft: [[523, 659], 1000, 3000], off: null });
12
+ export const DEFAULT_SOUND = Object.freeze({ enabled: true, volume: 0.5, keyTone: 'dtmf', ringtone: 'classic', speak: false, voice: '', rate: 1 });
13
+ const KEY = 'traitos.sound';
14
+ const SPOKEN = { '*': 'star', '#': 'pound', '+': 'plus' };
15
+
16
+ export function normalizeSound(p = {}) {
17
+ const vol = Number(p?.volume); const rate = Number(p?.rate);
18
+ return {
19
+ enabled: p?.enabled !== false,
20
+ volume: Number.isFinite(vol) ? Math.min(1, Math.max(0, vol)) : DEFAULT_SOUND.volume,
21
+ keyTone: KEY_TONES.includes(p?.keyTone) ? p.keyTone : DEFAULT_SOUND.keyTone,
22
+ ringtone: Object.prototype.hasOwnProperty.call(RINGTONES, p?.ringtone) ? p.ringtone : DEFAULT_SOUND.ringtone,
23
+ speak: p?.speak === true,
24
+ voice: typeof p?.voice === 'string' ? p.voice : '',
25
+ rate: Number.isFinite(rate) ? Math.min(2, Math.max(0.5, rate)) : 1,
26
+ };
27
+ }
28
+ export function loadSound(storage) { try { return normalizeSound(JSON.parse(storage?.getItem(KEY) || '{}')); } catch { return normalizeSound(); } }
29
+ export function saveSound(storage, s) { try { storage?.setItem(KEY, JSON.stringify(normalizeSound(s))); } catch { /* blocked */ } }
30
+
31
+ /**
32
+ * @param {{storage?: Storage, audio?: () => AudioContext, speech?: SpeechSynthesis, Utterance?: Function, settings?: object}} [opts]
33
+ */
34
+ export function createSound({ storage, audio, speech, Utterance, settings } = {}) {
35
+ let s = settings ? normalizeSound(settings) : loadSound(storage);
36
+ let ctx = null; let ring = null;
37
+ const listeners = new Set();
38
+ const synth = speech ?? globalThis.speechSynthesis;
39
+ const Utt = Utterance ?? globalThis.SpeechSynthesisUtterance;
40
+ const getCtx = () => {
41
+ if (ctx) return ctx;
42
+ try { const make = audio ?? (() => new (globalThis.AudioContext || globalThis.webkitAudioContext)()); ctx = make(); } catch { ctx = null; }
43
+ if (ctx?.state === 'suspended') ctx.resume?.().catch?.(() => {});
44
+ return ctx;
45
+ };
46
+ /** One tone made of one or more frequencies, with a short fade so it does not pop. Returns a stop function. */
47
+ function tone(freqs, ms, gain = 1) {
48
+ const c = getCtx();
49
+ if (!c) return () => {};
50
+ const g = c.createGain(); const t0 = c.currentTime; const t1 = t0 + ms / 1000;
51
+ const level = 0.25 * s.volume * gain;
52
+ g.gain.setValueAtTime(0.0001, t0); g.gain.linearRampToValueAtTime(level, t0 + 0.008); g.gain.setValueAtTime(level, Math.max(t0 + 0.008, t1 - 0.02)); g.gain.linearRampToValueAtTime(0.0001, t1);
53
+ g.connect(c.destination);
54
+ const oscs = freqs.map((f) => { const o = c.createOscillator(); o.type = 'sine'; o.frequency.value = f; o.connect(g); o.start(t0); o.stop(t1 + 0.02); return o; });
55
+ return () => { try { oscs.forEach((o) => o.stop()); g.disconnect(); } catch { /* already stopped */ } };
56
+ }
57
+ const on = () => s.enabled && s.volume > 0;
58
+ const api = {
59
+ get settings() { return { ...s }; },
60
+ update(patch) { s = normalizeSound({ ...s, ...patch }); saveSound(storage, s); if (!on()) api.stopRing(); listeners.forEach((fn) => fn()); },
61
+ subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
62
+ /** A key press: the DTMF pair for that key, or a click, per the settings; plus the spoken digit when that is on. */
63
+ key(d) {
64
+ if (!on()) return;
65
+ if (s.keyTone === 'dtmf' && DTMF_FREQ[d]) tone(DTMF_FREQ[d], 120);
66
+ else if (s.keyTone === 'click') api.click();
67
+ else if (s.keyTone === 'dtmf') api.click(); // + has no tone; still acknowledge the press
68
+ if (s.speak) api.say(SPOKEN[d] ?? d);
69
+ },
70
+ /** A short click for non-digit buttons (backspace, call, mute). */
71
+ click() { if (on() && s.keyTone !== 'off') tone([1800], 14, 0.9); },
72
+ /** Speak text in the chosen voice (if speech is available). Cancels what was being said. */
73
+ say(text) {
74
+ if (!s.enabled || !synth || !Utt) return false;
75
+ try {
76
+ synth.cancel?.();
77
+ const u = new Utt(String(text)); u.volume = Math.max(0.05, s.volume); u.rate = s.rate;
78
+ const v = s.voice && synth.getVoices?.().find((x) => x.voiceURI === s.voice); if (v) { u.voice = v; u.lang = v.lang; }
79
+ synth.speak(u); return true;
80
+ } catch { return false; }
81
+ },
82
+ /** Installed voices as `{ id, label }` (empty when the browser has none or has not loaded them yet). */
83
+ voices() { try { return (synth?.getVoices?.() ?? []).map((v) => ({ id: v.voiceURI, label: `${v.name} (${v.lang})` })); } catch { return []; } },
84
+ /** Ring until stopRing(): two-tone bursts on a cadence. */
85
+ startRing() {
86
+ if (ring || !on()) return;
87
+ const def = RINGTONES[s.ringtone]; if (!def) return;
88
+ const [freqs, burst, gap] = def;
89
+ const state = { stop: () => {}, timer: null };
90
+ const beat = () => { state.stop = tone(freqs, burst, 0.8); state.timer = setTimeout(beat, burst + gap); };
91
+ ring = state; beat();
92
+ },
93
+ stopRing() { if (!ring) return; clearTimeout(ring.timer); ring.stop(); ring = null; },
94
+ get ringing() { return Boolean(ring); },
95
+ /** Two falling beeps when a call ends. */
96
+ end() { if (!on()) return; tone([480], 140, 0.8); setTimeout(() => tone([380], 200, 0.8), 170); },
97
+ /** Preview for the options panel. */
98
+ test() { api.key('5'); if (s.speak) api.say('Five'); },
99
+ };
100
+ return api;
101
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Every user-facing word in the phone elements, in one object. Override per element (`el.strings = { call: 'Appeler' }`)
3
+ * or for the whole page (`setDefaultStrings({...})`). Missing keys fall back to English. `{name}` placeholders are filled by `t()`.
4
+ */
5
+ export const DEFAULT_STRINGS = Object.freeze({
6
+ softphone: 'Softphone', phone: 'Phone',
7
+ off: 'Softphone off', connecting: 'Connecting…', ready: 'Ready for calls', ringing: 'Incoming call', inCall: 'On a call', error: 'Softphone error',
8
+ goOnline: 'Go online', goOffline: 'Go offline', tryAgain: 'Try again',
9
+ goOnlineHint: 'Go online to receive calls in this browser. Allow microphone access when asked.',
10
+ waiting: 'Waiting for calls', waitingAs: 'Waiting for calls as {name}.',
11
+ isCalling: 'is calling', answer: 'Answer', decline: 'Decline', hangUp: 'Hang up', mute: 'Mute', unmute: 'Unmute', hold: 'Hold', resume: 'Resume',
12
+ onHold: 'On hold', onACall: 'On a call', showKeypad: 'Keypad', hideKeypad: 'Hide keypad', sendingDigits: 'Tap a key to send it to the caller',
13
+ callEnded: 'Call ended', callEndedFor: 'Call ended · {time}', missedCall: 'Missed call',
14
+ placing: 'Calling {number}… your browser will ring when the line connects.',
15
+ numberLabel: 'Number to call', numberPlaceholder: 'Number with country code', backspace: 'Delete last digit', keypad: 'Keypad',
16
+ callOn: 'Call on {channel}', whatsapp: 'WhatsApp', phoneChannel: 'Phone', callingOff: 'Calling is off for this workspace.', needCountryCode: 'Include the country code, e.g. 1876…',
17
+ keyZero: '0, hold for plus', keyStar: 'star', keyHash: 'hash',
18
+ recent: 'Recent calls', noRecent: 'No recent calls yet.', redial: 'Call {who} again', incoming: 'Incoming', outgoing: 'Outgoing', missed: 'Missed',
19
+ openPhone: 'Open phone', closePhone: 'Close phone', missedBadge: '{n} missed calls', dialogLabel: 'Phone',
20
+ needSetup: 'Set the client and adapter properties first.', goOnlineFirst: 'Go online first to place calls.', badNumber: 'Enter the number as +, then country code and number.',
21
+ whatsappNotConfigured: 'WhatsApp calling is not set up for this page (set the whatsapp property).',
22
+ micBlocked: 'Microphone access is blocked. Allow it in your browser settings, then try again.',
23
+ sessionExpired: 'Your session expired. Reload the page or sign in again.', connectionLost: 'Connection lost. Try again.', unstable: 'Connection to TraitOS is unstable.',
24
+ sound: 'Sound', soundOn: 'Sounds on', volume: 'Volume', keyTone: 'Key sound', keyToneDtmf: 'Phone tones', keyToneClick: 'Click', keyToneOff: 'None',
25
+ ringtone: 'Ringtone', ringClassic: 'Classic', ringSoft: 'Soft', ringOff: 'Silent', speakDigits: 'Say each digit aloud', voice: 'Voice', voiceDefault: 'Browser default', voiceRate: 'Speaking speed', soundTest: 'Test sound',
26
+ couldNotCall: 'Could not place the call', noIdentity: 'This account has no softphone identity yet.', couldNotLoad: 'Could not load this section.',
27
+ });
28
+
29
+ let defaults = {};
30
+ /** Page-wide overrides, merged over English. */
31
+ export function setDefaultStrings(overrides) { defaults = { ...(overrides || {}) }; }
32
+ export const stringsFor = (own) => ({ ...DEFAULT_STRINGS, ...defaults, ...(own || {}) });
33
+
34
+ /** `t(S, 'placing', { number })` — fills `{name}` placeholders; an unknown key shows the key, never "undefined". */
35
+ export function t(S, key, vars) {
36
+ const s = S?.[key] ?? DEFAULT_STRINGS[key] ?? key;
37
+ return vars ? String(s).replace(/\{(\w+)\}/g, (m, k) => (vars[k] ?? m)) : String(s);
38
+ }