@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,4462 @@
1
+ (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/index.js
9
+ var index_exports = {};
10
+ __export(index_exports, {
11
+ CORNERS: () => CORNERS,
12
+ CallLog: () => CallLog,
13
+ DAYS: () => DAYS,
14
+ DEFAULT_SOUND: () => DEFAULT_SOUND,
15
+ DEFAULT_STRINGS: () => DEFAULT_STRINGS,
16
+ DIGITS: () => DIGITS,
17
+ DTMF_FREQ: () => DTMF_FREQ,
18
+ FlowBuilderController: () => FlowBuilderController,
19
+ KEYS: () => KEYS,
20
+ KEY_TONES: () => KEY_TONES,
21
+ MIN_DIGITS: () => MIN_DIGITS,
22
+ PhoneBase: () => PhoneBase,
23
+ RINGTONES: () => RINGTONES,
24
+ SECTIONS: () => SECTIONS,
25
+ SOFTPHONE_HEARTBEAT_MS: () => SOFTPHONE_HEARTBEAT_MS,
26
+ SettingsController: () => SettingsController,
27
+ SoftphoneController: () => SoftphoneController,
28
+ TARGET_LABEL: () => TARGET_LABEL,
29
+ TARGET_TYPES: () => TARGET_TYPES,
30
+ TokenManager: () => TokenManager,
31
+ TraitElement: () => TraitElement,
32
+ TraitOSDialerWidget: () => TraitOSDialerWidget,
33
+ TraitOSFlowBuilder: () => TraitOSFlowBuilder,
34
+ TraitOSKeypad: () => TraitOSKeypad,
35
+ TraitOSSettings: () => TraitOSSettings,
36
+ TraitOSSoftphone: () => TraitOSSoftphone,
37
+ addRoute: () => addRoute,
38
+ baseCss: () => baseCss,
39
+ callerLabel: () => callerLabel,
40
+ canCall: () => canCall,
41
+ capsFromLines: () => capsFromLines,
42
+ cleanDialInput: () => cleanDialInput,
43
+ createDialpad: () => createDialpad,
44
+ createOpenState: () => createOpenState,
45
+ createSound: () => createSound,
46
+ defaultChannel: () => defaultChannel,
47
+ define: () => define,
48
+ defineAll: () => defineAll,
49
+ describeFlow: () => describeFlow,
50
+ digitsOf: () => digitsOf,
51
+ emptyFlow: () => emptyFlow,
52
+ enabledChannels: () => enabledChannels,
53
+ escapeHtml: () => escapeHtml,
54
+ formatDuration: () => formatDuration,
55
+ html: () => html,
56
+ iconLabel: () => iconLabel,
57
+ isE164: () => isE164,
58
+ loadPrefs: () => loadPrefs,
59
+ moveRoute: () => moveRoute,
60
+ nextFreeDigit: () => nextFreeDigit,
61
+ normalizeFlow: () => normalizeFlow,
62
+ normalizePrefs: () => normalizePrefs,
63
+ normalizeSound: () => normalizeSound,
64
+ panelSide: () => panelSide,
65
+ placementOf: () => placementOf,
66
+ raw: () => raw,
67
+ registrationFor: () => registrationFor,
68
+ removeRoute: () => removeRoute,
69
+ renderCallControls: () => renderCallControls,
70
+ renderFlowBuilder: () => renderFlowBuilder,
71
+ renderKeypad: () => renderKeypad,
72
+ renderRecentCalls: () => renderRecentCalls,
73
+ renderSettings: () => renderSettings,
74
+ renderSoftphone: () => renderSoftphone,
75
+ renderSoundOptions: () => renderSoundOptions,
76
+ renderWidget: () => renderWidget,
77
+ sanitizeNumber: () => sanitizeNumber,
78
+ savePrefs: () => savePrefs,
79
+ setDefaultStrings: () => setDefaultStrings,
80
+ setGreeting: () => setGreeting,
81
+ setHours: () => setHours,
82
+ setMenu: () => setMenu,
83
+ setRoute: () => setRoute,
84
+ setSpam: () => setSpam,
85
+ softphoneLabel: () => softphoneLabel,
86
+ stateForCall: () => stateForCall,
87
+ storedPrefs: () => storedPrefs,
88
+ stringsFor: () => stringsFor,
89
+ t: () => t,
90
+ telnyxAdapter: () => telnyxAdapter,
91
+ toggleDay: () => toggleDay,
92
+ validateFlow: () => validateFlow
93
+ });
94
+
95
+ // src/html.js
96
+ var ESC = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" };
97
+ var escapeHtml = (value) => String(value != null ? value : "").replace(/[&<>"']/g, (c) => ESC[c]);
98
+ var SafeHtml = class {
99
+ constructor(value) {
100
+ this.value = value;
101
+ }
102
+ toString() {
103
+ return this.value;
104
+ }
105
+ };
106
+ var raw = (value) => new SafeHtml(String(value));
107
+ var part = (v) => v instanceof SafeHtml ? v.value : Array.isArray(v) ? v.map(part).join("") : v === false || v === null || v === void 0 ? "" : escapeHtml(v);
108
+ function html(strings, ...values) {
109
+ let out = strings[0];
110
+ for (let i = 0; i < values.length; i++) out += part(values[i]) + strings[i + 1];
111
+ return new SafeHtml(out);
112
+ }
113
+
114
+ // src/theme.js
115
+ var baseCss = `
116
+ :host { display: block; font: var(--traitos-font, 14px/1.45 system-ui, -apple-system, 'Segoe UI', sans-serif); color: var(--traitos-text, var(--_text));
117
+ --_text: #1b1f24; --_accent: var(--traitos-accent, #4f46e5); --_bg: var(--traitos-bg, #fff); --_alt: var(--traitos-key-bg, #f4f6f8); --_muted: var(--traitos-muted, #5b6470); --_line: var(--traitos-line, #d8dde3);
118
+ --_ok: var(--traitos-ok, #137a3d); --_warn: var(--traitos-warn, #a15c00); --_bad: var(--traitos-danger, #b3261e); --_r: var(--traitos-radius, 10px); --_wa: var(--traitos-whatsapp, #137a3d); --_ph: var(--traitos-phone, #0b6bb5);
119
+ --_accfill: var(--traitos-accent, #4f46e5); --_okfill: var(--traitos-ok, #137a3d); --_badfill: var(--traitos-danger, #b3261e); }
120
+ @media (prefers-color-scheme: dark) { :host(:not([theme=light])) { --_text: #e8ebef; --_accent: var(--traitos-accent, #8b87ff); --_bg: var(--traitos-bg, #181b20); --_alt: var(--traitos-key-bg, #232830); --_muted: var(--traitos-muted, #a4adb9); --_line: var(--traitos-line, #343b45);
121
+ --_ok: var(--traitos-ok, #4cc57e); --_warn: var(--traitos-warn, #e0a23a); --_bad: var(--traitos-danger, #ff7a70); --_wa: var(--traitos-whatsapp, #1f8a4d); --_ph: var(--traitos-phone, #2b7fc9);
122
+ --_accfill: var(--traitos-accent, #5b57d6); --_okfill: var(--traitos-ok, #1b7f45); --_badfill: var(--traitos-danger, #c9372c); } }
123
+ :host([theme=dark]) { --_text: #e8ebef; --_accent: var(--traitos-accent, #8b87ff); --_bg: var(--traitos-bg, #181b20); --_alt: var(--traitos-key-bg, #232830); --_muted: var(--traitos-muted, #a4adb9); --_line: var(--traitos-line, #343b45);
124
+ --_ok: var(--traitos-ok, #4cc57e); --_warn: var(--traitos-warn, #e0a23a); --_bad: var(--traitos-danger, #ff7a70); --_wa: var(--traitos-whatsapp, #1f8a4d); --_ph: var(--traitos-phone, #2b7fc9);
125
+ --_accfill: var(--traitos-accent, #5b57d6); --_okfill: var(--traitos-ok, #1b7f45); --_badfill: var(--traitos-danger, #c9372c); }
126
+ * { box-sizing: border-box; }
127
+ .card { background: var(--_bg); border: 1px solid var(--_line); border-radius: var(--_r); padding: 16px; }
128
+ h2 { font-size: 15px; margin: 0 0 4px; } h3 { font-size: 13px; margin: 16px 0 6px; color: var(--_muted); text-transform: uppercase; letter-spacing: .04em; }
129
+ p.hint, .hint { color: var(--_muted); font-size: 12.5px; margin: 2px 0 8px; }
130
+ label { display: block; font-weight: 600; font-size: 13px; margin: 10px 0 4px; }
131
+ input, select, textarea { width: 100%; font: inherit; color: inherit; background: var(--_bg); border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 7px 9px; }
132
+ input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible, a:focus-visible { outline: 3px solid var(--_accent); outline-offset: 2px; }
133
+ input[aria-invalid="true"], select[aria-invalid="true"] { border-color: var(--_bad); }
134
+ input[type=checkbox], input[type=radio] { width: auto; margin-right: 6px; }
135
+ .row { display: flex; gap: 8px; align-items: flex-end; flex-wrap: wrap; } .row > * { flex: 1 1 120px; } .row > .fixed { flex: 0 0 auto; }
136
+ button { font: inherit; cursor: pointer; border-radius: calc(var(--_r) - 4px); border: 1px solid var(--_line); background: var(--_bg); color: inherit; padding: 7px 12px; }
137
+ button.primary { background: var(--_accfill); border-color: var(--_accfill); color: #fff; }
138
+ button.danger { background: var(--_badfill); border-color: var(--_badfill); color: #fff; }
139
+ button.ok { background: var(--_okfill); border-color: var(--_okfill); color: #fff; }
140
+ button:disabled { opacity: .5; cursor: not-allowed; }
141
+ @media (pointer: coarse) { button, select, input:not([type=checkbox]):not([type=radio]) { min-height: 44px; } }
142
+ .err { color: var(--_bad); font-size: 12.5px; margin: 3px 0 0; }
143
+ .status { padding: 8px 10px; border-radius: calc(var(--_r) - 4px); background: color-mix(in srgb, var(--_accent) 8%, transparent); }
144
+ .status.bad { background: color-mix(in srgb, var(--_bad) 10%, transparent); color: var(--_bad); }
145
+ .status.ok { background: color-mix(in srgb, var(--_ok) 10%, transparent); color: var(--_ok); }
146
+ .pill { display: inline-block; padding: 1px 8px; border-radius: 99px; font-size: 12px; border: 1px solid var(--_line); color: var(--_muted); }
147
+ .bar { height: 8px; border-radius: 99px; background: var(--_line); overflow: hidden; } .bar > i { display: block; height: 100%; background: var(--_accent); }
148
+ .actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; }
149
+ .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
150
+ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
151
+ `;
152
+ var keypadCss = `
153
+ .kp { display: flex; flex-direction: column; gap: 8px; }
154
+ .kp-row { display: flex; align-items: center; gap: 6px; }
155
+ .kp-num { flex: 1; min-width: 0; font-size: 18px; letter-spacing: .5px; text-align: center; min-height: 44px; }
156
+ .kp-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
157
+ .kp-key { min-height: 52px; min-width: 44px; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.1; background: var(--_alt); border-radius: var(--_r); touch-action: manipulation; }
158
+ .kp-key b { font-size: 20px; font-weight: 600; } .kp-key i { font-style: normal; font-size: 9px; letter-spacing: 1px; color: var(--_muted); min-height: 10px; }
159
+ .kp-back { min-width: 44px; min-height: 44px; }
160
+ .kp-calls { display: flex; gap: 6px; } .kp-call { flex: 1; min-height: 46px; color: #fff; font-weight: 600; border: 0; }
161
+ .kp-call[data-channel=whatsapp] { background: var(--_wa); } .kp-call[data-channel=phone] { background: var(--_ph); }
162
+ .kp-note { font-size: 12px; text-align: center; color: var(--_muted); margin: 0; } .kp-note.warn { color: var(--_warn); }
163
+ .btns { display: flex; gap: 8px; margin-top: 12px; } .btns button { flex: 1; min-height: 44px; padding: 10px; }
164
+ .who { font-size: 18px; font-weight: 600; margin: 10px 0 2px; overflow-wrap: anywhere; } .timer { font-variant-numeric: tabular-nums; color: var(--_muted); }
165
+ .recent-list { list-style: none; margin: 6px 0 0; padding: 0; } .recent-list li { display: flex; align-items: center; justify-content: space-between; gap: 8px; border-top: 1px solid var(--_line); }
166
+ .recent-list button { min-height: 44px; flex: 1; text-align: left; border: 0; background: none; padding: 4px 2px; } .recent-list .miss { color: var(--_bad); }
167
+ `;
168
+
169
+ // src/elements/base.js
170
+ var Base = typeof HTMLElement !== "undefined" ? HTMLElement : class {
171
+ };
172
+ var TraitElement = class extends Base {
173
+ constructor() {
174
+ super();
175
+ this._painted = false;
176
+ this._queued = false;
177
+ if (this.attachShadow) {
178
+ this.attachShadow({ mode: "open" });
179
+ this.shadowRoot.addEventListener("click", (e) => {
180
+ var _a2, _b, _c;
181
+ if (this._held) {
182
+ this._held = false;
183
+ return;
184
+ }
185
+ const t2 = (_b = (_a2 = e.target).closest) == null ? void 0 : _b.call(_a2, "[data-action]");
186
+ if (t2 && !t2.disabled) (_c = this.onClick) == null ? void 0 : _c.call(this, t2.dataset.action, t2, e);
187
+ });
188
+ this.shadowRoot.addEventListener("input", (e) => {
189
+ var _a2, _b;
190
+ if ((_a2 = e.target.dataset) == null ? void 0 : _a2.key) (_b = this.onInput) == null ? void 0 : _b.call(this, e.target, e);
191
+ });
192
+ this.shadowRoot.addEventListener("change", (e) => {
193
+ var _a2, _b;
194
+ if ((_a2 = e.target.dataset) == null ? void 0 : _a2.key) (_b = this.onChange) == null ? void 0 : _b.call(this, e.target, e);
195
+ });
196
+ this.shadowRoot.addEventListener("keydown", (e) => {
197
+ var _a2;
198
+ return (_a2 = this.onKey) == null ? void 0 : _a2.call(this, e);
199
+ });
200
+ let holdTimer = null;
201
+ const stopHold = () => {
202
+ clearTimeout(holdTimer);
203
+ holdTimer = null;
204
+ };
205
+ this.shadowRoot.addEventListener("pointerdown", (e) => {
206
+ var _a2, _b;
207
+ const t2 = (_b = (_a2 = e.target).closest) == null ? void 0 : _b.call(_a2, "[data-hold]");
208
+ if (!t2) return;
209
+ stopHold();
210
+ this._held = false;
211
+ holdTimer = setTimeout(() => {
212
+ var _a3;
213
+ holdTimer = null;
214
+ this._held = true;
215
+ (_a3 = this.onHold) == null ? void 0 : _a3.call(this, t2.dataset.hold, t2);
216
+ }, 500);
217
+ });
218
+ for (const ev of ["pointerup", "pointerleave", "pointercancel"]) this.shadowRoot.addEventListener(ev, stopHold);
219
+ this.shadowRoot.addEventListener("submit", (e) => {
220
+ var _a2, _b;
221
+ e.preventDefault();
222
+ const f = (_a2 = e.target.dataset) == null ? void 0 : _a2.submit;
223
+ if (f) (_b = this.onClick) == null ? void 0 : _b.call(this, f, e.target, e);
224
+ });
225
+ }
226
+ }
227
+ connectedCallback() {
228
+ var _a2;
229
+ this._connected = true;
230
+ (_a2 = this.mounted) == null ? void 0 : _a2.call(this);
231
+ this.requestRender();
232
+ }
233
+ disconnectedCallback() {
234
+ var _a2;
235
+ this._connected = false;
236
+ (_a2 = this.unmounted) == null ? void 0 : _a2.call(this);
237
+ }
238
+ /** Repaint on the next microtask, however many times it is asked for. */
239
+ requestRender() {
240
+ if (this._queued || !this.shadowRoot) return;
241
+ this._queued = true;
242
+ queueMicrotask(() => {
243
+ this._queued = false;
244
+ if (this._connected !== false) this.paint();
245
+ });
246
+ }
247
+ paint() {
248
+ var _a2, _b, _c, _d;
249
+ const root = this.shadowRoot;
250
+ const active = root.activeElement;
251
+ const key = (_a2 = active == null ? void 0 : active.dataset) == null ? void 0 : _a2.key;
252
+ const focusId = !key && (active == null ? void 0 : active.id) ? active.id : null;
253
+ const caret = active && "selectionStart" in active ? [active.selectionStart, active.selectionEnd] : null;
254
+ root.innerHTML = `<style>${baseCss}${(_b = this.css) != null ? _b : ""}</style>${this.render()}`;
255
+ if (key) {
256
+ const el = root.querySelector(`[data-key="${CSS.escape(key)}"]`);
257
+ if (el) {
258
+ el.focus();
259
+ if (caret && el.setSelectionRange) {
260
+ try {
261
+ el.setSelectionRange(caret[0], caret[1]);
262
+ } catch {
263
+ }
264
+ }
265
+ }
266
+ } else if (focusId) (_d = (_c = root.getElementById) == null ? void 0 : _c.call(root, focusId)) == null ? void 0 : _d.focus();
267
+ this._painted = true;
268
+ }
269
+ /** A bubbling, composed event, so the host page can listen on the element or above it. */
270
+ emit(name, detail, { cancelable = false } = {}) {
271
+ return this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true, cancelable }));
272
+ }
273
+ };
274
+ function define(tag, ctor) {
275
+ if (typeof customElements !== "undefined" && !customElements.get(tag)) customElements.define(tag, ctor);
276
+ }
277
+
278
+ // src/core/dialpad.js
279
+ var MIN_DIGITS = 7;
280
+ var MAX_LENGTH = 24;
281
+ var KEYS = Object.freeze([
282
+ { d: "1", l: "" },
283
+ { d: "2", l: "ABC" },
284
+ { d: "3", l: "DEF" },
285
+ { d: "4", l: "GHI" },
286
+ { d: "5", l: "JKL" },
287
+ { d: "6", l: "MNO" },
288
+ { d: "7", l: "PQRS" },
289
+ { d: "8", l: "TUV" },
290
+ { d: "9", l: "WXYZ" },
291
+ { d: "*", l: "" },
292
+ { d: "0", l: "+" },
293
+ { d: "#", l: "" }
294
+ ]);
295
+ var CHANNELS = Object.freeze([
296
+ { id: "whatsapp", labelKey: "whatsapp", capKey: "whatsappCallingEnabled" },
297
+ { id: "phone", labelKey: "phoneChannel", capKey: "phoneCallingEnabled" }
298
+ ]);
299
+ var sanitizeNumber = (v) => String(v != null ? v : "").replace(/[^0-9+*#\s-]/g, "").slice(0, MAX_LENGTH);
300
+ var digitsOf = (v) => String(v != null ? v : "").replace(/\D/g, "");
301
+ var canCall = (v) => digitsOf(v).length >= MIN_DIGITS;
302
+ var enabledChannels = (caps) => CHANNELS.filter((c) => caps && caps[c.capKey]).map((c) => c.id);
303
+ function defaultChannel(caps, preferred) {
304
+ var _a2;
305
+ const on = enabledChannels(caps);
306
+ if (preferred && on.includes(preferred)) return preferred;
307
+ return on.includes("whatsapp") ? "whatsapp" : (_a2 = on[0]) != null ? _a2 : null;
308
+ }
309
+ function capsFromLines(lines) {
310
+ const has = (c) => (lines || []).some((l) => Array.isArray(l == null ? void 0 : l.channels) && l.channels.includes(c));
311
+ return { whatsappCallingEnabled: has("whatsapp_calling"), phoneCallingEnabled: has("voice") };
312
+ }
313
+ function createDialpad(opts2 = {}) {
314
+ let number = "";
315
+ let caps = opts2.caps || {};
316
+ let onCall = opts2.onCall;
317
+ const listeners = /* @__PURE__ */ new Set();
318
+ const set = (v) => {
319
+ number = sanitizeNumber(v);
320
+ listeners.forEach((fn) => fn());
321
+ };
322
+ const api = {
323
+ get number() {
324
+ return number;
325
+ },
326
+ get caps() {
327
+ return caps;
328
+ },
329
+ get digits() {
330
+ return digitsOf(number);
331
+ },
332
+ get canCall() {
333
+ return canCall(number);
334
+ },
335
+ get channels() {
336
+ return enabledChannels(caps);
337
+ },
338
+ get nothingEnabled() {
339
+ return enabledChannels(caps).length === 0;
340
+ },
341
+ setNumber: set,
342
+ press: (d) => set(number + d),
343
+ /** Long-press on 0: a "+" when the box is empty, otherwise an ordinary 0. */
344
+ pressZeroLong: () => set(number ? number + "0" : "+"),
345
+ backspace: () => set(number.slice(0, -1)),
346
+ clear: () => set(""),
347
+ setCaps(next) {
348
+ caps = next || {};
349
+ listeners.forEach((fn) => fn());
350
+ },
351
+ setOnCall(fn) {
352
+ onCall = fn;
353
+ },
354
+ /** Returns true when `onCall` was invoked. A disabled channel or a short number never calls. */
355
+ call(channel) {
356
+ if (!canCall(number) || !enabledChannels(caps).includes(channel) || typeof onCall !== "function") return false;
357
+ const payload = { number: digitsOf(number), channel };
358
+ if (opts2.clearOnCall !== false) number = "";
359
+ listeners.forEach((fn) => fn());
360
+ onCall(payload);
361
+ return true;
362
+ },
363
+ /** Enter key. */
364
+ submit() {
365
+ const ch = defaultChannel(caps, opts2.defaultChannel);
366
+ return ch ? api.call(ch) : false;
367
+ },
368
+ subscribe(fn) {
369
+ listeners.add(fn);
370
+ return () => listeners.delete(fn);
371
+ }
372
+ };
373
+ return api;
374
+ }
375
+
376
+ // src/core/strings.js
377
+ var DEFAULT_STRINGS = Object.freeze({
378
+ softphone: "Softphone",
379
+ phone: "Phone",
380
+ off: "Softphone off",
381
+ connecting: "Connecting\u2026",
382
+ ready: "Ready for calls",
383
+ ringing: "Incoming call",
384
+ inCall: "On a call",
385
+ error: "Softphone error",
386
+ goOnline: "Go online",
387
+ goOffline: "Go offline",
388
+ tryAgain: "Try again",
389
+ goOnlineHint: "Go online to receive calls in this browser. Allow microphone access when asked.",
390
+ waiting: "Waiting for calls",
391
+ waitingAs: "Waiting for calls as {name}.",
392
+ isCalling: "is calling",
393
+ answer: "Answer",
394
+ decline: "Decline",
395
+ hangUp: "Hang up",
396
+ mute: "Mute",
397
+ unmute: "Unmute",
398
+ hold: "Hold",
399
+ resume: "Resume",
400
+ onHold: "On hold",
401
+ onACall: "On a call",
402
+ showKeypad: "Keypad",
403
+ hideKeypad: "Hide keypad",
404
+ sendingDigits: "Tap a key to send it to the caller",
405
+ callEnded: "Call ended",
406
+ callEndedFor: "Call ended \xB7 {time}",
407
+ missedCall: "Missed call",
408
+ placing: "Calling {number}\u2026 your browser will ring when the line connects.",
409
+ numberLabel: "Number to call",
410
+ numberPlaceholder: "Number with country code",
411
+ backspace: "Delete last digit",
412
+ keypad: "Keypad",
413
+ callOn: "Call on {channel}",
414
+ whatsapp: "WhatsApp",
415
+ phoneChannel: "Phone",
416
+ callingOff: "Calling is off for this workspace.",
417
+ needCountryCode: "Include the country code, e.g. 1876\u2026",
418
+ keyZero: "0, hold for plus",
419
+ keyStar: "star",
420
+ keyHash: "hash",
421
+ recent: "Recent calls",
422
+ noRecent: "No recent calls yet.",
423
+ redial: "Call {who} again",
424
+ incoming: "Incoming",
425
+ outgoing: "Outgoing",
426
+ missed: "Missed",
427
+ openPhone: "Open phone",
428
+ closePhone: "Close phone",
429
+ missedBadge: "{n} missed calls",
430
+ dialogLabel: "Phone",
431
+ needSetup: "Set the client and adapter properties first.",
432
+ goOnlineFirst: "Go online first to place calls.",
433
+ badNumber: "Enter the number as +, then country code and number.",
434
+ whatsappNotConfigured: "WhatsApp calling is not set up for this page (set the whatsapp property).",
435
+ micBlocked: "Microphone access is blocked. Allow it in your browser settings, then try again.",
436
+ sessionExpired: "Your session expired. Reload the page or sign in again.",
437
+ connectionLost: "Connection lost. Try again.",
438
+ unstable: "Connection to TraitOS is unstable.",
439
+ sound: "Sound",
440
+ soundOn: "Sounds on",
441
+ volume: "Volume",
442
+ keyTone: "Key sound",
443
+ keyToneDtmf: "Phone tones",
444
+ keyToneClick: "Click",
445
+ keyToneOff: "None",
446
+ ringtone: "Ringtone",
447
+ ringClassic: "Classic",
448
+ ringSoft: "Soft",
449
+ ringOff: "Silent",
450
+ speakDigits: "Say each digit aloud",
451
+ voice: "Voice",
452
+ voiceDefault: "Browser default",
453
+ voiceRate: "Speaking speed",
454
+ soundTest: "Test sound",
455
+ couldNotCall: "Could not place the call",
456
+ noIdentity: "This account has no softphone identity yet.",
457
+ couldNotLoad: "Could not load this section."
458
+ });
459
+ var defaults = {};
460
+ function setDefaultStrings(overrides) {
461
+ defaults = { ...overrides || {} };
462
+ }
463
+ var stringsFor = (own) => ({ ...DEFAULT_STRINGS, ...defaults, ...own || {} });
464
+ function t(S, key, vars) {
465
+ var _a2, _b;
466
+ const s = (_b = (_a2 = S == null ? void 0 : S[key]) != null ? _a2 : DEFAULT_STRINGS[key]) != null ? _b : key;
467
+ return vars ? String(s).replace(/\{(\w+)\}/g, (m, k) => {
468
+ var _a3;
469
+ return (_a3 = vars[k]) != null ? _a3 : m;
470
+ }) : String(s);
471
+ }
472
+
473
+ // src/core/sound.js
474
+ var DTMF_FREQ = Object.freeze({
475
+ 1: [697, 1209],
476
+ 2: [697, 1336],
477
+ 3: [697, 1477],
478
+ 4: [770, 1209],
479
+ 5: [770, 1336],
480
+ 6: [770, 1477],
481
+ 7: [852, 1209],
482
+ 8: [852, 1336],
483
+ 9: [852, 1477],
484
+ "*": [941, 1209],
485
+ 0: [941, 1336],
486
+ "#": [941, 1477]
487
+ });
488
+ var KEY_TONES = Object.freeze(["dtmf", "click", "off"]);
489
+ var RINGTONES = Object.freeze({ classic: [[440, 480], 2e3, 4e3], soft: [[523, 659], 1e3, 3e3], off: null });
490
+ var DEFAULT_SOUND = Object.freeze({ enabled: true, volume: 0.5, keyTone: "dtmf", ringtone: "classic", speak: false, voice: "", rate: 1 });
491
+ var KEY = "traitos.sound";
492
+ var SPOKEN = { "*": "star", "#": "pound", "+": "plus" };
493
+ function normalizeSound(p = {}) {
494
+ const vol = Number(p == null ? void 0 : p.volume);
495
+ const rate = Number(p == null ? void 0 : p.rate);
496
+ return {
497
+ enabled: (p == null ? void 0 : p.enabled) !== false,
498
+ volume: Number.isFinite(vol) ? Math.min(1, Math.max(0, vol)) : DEFAULT_SOUND.volume,
499
+ keyTone: KEY_TONES.includes(p == null ? void 0 : p.keyTone) ? p.keyTone : DEFAULT_SOUND.keyTone,
500
+ ringtone: Object.prototype.hasOwnProperty.call(RINGTONES, p == null ? void 0 : p.ringtone) ? p.ringtone : DEFAULT_SOUND.ringtone,
501
+ speak: (p == null ? void 0 : p.speak) === true,
502
+ voice: typeof (p == null ? void 0 : p.voice) === "string" ? p.voice : "",
503
+ rate: Number.isFinite(rate) ? Math.min(2, Math.max(0.5, rate)) : 1
504
+ };
505
+ }
506
+ function loadSound(storage) {
507
+ try {
508
+ return normalizeSound(JSON.parse((storage == null ? void 0 : storage.getItem(KEY)) || "{}"));
509
+ } catch {
510
+ return normalizeSound();
511
+ }
512
+ }
513
+ function saveSound(storage, s) {
514
+ try {
515
+ storage == null ? void 0 : storage.setItem(KEY, JSON.stringify(normalizeSound(s)));
516
+ } catch {
517
+ }
518
+ }
519
+ function createSound({ storage, audio, speech, Utterance, settings } = {}) {
520
+ let s = settings ? normalizeSound(settings) : loadSound(storage);
521
+ let ctx = null;
522
+ let ring = null;
523
+ const listeners = /* @__PURE__ */ new Set();
524
+ const synth = speech != null ? speech : globalThis.speechSynthesis;
525
+ const Utt = Utterance != null ? Utterance : globalThis.SpeechSynthesisUtterance;
526
+ const getCtx = () => {
527
+ var _a2, _b, _c;
528
+ if (ctx) return ctx;
529
+ try {
530
+ const make = audio != null ? audio : (() => new (globalThis.AudioContext || globalThis.webkitAudioContext)());
531
+ ctx = make();
532
+ } catch {
533
+ ctx = null;
534
+ }
535
+ if ((ctx == null ? void 0 : ctx.state) === "suspended") (_c = (_a2 = ctx.resume) == null ? void 0 : (_b = _a2.call(ctx)).catch) == null ? void 0 : _c.call(_b, () => {
536
+ });
537
+ return ctx;
538
+ };
539
+ function tone(freqs, ms, gain = 1) {
540
+ const c = getCtx();
541
+ if (!c) return () => {
542
+ };
543
+ const g = c.createGain();
544
+ const t0 = c.currentTime;
545
+ const t1 = t0 + ms / 1e3;
546
+ const level = 0.25 * s.volume * gain;
547
+ g.gain.setValueAtTime(1e-4, t0);
548
+ g.gain.linearRampToValueAtTime(level, t0 + 8e-3);
549
+ g.gain.setValueAtTime(level, Math.max(t0 + 8e-3, t1 - 0.02));
550
+ g.gain.linearRampToValueAtTime(1e-4, t1);
551
+ g.connect(c.destination);
552
+ const oscs = freqs.map((f) => {
553
+ const o = c.createOscillator();
554
+ o.type = "sine";
555
+ o.frequency.value = f;
556
+ o.connect(g);
557
+ o.start(t0);
558
+ o.stop(t1 + 0.02);
559
+ return o;
560
+ });
561
+ return () => {
562
+ try {
563
+ oscs.forEach((o) => o.stop());
564
+ g.disconnect();
565
+ } catch {
566
+ }
567
+ };
568
+ }
569
+ const on = () => s.enabled && s.volume > 0;
570
+ const api = {
571
+ get settings() {
572
+ return { ...s };
573
+ },
574
+ update(patch) {
575
+ s = normalizeSound({ ...s, ...patch });
576
+ saveSound(storage, s);
577
+ if (!on()) api.stopRing();
578
+ listeners.forEach((fn) => fn());
579
+ },
580
+ subscribe(fn) {
581
+ listeners.add(fn);
582
+ return () => listeners.delete(fn);
583
+ },
584
+ /** A key press: the DTMF pair for that key, or a click, per the settings; plus the spoken digit when that is on. */
585
+ key(d) {
586
+ var _a2;
587
+ if (!on()) return;
588
+ if (s.keyTone === "dtmf" && DTMF_FREQ[d]) tone(DTMF_FREQ[d], 120);
589
+ else if (s.keyTone === "click") api.click();
590
+ else if (s.keyTone === "dtmf") api.click();
591
+ if (s.speak) api.say((_a2 = SPOKEN[d]) != null ? _a2 : d);
592
+ },
593
+ /** A short click for non-digit buttons (backspace, call, mute). */
594
+ click() {
595
+ if (on() && s.keyTone !== "off") tone([1800], 14, 0.9);
596
+ },
597
+ /** Speak text in the chosen voice (if speech is available). Cancels what was being said. */
598
+ say(text) {
599
+ var _a2, _b;
600
+ if (!s.enabled || !synth || !Utt) return false;
601
+ try {
602
+ (_a2 = synth.cancel) == null ? void 0 : _a2.call(synth);
603
+ const u = new Utt(String(text));
604
+ u.volume = Math.max(0.05, s.volume);
605
+ u.rate = s.rate;
606
+ const v = s.voice && ((_b = synth.getVoices) == null ? void 0 : _b.call(synth).find((x) => x.voiceURI === s.voice));
607
+ if (v) {
608
+ u.voice = v;
609
+ u.lang = v.lang;
610
+ }
611
+ synth.speak(u);
612
+ return true;
613
+ } catch {
614
+ return false;
615
+ }
616
+ },
617
+ /** Installed voices as `{ id, label }` (empty when the browser has none or has not loaded them yet). */
618
+ voices() {
619
+ var _a2, _b;
620
+ try {
621
+ return ((_b = (_a2 = synth == null ? void 0 : synth.getVoices) == null ? void 0 : _a2.call(synth)) != null ? _b : []).map((v) => ({ id: v.voiceURI, label: `${v.name} (${v.lang})` }));
622
+ } catch {
623
+ return [];
624
+ }
625
+ },
626
+ /** Ring until stopRing(): two-tone bursts on a cadence. */
627
+ startRing() {
628
+ if (ring || !on()) return;
629
+ const def = RINGTONES[s.ringtone];
630
+ if (!def) return;
631
+ const [freqs, burst, gap] = def;
632
+ const state = { stop: () => {
633
+ }, timer: null };
634
+ const beat = () => {
635
+ state.stop = tone(freqs, burst, 0.8);
636
+ state.timer = setTimeout(beat, burst + gap);
637
+ };
638
+ ring = state;
639
+ beat();
640
+ },
641
+ stopRing() {
642
+ if (!ring) return;
643
+ clearTimeout(ring.timer);
644
+ ring.stop();
645
+ ring = null;
646
+ },
647
+ get ringing() {
648
+ return Boolean(ring);
649
+ },
650
+ /** Two falling beeps when a call ends. */
651
+ end() {
652
+ if (!on()) return;
653
+ tone([480], 140, 0.8);
654
+ setTimeout(() => tone([380], 200, 0.8), 170);
655
+ },
656
+ /** Preview for the options panel. */
657
+ test() {
658
+ api.key("5");
659
+ if (s.speak) api.say("Five");
660
+ }
661
+ };
662
+ return api;
663
+ }
664
+
665
+ // src/elements/keypad.js
666
+ var keyLabel = (S, d) => d === "0" ? S.keyZero : d === "*" ? S.keyStar : d === "#" ? S.keyHash : d;
667
+ function renderKeypad(dp, { S = stringsFor(), mode = "dial", busy = false } = {}) {
668
+ const dtmf = mode === "dtmf";
669
+ const calls2 = CHANNELS.filter((c) => dp.channels.includes(c.id));
670
+ const note = dtmf ? html`<p class="kp-note" role="status">${S.sendingDigits}</p>` : dp.nothingEnabled ? html`<p class="kp-note warn" role="status">${S.callingOff}</p>` : dp.number && !dp.canCall ? html`<p class="kp-note" role="status">${S.needCountryCode}</p>` : "";
671
+ return html`<div class="kp" role="group" aria-label="${S.keypad}" data-at="dial-pad">
672
+ ${dtmf ? "" : html`<div class="kp-row"><input class="kp-num" id="kp-number" data-key="dialpad-number" type="tel" inputmode="tel" autocomplete="off" maxlength="24" placeholder="${S.numberPlaceholder}" aria-label="${S.numberLabel}" value="${dp.number}" data-at="dial-pad-input" />
673
+ <button type="button" class="kp-back" data-action="kp-back" aria-label="${S.backspace}" ${dp.number ? "" : "disabled"} data-at="dial-pad-backspace">⌫</button></div>`}
674
+ <div class="kp-grid">${KEYS.map((k) => html`<button type="button" class="kp-key" data-action="${dtmf ? "kp-dtmf" : "kp-key"}" data-d="${k.d}" ${k.d === "0" && !dtmf ? raw('data-hold="zero"') : ""} aria-label="${keyLabel(S, k.d)}" data-at="dial-pad-key-${k.d}"><b aria-hidden="true">${k.d}</b><i aria-hidden="true">${k.l}</i></button>`)}</div>
675
+ ${dtmf || !calls2.length ? "" : html`<div class="kp-calls">${calls2.map((c) => html`<button type="button" class="kp-call" data-action="kp-call" data-channel="${c.id}" aria-label="${t(S, "callOn", { channel: S[c.labelKey] })}" ${dp.canCall && !busy ? "" : "disabled"} data-at="dial-pad-call-${c.id}">${S[c.labelKey]}</button>`)}</div>`}
676
+ ${note}
677
+ </div>`;
678
+ }
679
+ function keypadClick(dp, action, node, { onDtmf } = {}) {
680
+ if (action === "kp-key") {
681
+ dp.press(node.dataset.d);
682
+ return true;
683
+ }
684
+ if (action === "kp-back") {
685
+ dp.backspace();
686
+ return true;
687
+ }
688
+ if (action === "kp-call") {
689
+ dp.call(node.dataset.channel);
690
+ return true;
691
+ }
692
+ if (action === "kp-dtmf") {
693
+ onDtmf == null ? void 0 : onDtmf(node.dataset.d);
694
+ return true;
695
+ }
696
+ return false;
697
+ }
698
+ function keypadInput(dp, target) {
699
+ var _a2;
700
+ if (((_a2 = target.dataset) == null ? void 0 : _a2.key) !== "dialpad-number") return false;
701
+ dp.setNumber(target.value);
702
+ return true;
703
+ }
704
+ function keypadKey(dp, e) {
705
+ var _a2, _b;
706
+ if (e.key === "Enter" && ((_b = (_a2 = e.target) == null ? void 0 : _a2.dataset) == null ? void 0 : _b.key) === "dialpad-number") {
707
+ e.preventDefault();
708
+ dp.submit();
709
+ return true;
710
+ }
711
+ return false;
712
+ }
713
+ function keypadHold(dp, what) {
714
+ if (what === "zero") {
715
+ dp.pressZeroLong();
716
+ return true;
717
+ }
718
+ return false;
719
+ }
720
+ var TraitOSKeypad = class extends TraitElement {
721
+ static get observedAttributes() {
722
+ return ["whatsapp-calling", "phone-calling", "theme"];
723
+ }
724
+ constructor() {
725
+ super();
726
+ this.dp = createDialpad({ onCall: (c) => this.emit("traitos-call", c) });
727
+ this.dp.subscribe(() => this.requestRender());
728
+ }
729
+ get css() {
730
+ return keypadCss + ":host{max-width:280px}";
731
+ }
732
+ get caps() {
733
+ var _a2;
734
+ return (_a2 = this._caps) != null ? _a2 : this._attrCaps();
735
+ }
736
+ set caps(v) {
737
+ this._caps = v;
738
+ this.dp.setCaps(v);
739
+ }
740
+ set strings(v) {
741
+ this._strings = v;
742
+ this.requestRender();
743
+ }
744
+ _attrCaps() {
745
+ return { whatsappCallingEnabled: this.hasAttribute("whatsapp-calling"), phoneCallingEnabled: this.hasAttribute("phone-calling") };
746
+ }
747
+ mounted() {
748
+ this.dp.setCaps(this.caps);
749
+ }
750
+ attributeChangedCallback() {
751
+ if (!this._caps) this.dp.setCaps(this._attrCaps());
752
+ this.requestRender();
753
+ }
754
+ render() {
755
+ return `<div class="card">${renderKeypad(this.dp, { S: stringsFor(this._strings) })}</div>`;
756
+ }
757
+ /** Key tones for the standalone keypad; replace to supply your own, or set `sound.update({ enabled: false })`. */
758
+ get sound() {
759
+ var _a2;
760
+ return (_a2 = this._sound) != null ? _a2 : this._sound = createSound({ storage: typeof localStorage !== "undefined" ? localStorage : void 0 });
761
+ }
762
+ set sound(v) {
763
+ this._sound = v;
764
+ }
765
+ onClick(a, n) {
766
+ if (a === "kp-key") this.sound.key(n.dataset.d);
767
+ else if (a === "kp-back" || a === "kp-call") this.sound.click();
768
+ keypadClick(this.dp, a, n);
769
+ }
770
+ onInput(t2) {
771
+ keypadInput(this.dp, t2);
772
+ }
773
+ onKey(e) {
774
+ var _a2, _b;
775
+ if (((_b = (_a2 = e.target) == null ? void 0 : _a2.dataset) == null ? void 0 : _b.key) === "dialpad-number" && e.key.length === 1 && /[0-9*#]/.test(e.key) && !e.ctrlKey && !e.metaKey) this.sound.key(e.key);
776
+ keypadKey(this.dp, e);
777
+ }
778
+ onHold(w) {
779
+ if (keypadHold(this.dp, w)) this.sound.key("+");
780
+ }
781
+ };
782
+ define("traitos-keypad", TraitOSKeypad);
783
+
784
+ // src/core/softphoneState.js
785
+ var SOFTPHONE_HEARTBEAT_MS = 6e4;
786
+ function stateForCall(direction, callState) {
787
+ switch (callState) {
788
+ case "ringing":
789
+ return direction === "inbound" ? "ringing" : null;
790
+ case "answering":
791
+ case "active":
792
+ case "held":
793
+ case "early":
794
+ return "in-call";
795
+ case "hangup":
796
+ case "destroy":
797
+ case "done":
798
+ return "ready";
799
+ default:
800
+ return null;
801
+ }
802
+ }
803
+ var softphoneLabel = {
804
+ off: "Softphone off",
805
+ connecting: "Connecting\u2026",
806
+ ready: "Ready for calls",
807
+ ringing: "Incoming call",
808
+ "in-call": "On a call",
809
+ error: "Softphone error"
810
+ };
811
+ function callerLabel(opts2) {
812
+ const name = ((opts2 == null ? void 0 : opts2.remoteCallerName) || (opts2 == null ? void 0 : opts2.callerName) || "").trim();
813
+ const num = ((opts2 == null ? void 0 : opts2.remoteCallerNumber) || (opts2 == null ? void 0 : opts2.callerNumber) || "").trim();
814
+ if (name && num && name !== num) return `${name} (${num})`;
815
+ return name || num || "Unknown caller";
816
+ }
817
+ function formatDuration(ms) {
818
+ const s = Math.max(0, Math.floor(ms / 1e3));
819
+ const h = Math.floor(s / 3600), m = Math.floor(s % 3600 / 60), sec = s % 60;
820
+ const mm = h ? String(m).padStart(2, "0") : String(m);
821
+ return `${h ? `${h}:` : ""}${mm}:${String(sec).padStart(2, "0")}`;
822
+ }
823
+ function cleanDialInput(value) {
824
+ const v = String(value != null ? value : "").replace(/[^\d+]/g, "");
825
+ return (v.startsWith("+") ? "+" : "") + v.replace(/\+/g, "");
826
+ }
827
+ var isE164 = (n) => /^\+[1-9]\d{6,14}$/.test(String(n != null ? n : ""));
828
+
829
+ // src/core/callLog.js
830
+ var KEY2 = "traitos.calllog";
831
+ var CallLog = class {
832
+ constructor({ storage, max = 10, now = Date.now } = {}) {
833
+ this.storage = storage;
834
+ this.max = max;
835
+ this.now = now;
836
+ this.listeners = /* @__PURE__ */ new Set();
837
+ this.entries = this._read();
838
+ this.seenAt = this._seen();
839
+ }
840
+ _read() {
841
+ var _a2;
842
+ try {
843
+ const v = JSON.parse(((_a2 = this.storage) == null ? void 0 : _a2.getItem(KEY2)) || "[]");
844
+ return Array.isArray(v) ? v.slice(0, this.max) : [];
845
+ } catch {
846
+ return [];
847
+ }
848
+ }
849
+ _seen() {
850
+ var _a2;
851
+ try {
852
+ return Number((_a2 = this.storage) == null ? void 0 : _a2.getItem(`${KEY2}.seen`)) || 0;
853
+ } catch {
854
+ return 0;
855
+ }
856
+ }
857
+ _save() {
858
+ var _a2, _b;
859
+ try {
860
+ (_a2 = this.storage) == null ? void 0 : _a2.setItem(KEY2, JSON.stringify(this.entries));
861
+ (_b = this.storage) == null ? void 0 : _b.setItem(`${KEY2}.seen`, String(this.seenAt));
862
+ } catch {
863
+ }
864
+ }
865
+ subscribe(fn) {
866
+ this.listeners.add(fn);
867
+ return () => this.listeners.delete(fn);
868
+ }
869
+ /** @param {{who: string, number?: string|null, direction: 'in'|'out', outcome: 'answered'|'missed', durationMs?: number}} e */
870
+ add(e) {
871
+ this.entries = [{ ...e, at: this.now() }, ...this.entries].slice(0, this.max);
872
+ this._save();
873
+ this.listeners.forEach((fn) => fn());
874
+ }
875
+ list() {
876
+ return this.entries.map((e) => ({ ...e }));
877
+ }
878
+ /** Missed inbound calls since the log was last marked seen (the widget's badge). */
879
+ missedCount() {
880
+ return this.entries.filter((e) => e.outcome === "missed" && e.at > this.seenAt).length;
881
+ }
882
+ markSeen() {
883
+ this.seenAt = this.now();
884
+ this._save();
885
+ this.listeners.forEach((fn) => fn());
886
+ }
887
+ clear() {
888
+ this.entries = [];
889
+ this._save();
890
+ this.listeners.forEach((fn) => fn());
891
+ }
892
+ };
893
+
894
+ // src/core/softphoneController.js
895
+ var PLACING_MS = 45e3;
896
+ var DTMF = /^[0-9A-D*#]$/i;
897
+ var isMicDenied = (e) => (e == null ? void 0 : e.name) === "NotAllowedError" || (e == null ? void 0 : e.name) === "SecurityError" || /permission denied|microphone.*(denied|blocked)|not allowed/i.test((e == null ? void 0 : e.message) || "");
898
+ var SoftphoneController = class {
899
+ /**
900
+ * @param {{client: object, adapter: object, numbers?: string[], ringTimeoutSeconds?: number, liveEvents?: boolean, heartbeatMs?: number,
901
+ * timers?: {setInterval: Function, clearInterval: Function, setTimeout?: Function, clearTimeout?: Function}, now?: () => number,
902
+ * whatsapp?: object, log?: CallLog, media?: {getUserMedia: Function}|null, strings?: object}} options
903
+ * `whatsapp` holds what a WhatsApp call needs (`from`, `sipHostname`, `sipPassword`, ...); without it only phone calls can be placed.
904
+ */
905
+ constructor({ client, adapter, numbers, ringTimeoutSeconds, liveEvents = false, heartbeatMs = SOFTPHONE_HEARTBEAT_MS, timers, now = Date.now, whatsapp: whatsapp2, log, media, strings }) {
906
+ var _a2, _b;
907
+ this.client = client;
908
+ this.adapter = adapter;
909
+ this.numbers = numbers;
910
+ this.ringTimeoutSeconds = ringTimeoutSeconds;
911
+ this.liveEvents = liveEvents;
912
+ this.heartbeatMs = heartbeatMs;
913
+ this.timers = { setTimeout: (f, ms) => setTimeout(f, ms), clearTimeout: (h) => clearTimeout(h), ...timers != null ? timers : { setInterval: (f, ms) => setInterval(f, ms), clearInterval: (h) => clearInterval(h) } };
914
+ this.now = now;
915
+ this.whatsapp = whatsapp2;
916
+ this.log = log != null ? log : new CallLog({ now });
917
+ this.media = media === void 0 ? (_b = (_a2 = globalThis.navigator) == null ? void 0 : _a2.mediaDevices) != null ? _b : null : media;
918
+ this.S = { ...DEFAULT_STRINGS, ...strings || {} };
919
+ 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: [] };
920
+ this._call = null;
921
+ this._listeners = /* @__PURE__ */ new Set();
922
+ this._heartbeat = null;
923
+ this._sub = null;
924
+ this._wired = false;
925
+ this._gen = 0;
926
+ this._failures = 0;
927
+ this._placingTimer = null;
928
+ this._current = null;
929
+ }
930
+ snapshot() {
931
+ return { ...this.state, recent: [...this.state.recent] };
932
+ }
933
+ /** Subscribe to state changes. Returns an unsubscribe function. */
934
+ subscribe(fn) {
935
+ this._listeners.add(fn);
936
+ return () => this._listeners.delete(fn);
937
+ }
938
+ _set(patch) {
939
+ this.state = { ...this.state, ...patch };
940
+ for (const fn of [...this._listeners]) {
941
+ try {
942
+ fn(this.snapshot());
943
+ } catch {
944
+ }
945
+ }
946
+ }
947
+ _wire() {
948
+ if (this._wired) return;
949
+ this._wired = true;
950
+ this.adapter.on("ready", () => {
951
+ if (this.state.status === "connecting") this._set({ status: "ready" });
952
+ });
953
+ this.adapter.on("error", (e) => this._fail(e));
954
+ this.adapter.on("close", () => {
955
+ if (this.state.status !== "off" && this.state.status !== "error") {
956
+ this._teardown();
957
+ this._fail(Object.assign(new Error(this.S.connectionLost), { code: "connection-lost" }));
958
+ }
959
+ });
960
+ this.adapter.on("call", (call) => this._onCall(call));
961
+ }
962
+ async _checkMic() {
963
+ var _a2, _b;
964
+ if (!((_a2 = this.media) == null ? void 0 : _a2.getUserMedia)) return;
965
+ const stream = await this.media.getUserMedia({ audio: true });
966
+ (_b = stream == null ? void 0 : stream.getTracks) == null ? void 0 : _b.call(stream).forEach((tr) => tr.stop());
967
+ }
968
+ async start() {
969
+ if (this.state.status !== "off" && this.state.status !== "error") return;
970
+ const gen = ++this._gen;
971
+ this._set({ status: "connecting", error: null, errorCode: null, warning: null });
972
+ try {
973
+ await this._checkMic();
974
+ const { token, sipUsername } = await this.client.softphone.token();
975
+ if (gen !== this._gen) return;
976
+ if (!token || !sipUsername) throw new Error(this.S.noIdentity);
977
+ this._wire();
978
+ this._set({ sipUsername });
979
+ await this.adapter.connect({ token, sipUsername });
980
+ if (gen !== this._gen) return;
981
+ await this._register();
982
+ if (gen !== this._gen) return;
983
+ this._failures = 0;
984
+ this._heartbeat = this.timers.setInterval(() => this._beat(), this.heartbeatMs);
985
+ if (this.liveEvents) this._watchEvents();
986
+ } catch (error) {
987
+ if (gen !== this._gen) return;
988
+ this._teardown();
989
+ try {
990
+ await this.adapter.disconnect();
991
+ } catch {
992
+ }
993
+ this._fail(error);
994
+ }
995
+ }
996
+ async stop() {
997
+ var _a2, _b;
998
+ this._gen++;
999
+ const sip = this.state.sipUsername;
1000
+ this._teardown();
1001
+ try {
1002
+ (_b = (_a2 = this._call) == null ? void 0 : _a2.hangup) == null ? void 0 : _b.call(_a2);
1003
+ } catch {
1004
+ }
1005
+ try {
1006
+ await this.adapter.disconnect();
1007
+ } catch {
1008
+ }
1009
+ if (sip) await this.client.softphone.unregister(sip).catch(() => {
1010
+ });
1011
+ this._call = null;
1012
+ this._current = null;
1013
+ this._set({ status: "off", caller: null, muted: false, held: false, startedAt: null, placing: null, warning: null });
1014
+ }
1015
+ /** Stop the timers and the live feed (used by stop, by a failed start and by a dropped connection). */
1016
+ _teardown() {
1017
+ var _a2, _b;
1018
+ if (this._heartbeat) this.timers.clearInterval(this._heartbeat);
1019
+ this._heartbeat = null;
1020
+ (_b = (_a2 = this._sub) == null ? void 0 : _a2.close) == null ? void 0 : _b.call(_a2);
1021
+ this._sub = null;
1022
+ this._clearPlacing();
1023
+ }
1024
+ _register() {
1025
+ const n = this.numbers;
1026
+ return this.client.softphone.register({ sipUsername: this.state.sipUsername, ...n && n.length ? { numbers: n } : {}, ...this.ringTimeoutSeconds ? { ringTimeoutSeconds: this.ringTimeoutSeconds } : {} });
1027
+ }
1028
+ /** Renews the registration. An expired token ends the session loudly; a flaky network warns after three misses. */
1029
+ async _beat() {
1030
+ try {
1031
+ await this._register();
1032
+ this._failures = 0;
1033
+ if (this.state.warning) this._set({ warning: null });
1034
+ } catch (error) {
1035
+ if ((error == null ? void 0 : error.status) === 401 || (error == null ? void 0 : error.status) === 403) {
1036
+ this._teardown();
1037
+ try {
1038
+ await this.adapter.disconnect();
1039
+ } catch {
1040
+ }
1041
+ this._fail(Object.assign(new Error(this.S.sessionExpired), { code: "session-expired" }));
1042
+ } else if (++this._failures >= 3 && !this.state.warning) this._set({ warning: this.S.unstable });
1043
+ }
1044
+ }
1045
+ _watchEvents() {
1046
+ this._sub = this.client.events.subscribe((e) => {
1047
+ const recent = [{ type: e.type, at: e.created_at, id: e.id }, ...this.state.recent].slice(0, 5);
1048
+ this._set({ recent });
1049
+ }, { types: ["call.*"], onError: () => {
1050
+ } });
1051
+ }
1052
+ _fail(error) {
1053
+ var _a2;
1054
+ const denied = isMicDenied(error);
1055
+ this._set({ status: "error", error: denied ? this.S.micBlocked : (error == null ? void 0 : error.message) || this.S.error, errorCode: denied ? "mic-denied" : (_a2 = error == null ? void 0 : error.code) != null ? _a2 : null, caller: null, held: false, muted: false, startedAt: null, dialing: false });
1056
+ }
1057
+ _clearPlacing() {
1058
+ if (this._placingTimer) this.timers.clearTimeout(this._placingTimer);
1059
+ this._placingTimer = null;
1060
+ if (this.state.placing) this.state = { ...this.state, placing: null };
1061
+ }
1062
+ _finish(outcome) {
1063
+ const c = this._current;
1064
+ this._current = null;
1065
+ if (!c) return;
1066
+ const durationMs = c.answeredAt ? this.now() - c.answeredAt : 0;
1067
+ const result = c.answeredAt ? "answered" : "missed";
1068
+ this.log.add({ who: c.who, number: c.number, direction: c.direction === "inbound" ? "in" : "out", outcome: outcome != null ? outcome : result, durationMs });
1069
+ this._set({ lastCall: { who: c.who, durationMs, outcome: outcome != null ? outcome : result, at: this.now() } });
1070
+ }
1071
+ _onCall(call) {
1072
+ var _a2, _b, _c, _d, _e;
1073
+ this._call = call;
1074
+ const next = stateForCall(call.direction, call.state);
1075
+ if (!next) return;
1076
+ if (this.state.placing) {
1077
+ this._clearPlacing();
1078
+ }
1079
+ if (next === "ringing") {
1080
+ this._current = { who: callerLabel(call), number: call.remoteCallerNumber || null, direction: "inbound", answeredAt: null };
1081
+ this._set({ status: "ringing", caller: callerLabel(call), muted: false, held: false, lastCall: null, placing: null });
1082
+ } else if (next === "in-call") {
1083
+ (_a2 = this._current) != null ? _a2 : this._current = { who: callerLabel(call), number: call.remoteCallerNumber || null, direction: call.direction, answeredAt: null };
1084
+ (_c = (_b = this._current).answeredAt) != null ? _c : _b.answeredAt = this.now();
1085
+ this._set({ status: "in-call", startedAt: (_d = this.state.startedAt) != null ? _d : this.now(), caller: (_e = this.state.caller) != null ? _e : callerLabel(call), held: call.state === "held", lastCall: null, placing: null });
1086
+ } else {
1087
+ this._call = null;
1088
+ this._finish();
1089
+ this._set({ status: "ready", caller: null, muted: false, held: false, startedAt: null });
1090
+ }
1091
+ }
1092
+ /** Feed a call update by hand (adapters usually do this through the 'call' event). */
1093
+ applyCallUpdate(call) {
1094
+ this._onCall(call);
1095
+ }
1096
+ answer() {
1097
+ var _a2, _b;
1098
+ if (this.state.status === "ringing") (_b = (_a2 = this._call) == null ? void 0 : _a2.answer) == null ? void 0 : _b.call(_a2);
1099
+ }
1100
+ hangup() {
1101
+ var _a2, _b;
1102
+ (_b = (_a2 = this._call) == null ? void 0 : _a2.hangup) == null ? void 0 : _b.call(_a2);
1103
+ }
1104
+ mute() {
1105
+ var _a2, _b;
1106
+ if (!this._call) return;
1107
+ const muted = !this.state.muted;
1108
+ try {
1109
+ (_b = (_a2 = this._call).mute) == null ? void 0 : _b.call(_a2, muted);
1110
+ } catch {
1111
+ return;
1112
+ }
1113
+ this._set({ muted });
1114
+ }
1115
+ /** Hold or resume. Needs an adapter whose call object has `hold(on)`; returns false when it cannot. */
1116
+ hold() {
1117
+ if (!this._call || typeof this._call.hold !== "function" || this.state.status !== "in-call") return false;
1118
+ const held = !this.state.held;
1119
+ try {
1120
+ this._call.hold(held);
1121
+ } catch {
1122
+ return false;
1123
+ }
1124
+ this._set({ held });
1125
+ return true;
1126
+ }
1127
+ /** Send a keypad tone on the live call (0–9, *, #, A–D). */
1128
+ dtmf(digit) {
1129
+ var _a2;
1130
+ const d = String(digit != null ? digit : "");
1131
+ if (!DTMF.test(d) || this.state.status !== "in-call" || typeof ((_a2 = this._call) == null ? void 0 : _a2.dtmf) !== "function") return false;
1132
+ try {
1133
+ this._call.dtmf(d.toUpperCase());
1134
+ return true;
1135
+ } catch {
1136
+ return false;
1137
+ }
1138
+ }
1139
+ get canHold() {
1140
+ var _a2;
1141
+ return typeof ((_a2 = this._call) == null ? void 0 : _a2.hold) === "function";
1142
+ }
1143
+ get canDtmf() {
1144
+ var _a2;
1145
+ return typeof ((_a2 = this._call) == null ? void 0 : _a2.dtmf) === "function";
1146
+ }
1147
+ /**
1148
+ * Ring a customer from the company line and bridge them to this softphone when they pick up.
1149
+ * @param {string} to digits or E.164 ("18765550100" and "+18765550100" are the same)
1150
+ * @param {'phone'|'whatsapp'} [channel]
1151
+ */
1152
+ async dial(to, channel = "phone") {
1153
+ var _a2;
1154
+ const num = String(to != null ? to : "");
1155
+ const e164 = /^\d+$/.test(num) ? `+${num}` : num;
1156
+ if (this.state.dialing) return false;
1157
+ if (!isE164(e164)) {
1158
+ this._set({ error: this.S.badNumber, errorCode: "bad-number" });
1159
+ return false;
1160
+ }
1161
+ if (this.state.status !== "ready") {
1162
+ this._set({ error: this.S.goOnlineFirst, errorCode: "offline" });
1163
+ return false;
1164
+ }
1165
+ if (channel === "whatsapp" && !this.whatsapp) {
1166
+ this._set({ error: this.S.whatsappNotConfigured, errorCode: "whatsapp-not-configured" });
1167
+ return false;
1168
+ }
1169
+ this._set({ dialing: true, error: null, errorCode: null });
1170
+ try {
1171
+ await this.client.calls.create(channel === "whatsapp" ? { channel: "whatsapp", to: e164, agentSipUsername: this.state.sipUsername, ...this.whatsapp } : { channel: "phone", to: e164, agentSipUsername: this.state.sipUsername });
1172
+ this._set({ placing: { number: e164, channel } });
1173
+ this._placingTimer = this.timers.setTimeout(() => {
1174
+ this._placingTimer = null;
1175
+ if (this.state.placing) this._set({ placing: null });
1176
+ }, PLACING_MS);
1177
+ return true;
1178
+ } catch (error) {
1179
+ this._set({ error: (error == null ? void 0 : error.message) || this.S.couldNotCall, errorCode: (_a2 = error == null ? void 0 : error.code) != null ? _a2 : null });
1180
+ return false;
1181
+ } finally {
1182
+ this._set({ dialing: false });
1183
+ }
1184
+ }
1185
+ };
1186
+
1187
+ // src/elements/soundOptions.js
1188
+ var KEY_LABEL = { dtmf: "keyToneDtmf", click: "keyToneClick", off: "keyToneOff" };
1189
+ var RING_LABEL = { classic: "ringClassic", soft: "ringSoft", off: "ringOff" };
1190
+ function renderSoundOptions(sound, S, { open = false, voices = [], idPrefix = "snd" } = {}) {
1191
+ const s = sound.settings;
1192
+ const id = (n) => `${idPrefix}-${n}`;
1193
+ return html`<div class="snd">
1194
+ <button type="button" class="snd-toggle" data-action="snd-toggle" aria-expanded="${String(Boolean(open))}" aria-controls="${id("panel")}">${s.enabled ? "\u{1F50A}" : "\u{1F507}"} ${S.sound}</button>
1195
+ ${open ? html`<div class="snd-panel" id="${id("panel")}" role="group" aria-label="${S.sound}">
1196
+ <label class="snd-check"><input type="checkbox" data-key="snd-enabled" ${s.enabled ? "checked" : ""} />${S.soundOn}</label>
1197
+ <label for="${id("vol")}">${S.volume}</label>
1198
+ <input id="${id("vol")}" type="range" min="0" max="1" step="0.05" data-key="snd-volume" value="${s.volume}" aria-valuetext="${Math.round(s.volume * 100)}%" />
1199
+ <label for="${id("key")}">${S.keyTone}</label>
1200
+ <select id="${id("key")}" data-key="snd-keyTone">${KEY_TONES.map((k) => html`<option value="${k}" ${s.keyTone === k ? "selected" : ""}>${S[KEY_LABEL[k]]}</option>`)}</select>
1201
+ <label for="${id("ring")}">${S.ringtone}</label>
1202
+ <select id="${id("ring")}" data-key="snd-ringtone">${Object.keys(RINGTONES).map((k) => html`<option value="${k}" ${s.ringtone === k ? "selected" : ""}>${S[RING_LABEL[k]]}</option>`)}</select>
1203
+ <label class="snd-check"><input type="checkbox" data-key="snd-speak" ${s.speak ? "checked" : ""} />${S.speakDigits}</label>
1204
+ ${s.speak ? html`<label for="${id("voice")}">${S.voice}</label>
1205
+ <select id="${id("voice")}" data-key="snd-voice"><option value="">${S.voiceDefault}</option>${voices.map((v) => html`<option value="${v.id}" ${s.voice === v.id ? "selected" : ""}>${v.label}</option>`)}</select>
1206
+ <label for="${id("rate")}">${S.voiceRate}</label>
1207
+ <input id="${id("rate")}" type="range" min="0.5" max="2" step="0.1" data-key="snd-rate" value="${s.rate}" aria-valuetext="${s.rate}×" />` : ""}
1208
+ <div class="btns"><button type="button" data-action="snd-test">${S.soundTest}</button></div>
1209
+ </div>` : ""}
1210
+ </div>`;
1211
+ }
1212
+ function applySoundEdit(sound, target) {
1213
+ var _a2;
1214
+ const key = (_a2 = target == null ? void 0 : target.dataset) == null ? void 0 : _a2.key;
1215
+ if (!key || !key.startsWith("snd-")) return false;
1216
+ const name = key.slice(4);
1217
+ const value = target.type === "checkbox" ? !!target.checked : name === "volume" || name === "rate" ? Number(target.value) : target.value;
1218
+ sound.update({ [name]: value });
1219
+ return true;
1220
+ }
1221
+
1222
+ // src/core/api.js
1223
+ var json = (method, body) => ({ method, body: JSON.stringify(body != null ? body : {}) });
1224
+ var raw2 = (client) => {
1225
+ var _a2;
1226
+ return (_a2 = client._request) == null ? void 0 : _a2.bind(client);
1227
+ };
1228
+ async function listLines(client) {
1229
+ var _a2, _b, _c, _d, _e;
1230
+ if (typeof ((_a2 = client.phoneNumbers) == null ? void 0 : _a2.list) === "function") return (_c = (_b = await client.phoneNumbers.list()) == null ? void 0 : _b.numbers) != null ? _c : [];
1231
+ return (_e = (_d = await raw2(client)("/telephony/numbers")) == null ? void 0 : _d.numbers) != null ? _e : [];
1232
+ }
1233
+ async function getOutboundMode(client) {
1234
+ var _a2, _b, _c, _d, _e, _f;
1235
+ if (typeof ((_b = (_a2 = client.calls) == null ? void 0 : _a2.outboundSettings) == null ? void 0 : _b.get) === "function") return (_d = (_c = await client.calls.outboundSettings.get()) == null ? void 0 : _c.mode) != null ? _d : "direct";
1236
+ return (_f = (_e = await raw2(client)("/telephony/outbound-call-settings")) == null ? void 0 : _e.mode) != null ? _f : "direct";
1237
+ }
1238
+ async function setOutboundMode(client, mode) {
1239
+ var _a2, _b;
1240
+ if (typeof ((_b = (_a2 = client.calls) == null ? void 0 : _a2.outboundSettings) == null ? void 0 : _b.update) === "function") return client.calls.outboundSettings.update({ mode });
1241
+ return raw2(client)("/telephony/outbound-call-settings", json("PUT", { mode }));
1242
+ }
1243
+ async function listCalls(client, limit = 10) {
1244
+ var _a2, _b, _c, _d, _e;
1245
+ if (typeof ((_a2 = client.calls) == null ? void 0 : _a2.list) === "function") return (_c = (_b = await client.calls.list({ limit })) == null ? void 0 : _b.calls) != null ? _c : [];
1246
+ return (_e = (_d = await raw2(client)(`/calls?limit=${limit}`)) == null ? void 0 : _d.calls) != null ? _e : [];
1247
+ }
1248
+
1249
+ // src/core/history.js
1250
+ var SAME_CALL_MS = 12e4;
1251
+ var digits = (v) => String(v != null ? v : "").replace(/\D/g, "");
1252
+ function fromRecord(r) {
1253
+ const inbound = r.direction === "inbound";
1254
+ const number = (inbound ? r.from : r.to) || null;
1255
+ const at = r.startedAt ? Date.parse(r.startedAt) : 0;
1256
+ const dur = Number(r.durationSeconds) > 0 ? Number(r.durationSeconds) * 1e3 : 0;
1257
+ return { who: number != null ? number : "Unknown", number, direction: inbound ? "in" : "out", outcome: dur ? "answered" : "missed", durationMs: dur, at, id: r.id };
1258
+ }
1259
+ function mergeCalls(local = [], server = [], max = 10) {
1260
+ const out = [...local];
1261
+ for (const r of server.map(fromRecord)) {
1262
+ const dup = out.some((e) => digits(e.number) === digits(r.number) && Math.abs((e.at || 0) - r.at) <= SAME_CALL_MS);
1263
+ if (!dup) out.push(r);
1264
+ }
1265
+ return out.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, max);
1266
+ }
1267
+
1268
+ // src/core/dialerPrefs.js
1269
+ var MAX_RING_SECONDS = 60;
1270
+ var KEY3 = "traitos.dialer.prefs";
1271
+ var DEFAULT_PREFS = Object.freeze({ ringTimeoutSeconds: 20, ringChannels: { whatsapp: true, phone: true }, callerId: null });
1272
+ function normalizePrefs(p = {}) {
1273
+ var _a2, _b;
1274
+ const n = Math.round(Number(p == null ? void 0 : p.ringTimeoutSeconds));
1275
+ return {
1276
+ ringTimeoutSeconds: (p == null ? void 0 : p.ringTimeoutSeconds) === "" || (p == null ? void 0 : p.ringTimeoutSeconds) == null || !Number.isFinite(n) ? DEFAULT_PREFS.ringTimeoutSeconds : Math.min(MAX_RING_SECONDS, Math.max(0, n)),
1277
+ ringChannels: { whatsapp: ((_a2 = p == null ? void 0 : p.ringChannels) == null ? void 0 : _a2.whatsapp) !== false, phone: ((_b = p == null ? void 0 : p.ringChannels) == null ? void 0 : _b.phone) !== false },
1278
+ callerId: typeof (p == null ? void 0 : p.callerId) === "string" && p.callerId ? p.callerId : null
1279
+ };
1280
+ }
1281
+ function loadPrefs(storage) {
1282
+ try {
1283
+ return normalizePrefs(JSON.parse((storage == null ? void 0 : storage.getItem(KEY3)) || "{}"));
1284
+ } catch {
1285
+ return normalizePrefs();
1286
+ }
1287
+ }
1288
+ function savePrefs(storage, prefs) {
1289
+ try {
1290
+ storage == null ? void 0 : storage.setItem(KEY3, JSON.stringify(normalizePrefs(prefs)));
1291
+ } catch {
1292
+ }
1293
+ }
1294
+ function registrationFor(prefs, lines) {
1295
+ const p = normalizePrefs(prefs);
1296
+ if (!(lines == null ? void 0 : lines.length)) return { ringTimeoutSeconds: p.ringTimeoutSeconds };
1297
+ const numbers = lines.filter((l) => {
1298
+ const ch = Array.isArray(l.channels) ? l.channels : [];
1299
+ return ch.includes("whatsapp_calling") && p.ringChannels.whatsapp || ch.includes("voice") && p.ringChannels.phone;
1300
+ }).map((l) => l.number).filter(Boolean);
1301
+ return { ringTimeoutSeconds: p.ringTimeoutSeconds, numbers };
1302
+ }
1303
+ function storedPrefs(storage) {
1304
+ try {
1305
+ const v = storage == null ? void 0 : storage.getItem(KEY3);
1306
+ return v ? normalizePrefs(JSON.parse(v)) : null;
1307
+ } catch {
1308
+ return null;
1309
+ }
1310
+ }
1311
+ var PREFS_EVENT = "traitos-dialer-prefs";
1312
+
1313
+ // src/elements/phoneBase.js
1314
+ var localStore = () => {
1315
+ try {
1316
+ return typeof localStorage !== "undefined" ? localStorage : null;
1317
+ } catch {
1318
+ return null;
1319
+ }
1320
+ };
1321
+ var PhoneBase = class extends TraitElement {
1322
+ static get observedAttributes() {
1323
+ return ["allow-dial", "live-events", "auto-start", "theme", "position", "inline"];
1324
+ }
1325
+ constructor() {
1326
+ super();
1327
+ this.dp = createDialpad({ clearOnCall: false, onCall: (c) => this._placeCall(c.number, c.channel) });
1328
+ this.dp.subscribe(() => this.requestRender());
1329
+ this.keypadOpen = false;
1330
+ }
1331
+ set client(v) {
1332
+ this._client = v;
1333
+ this._lines = null;
1334
+ this._init();
1335
+ }
1336
+ get client() {
1337
+ return this._client;
1338
+ }
1339
+ set adapter(v) {
1340
+ this._adapter = v;
1341
+ this._init();
1342
+ }
1343
+ get adapter() {
1344
+ return this._adapter;
1345
+ }
1346
+ set numbers(v) {
1347
+ this._numbers = v;
1348
+ if (this.controller) this.controller.numbers = v;
1349
+ }
1350
+ set whatsapp(v) {
1351
+ this._whatsapp = v;
1352
+ if (this.controller) this.controller.whatsapp = v;
1353
+ this.requestRender();
1354
+ }
1355
+ get whatsapp() {
1356
+ return this._whatsapp;
1357
+ }
1358
+ set strings(v) {
1359
+ this._strings = v;
1360
+ this.requestRender();
1361
+ }
1362
+ get S() {
1363
+ return stringsFor(this._strings);
1364
+ }
1365
+ get caps() {
1366
+ return this.dp.caps;
1367
+ }
1368
+ set caps(v) {
1369
+ this._caps = v;
1370
+ this.dp.setCaps(v);
1371
+ }
1372
+ set storage(v) {
1373
+ this._storage = v;
1374
+ }
1375
+ /** The sound engine (key tones, ringtone, spoken digits). Replace it to supply your own. */
1376
+ get sound() {
1377
+ if (!this._sound) {
1378
+ this._sound = createSound({ storage: this._store });
1379
+ this._unsound = this._sound.subscribe(() => this.requestRender());
1380
+ }
1381
+ return this._sound;
1382
+ }
1383
+ set sound(v) {
1384
+ this._sound = v;
1385
+ this.requestRender();
1386
+ }
1387
+ get _store() {
1388
+ var _a2;
1389
+ return (_a2 = this._storage) != null ? _a2 : localStore();
1390
+ }
1391
+ mounted() {
1392
+ var _a2, _b, _c;
1393
+ this._onPrefs = () => this._applyPrefs();
1394
+ this._onVoices = () => this.requestRender();
1395
+ (_b = (_a2 = globalThis.speechSynthesis) == null ? void 0 : _a2.addEventListener) == null ? void 0 : _b.call(_a2, "voiceschanged", this._onVoices);
1396
+ (_c = globalThis.addEventListener) == null ? void 0 : _c.call(globalThis, PREFS_EVENT, this._onPrefs);
1397
+ this._init();
1398
+ }
1399
+ unmounted() {
1400
+ var _a2, _b, _c, _d, _e, _f, _g, _h;
1401
+ (_a2 = globalThis.removeEventListener) == null ? void 0 : _a2.call(globalThis, PREFS_EVENT, this._onPrefs);
1402
+ (_c = (_b = globalThis.speechSynthesis) == null ? void 0 : _b.removeEventListener) == null ? void 0 : _c.call(_b, "voiceschanged", this._onVoices);
1403
+ (_d = this._sound) == null ? void 0 : _d.stopRing();
1404
+ (_e = this._unsound) == null ? void 0 : _e.call(this);
1405
+ this._unsound = null;
1406
+ clearInterval(this._tick);
1407
+ (_f = this._unsub) == null ? void 0 : _f.call(this);
1408
+ this._unsub = null;
1409
+ (_g = this._unlog) == null ? void 0 : _g.call(this);
1410
+ this._unlog = null;
1411
+ (_h = this.controller) == null ? void 0 : _h.stop();
1412
+ this.controller = null;
1413
+ this._capsLoaded = false;
1414
+ }
1415
+ attributeChangedCallback() {
1416
+ this.requestRender();
1417
+ }
1418
+ _init() {
1419
+ if (!this._connected) return;
1420
+ this._initCaps();
1421
+ if (this.controller || !this._client || !this._adapter) {
1422
+ this.requestRender();
1423
+ return;
1424
+ }
1425
+ this.log = new CallLog({ storage: this._store });
1426
+ this._unlog = this.log.subscribe(() => this.requestRender());
1427
+ this.controller = new SoftphoneController({ client: this._client, adapter: this._adapter, numbers: this._numbers, whatsapp: this._whatsapp, liveEvents: this.hasAttribute("live-events"), log: this.log, strings: this._strings });
1428
+ this._applyPrefs();
1429
+ this._unsub = this.controller.subscribe((s) => {
1430
+ var _a2;
1431
+ this.emit("traitos-state", s);
1432
+ if (s.status === "error") this.emit("traitos-error", { message: s.error, code: s.errorCode });
1433
+ clearInterval(this._tick);
1434
+ if (s.status === "in-call") this._tick = setInterval(() => this.requestRender(), 1e3);
1435
+ if (s.status !== "in-call") this.keypadOpen = false;
1436
+ this._stateSound(s);
1437
+ (_a2 = this.onState) == null ? void 0 : _a2.call(this, s);
1438
+ this.requestRender();
1439
+ });
1440
+ if (this.hasAttribute("auto-start")) this.controller.start();
1441
+ this.requestRender();
1442
+ }
1443
+ /** Ring while a call is ringing; a short end tone when a call ends. */
1444
+ /** Recent calls: this browser's log merged with the server's list when the token may read it. */
1445
+ recentCalls() {
1446
+ var _a2, _b, _c;
1447
+ return mergeCalls((_b = (_a2 = this.log) == null ? void 0 : _a2.list()) != null ? _b : [], (_c = this._serverCalls) != null ? _c : []);
1448
+ }
1449
+ async _loadHistory() {
1450
+ if (!this._client || this._historyBusy) return;
1451
+ this._historyBusy = true;
1452
+ try {
1453
+ this._serverCalls = await listCalls(this._client, 10);
1454
+ this.requestRender();
1455
+ } catch {
1456
+ }
1457
+ this._historyBusy = false;
1458
+ }
1459
+ _stateSound(s) {
1460
+ const prev = this._prevStatus;
1461
+ this._prevStatus = s.status;
1462
+ if (s.status === "ringing") this.sound.startRing();
1463
+ else this.sound.stopRing();
1464
+ if (s.status === "ready" && (prev === "in-call" || prev === "ringing")) {
1465
+ this.sound.end();
1466
+ setTimeout(() => this._loadHistory(), 1500);
1467
+ }
1468
+ if (s.status === "ready" && prev !== "ready" && !this._serverCalls) this._loadHistory();
1469
+ }
1470
+ /** Without `caps`, learn which channels the workspace has from its phone lines. If that fails, phone calling stays on. */
1471
+ async _initCaps() {
1472
+ if (this._caps || this._capsLoaded || !this._client) return;
1473
+ this._capsLoaded = true;
1474
+ try {
1475
+ this._lines = await listLines(this._client);
1476
+ if (!this._caps) this.dp.setCaps(capsFromLines(this._lines));
1477
+ this._applyPrefs();
1478
+ } catch {
1479
+ if (!this._caps) this.dp.setCaps({ phoneCallingEnabled: true });
1480
+ }
1481
+ }
1482
+ /** Ring timeout and ringing channels chosen in <traitos-settings> (kept in this browser). */
1483
+ _applyPrefs() {
1484
+ const p = storedPrefs(this._store);
1485
+ if (!p || !this.controller) return;
1486
+ const reg = registrationFor(p, this._lines);
1487
+ this.controller.ringTimeoutSeconds = reg.ringTimeoutSeconds || void 0;
1488
+ if (!this._numbers && reg.numbers) this.controller.numbers = reg.numbers;
1489
+ }
1490
+ _placeCall(number, channel) {
1491
+ const go = this.emit("traitos-call", { number, channel }, { cancelable: true });
1492
+ if (go && this.controller) this.controller.dial(number, channel).then((ok) => {
1493
+ if (ok) this.dp.clear();
1494
+ this.requestRender();
1495
+ });
1496
+ else if (!this.controller || !go) this.dp.clear();
1497
+ }
1498
+ /** Place a call as if the number had been keyed in. Resolves false when it was refused. */
1499
+ dial(number, channel = "phone") {
1500
+ if (!this.dp.channels.includes(channel)) return false;
1501
+ this.dp.setNumber(String(number));
1502
+ return this.dp.call(channel);
1503
+ }
1504
+ /** Everything both elements do on a click; returns true when handled. */
1505
+ phoneClick(action, node) {
1506
+ const c = this.controller;
1507
+ if (action === "kp-key" || action === "kp-dtmf") this.sound.key(node.dataset.d);
1508
+ else if (action === "snd-test") this.sound.test();
1509
+ else if (action !== "snd-toggle" && action !== "start" && action !== "stop") this.sound.click();
1510
+ if (action === "snd-toggle") {
1511
+ this._sndOpen = !this._sndOpen;
1512
+ this.requestRender();
1513
+ return true;
1514
+ }
1515
+ if (action === "snd-test") return true;
1516
+ if (keypadClick(this.dp, action, node, { onDtmf: (d) => c == null ? void 0 : c.dtmf(d) })) return true;
1517
+ if (!c) return false;
1518
+ if (action === "start") c.start();
1519
+ else if (action === "stop") c.stop();
1520
+ else if (action === "answer") c.answer();
1521
+ else if (action === "hangup") c.hangup();
1522
+ else if (action === "mute") c.mute();
1523
+ else if (action === "hold") c.hold();
1524
+ else if (action === "toggle-keypad") {
1525
+ this.keypadOpen = !this.keypadOpen;
1526
+ this.requestRender();
1527
+ } else if (action === "redial") {
1528
+ const e = this.recentCalls()[Number(node.dataset.i)];
1529
+ if (e == null ? void 0 : e.number) this.dial(e.number.replace(/\D/g, ""), this.dp.channels.includes("phone") ? "phone" : this.dp.channels[0]);
1530
+ } else return false;
1531
+ return true;
1532
+ }
1533
+ onClick(action, node) {
1534
+ this.phoneClick(action, node);
1535
+ }
1536
+ onInput(target) {
1537
+ var _a2, _b;
1538
+ if ((_b = (_a2 = target.dataset) == null ? void 0 : _a2.key) == null ? void 0 : _b.startsWith("snd-")) {
1539
+ if (target.type === "range") applySoundEdit(this.sound, target);
1540
+ return;
1541
+ }
1542
+ keypadInput(this.dp, target);
1543
+ }
1544
+ onChange(target) {
1545
+ applySoundEdit(this.sound, target);
1546
+ }
1547
+ onHold(what) {
1548
+ if (keypadHold(this.dp, what)) this.sound.key("+");
1549
+ }
1550
+ onKey(e) {
1551
+ var _a2, _b;
1552
+ if (((_b = (_a2 = e.target) == null ? void 0 : _a2.dataset) == null ? void 0 : _b.key) !== "dialpad-number") return;
1553
+ if (e.key === "Enter") {
1554
+ e.preventDefault();
1555
+ this.dp.submit();
1556
+ } else if (e.key.length === 1 && /[0-9*#]/.test(e.key) && !e.ctrlKey && !e.metaKey) this.sound.key(e.key);
1557
+ }
1558
+ };
1559
+
1560
+ // src/elements/softphone.js
1561
+ var css = keypadCss + `
1562
+ .snd { margin-top: 10px; } .snd-panel { display: grid; gap: 4px; margin-top: 6px; } .snd-check { display: flex; align-items: center; gap: 6px; margin: 4px 0; } .snd-toggle { width: 100%; text-align: left; } .snd input[type=range] { padding: 0; }
1563
+ .phone { max-width: 340px; } .head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
1564
+ .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--_line); display: inline-block; margin-right: 6px; }
1565
+ .dot.ready { background: var(--_ok); } .dot.ringing { background: var(--_warn); animation: pulse 1s infinite; } .dot.in-call { background: var(--_accent); } .dot.error { background: var(--_bad); }
1566
+ .recent { list-style: none; margin: 6px 0 0; padding: 0; font-size: 12.5px; color: var(--_muted); }
1567
+ @keyframes pulse { 50% { opacity: .35; } }
1568
+ `;
1569
+ var STATUS_KEY = { off: "off", connecting: "connecting", ready: "ready", ringing: "ringing", "in-call": "inCall", error: "error" };
1570
+ function renderRecentCalls(calls2, S, { canRedial = true } = {}) {
1571
+ if (!(calls2 == null ? void 0 : calls2.length)) return html`<p class="hint">${S.noRecent}</p>`;
1572
+ return html`<ul class="recent-list">${calls2.map((c, i) => html`<li><button type="button" data-action="redial" data-i="${i}" ${canRedial && c.number ? "" : "disabled"} aria-label="${t(S, "redial", { who: c.who })}">
1573
+ <span class="${c.outcome === "missed" && c.direction === "in" ? "miss" : ""}">${c.who}</span> <span class="hint">${c.direction === "in" ? c.outcome === "missed" ? S.missed : S.incoming : S.outgoing}${c.durationMs ? ` \xB7 ${formatDuration(c.durationMs)}` : ""}</span></button></li>`)}</ul>`;
1574
+ }
1575
+ function renderCallControls(s, { S, now, canHold, canDtmf, keypadOpen }) {
1576
+ var _a2;
1577
+ return html`<div class="who">${(_a2 = s.caller) != null ? _a2 : S.onACall}</div><div class="timer" aria-hidden="true">${s.startedAt ? formatDuration(now - s.startedAt) : ""}${s.held ? html` · ${S.onHold}` : ""}</div>
1578
+ <div class="btns"><button type="button" data-action="mute" aria-pressed="${String(Boolean(s.muted))}">${s.muted ? S.unmute : S.mute}</button>${canHold ? html`<button type="button" data-action="hold" aria-pressed="${String(Boolean(s.held))}">${s.held ? S.resume : S.hold}</button>` : ""}${canDtmf ? html`<button type="button" data-action="toggle-keypad" aria-pressed="${String(Boolean(keypadOpen))}">${keypadOpen ? S.hideKeypad : S.showKeypad}</button>` : ""}<button type="button" class="danger" data-action="hangup">${S.hangUp}</button></div>`;
1579
+ }
1580
+ function renderLastCall(s, S) {
1581
+ if (!s.lastCall) return "";
1582
+ const l = s.lastCall;
1583
+ return html`<p class="status" role="status">${l.outcome === "missed" ? html`${S.missedCall}: ${l.who}` : t(S, "callEndedFor", { time: formatDuration(l.durationMs) })}</p>`;
1584
+ }
1585
+ function renderSoftphone(s, { allowDial = false, now = Date.now(), dial = "", title, S = stringsFor(), dp, canHold = false, canDtmf = false, keypadOpen = false, calls: calls2 = [], sound, soundOpen = false, voices = [] } = {}) {
1586
+ var _a2, _b, _c;
1587
+ const heading = title != null ? title : S.softphone;
1588
+ const label = (_b = (_a2 = S[STATUS_KEY[s.status]]) != null ? _a2 : softphoneLabel[s.status]) != null ? _b : s.status;
1589
+ return html`<div class="card phone" role="region" aria-label="${heading}">
1590
+ <div class="head"><h2>${heading}</h2><span class="pill"><i class="dot ${s.status}"></i>${label}</span></div>
1591
+ <div class="sr" role="status" aria-live="polite">${label}${s.caller ? `: ${s.caller}` : ""}</div>
1592
+ ${s.error ? html`<p class="err" role="alert">${s.error}</p>` : ""}
1593
+ ${s.warning ? html`<p class="status bad" role="status">${s.warning}</p>` : ""}
1594
+ ${s.status === "off" || s.status === "error" ? html`<div class="btns"><button class="primary" data-action="start">${s.status === "error" ? S.tryAgain : S.goOnline}</button></div>
1595
+ <p class="hint">${S.goOnlineHint}</p>` : ""}
1596
+ ${s.status === "connecting" ? html`<p class="hint">${S.connecting}</p>` : ""}
1597
+ ${s.status === "ready" ? html`
1598
+ ${renderLastCall(s, S)}
1599
+ <p class="hint">${s.sipUsername ? html`${S.waiting} · <b>${s.sipUsername}</b>` : S.waiting}</p>
1600
+ ${s.placing ? html`<p class="status" role="status">${t(S, "placing", { number: s.placing.number })}</p>` : ""}
1601
+ ${allowDial && dp ? renderKeypad(dp, { S, busy: s.dialing }) : ""}
1602
+ ${allowDial && !dp ? html`<form data-submit="dial"><label for="dial">${S.numberLabel}</label>
1603
+ <div class="row"><input id="dial" data-key="dial" type="tel" inputmode="tel" autocomplete="off" placeholder="+18765550100" value="${dial}" /><button class="primary fixed" type="submit" ${s.dialing ? "disabled" : ""}>${s.dialing ? "\u2026" : S.phone}</button></div></form>` : ""}
1604
+ ${calls2.length ? html`<h3>${S.recent}</h3>${renderRecentCalls(calls2, S)}` : ""}
1605
+ ${sound ? renderSoundOptions(sound, S, { open: soundOpen, voices, idPrefix: "sp-snd" }) : ""}
1606
+ <div class="btns"><button data-action="stop">${S.goOffline}</button></div>` : ""}
1607
+ ${s.status === "ringing" ? html`<div class="who">${s.caller}</div><div class="hint">${S.isCalling}</div>
1608
+ <div class="btns"><button class="ok" data-action="answer">${S.answer}</button><button class="danger" data-action="hangup">${S.decline}</button></div>` : ""}
1609
+ ${s.status === "in-call" ? html`${renderCallControls(s, { S, now, canHold, canDtmf, keypadOpen })}${keypadOpen && dp ? renderKeypad(dp, { S, mode: "dtmf" }) : ""}` : ""}
1610
+ ${((_c = s.recent) == null ? void 0 : _c.length) ? html`<h3>${S.recent}</h3><ul class="recent">${s.recent.map((e) => html`<li>${e.type}</li>`)}</ul>` : ""}
1611
+ </div>`.toString();
1612
+ }
1613
+ var TraitOSSoftphone = class extends PhoneBase {
1614
+ get css() {
1615
+ return css;
1616
+ }
1617
+ render() {
1618
+ var _a2, _b;
1619
+ const S = this.S;
1620
+ const c = this.controller;
1621
+ const s = (_a2 = c == null ? void 0 : c.snapshot()) != null ? _a2 : { status: "off", error: this._client && this._adapter ? null : S.needSetup, recent: [] };
1622
+ return renderSoftphone(s, { allowDial: this.hasAttribute("allow-dial"), dial: (_b = this._dial) != null ? _b : "", S, dp: this.dp, now: Date.now(), canHold: !!(c == null ? void 0 : c.canHold), canDtmf: !!(c == null ? void 0 : c.canDtmf), keypadOpen: this.keypadOpen, calls: this.recentCalls(), sound: this.sound, soundOpen: this._sndOpen, voices: this.sound.voices() });
1623
+ }
1624
+ onClick(action, node) {
1625
+ var _a2, _b, _c;
1626
+ if (this.phoneClick(action, node)) return;
1627
+ const c = this.controller;
1628
+ if (c && action === "dial") {
1629
+ const v = cleanDialInput((_c = (_b = (_a2 = node.querySelector) == null ? void 0 : _a2.call(node, '[data-key="dial"]')) == null ? void 0 : _b.value) != null ? _c : this._dial);
1630
+ this._dial = v;
1631
+ c.dial(v).then((ok) => {
1632
+ if (ok) this._dial = "";
1633
+ this.requestRender();
1634
+ });
1635
+ }
1636
+ }
1637
+ onInput(target) {
1638
+ if (target.dataset.key === "dial") this._dial = cleanDialInput(target.value);
1639
+ else super.onInput(target);
1640
+ }
1641
+ };
1642
+ define("traitos-softphone", TraitOSSoftphone);
1643
+
1644
+ // src/core/widgetState.js
1645
+ var CORNERS = Object.freeze(["bottom-right", "bottom-left", "top-right", "top-left"]);
1646
+ function placementOf({ position, inline } = {}) {
1647
+ if (inline) return { mode: "inline", corner: null };
1648
+ if (position && CORNERS.includes(position)) return { mode: "floating", corner: position };
1649
+ return { mode: "header", corner: null };
1650
+ }
1651
+ function panelSide(rect, viewport, panel = {}) {
1652
+ var _a2, _b;
1653
+ const w = (_a2 = panel.width) != null ? _a2 : 300, h = (_b = panel.height) != null ? _b : 460;
1654
+ const roomRight = viewport.width - rect.left;
1655
+ const roomLeft = rect.right;
1656
+ const horizontal = roomRight >= w || roomRight >= roomLeft ? "left" : "right";
1657
+ const below = viewport.height - rect.bottom, above = rect.top;
1658
+ const vertical = below >= h || below >= above ? "down" : "up";
1659
+ return { h: horizontal, v: vertical };
1660
+ }
1661
+ function createOpenState({ inline = false, onChange } = {}) {
1662
+ let open = inline;
1663
+ const set = (v) => {
1664
+ const next = inline ? true : Boolean(v);
1665
+ if (next === open) return false;
1666
+ open = next;
1667
+ onChange == null ? void 0 : onChange(open);
1668
+ return true;
1669
+ };
1670
+ return {
1671
+ get open() {
1672
+ return open;
1673
+ },
1674
+ openIt: () => set(true),
1675
+ close: () => set(false),
1676
+ toggle: () => set(!open),
1677
+ setInline(v) {
1678
+ inline = Boolean(v);
1679
+ if (inline && !open) {
1680
+ open = true;
1681
+ onChange == null ? void 0 : onChange(true);
1682
+ }
1683
+ },
1684
+ /** Escape closes (and the caller returns focus to the icon). Returns true when it did. */
1685
+ onKey(key) {
1686
+ return key === "Escape" && open && !inline ? set(false) : false;
1687
+ },
1688
+ /** A pointer press: closes unless it landed inside the widget (`path` is `event.composedPath()`). */
1689
+ onOutside(path, host) {
1690
+ return open && !inline && !path.includes(host) ? set(false) : false;
1691
+ }
1692
+ };
1693
+ }
1694
+ function iconLabel(S, { status, missed, open }) {
1695
+ const base = open ? S.closePhone : S.openPhone;
1696
+ const extra = status === "ringing" ? S.ringing : status === "in-call" ? S.inCall : missed > 0 ? S.missedBadge.replace("{n}", String(missed)) : "";
1697
+ return extra ? `${base} \u2014 ${extra}` : base;
1698
+ }
1699
+
1700
+ // src/elements/dialerWidget.js
1701
+ var ICON = '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true" focusable="false"><path fill="currentColor" d="M6.6 10.8a15 15 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25 11.4 11.4 0 0 0 3.6.57 1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A17 17 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.25.2 2.45.57 3.6a1 1 0 0 1-.25 1z"/></svg>';
1702
+ var css2 = keypadCss + `
1703
+ :host { display: inline-block; position: relative; }
1704
+ :host([inline]) { display: block; }
1705
+ :host([position]) { position: fixed; z-index: var(--traitos-z, 2147483000); }
1706
+ :host([position="bottom-right"]) { right: max(16px, env(safe-area-inset-right)); bottom: max(16px, env(safe-area-inset-bottom)); }
1707
+ :host([position="bottom-left"]) { left: max(16px, env(safe-area-inset-left)); bottom: max(16px, env(safe-area-inset-bottom)); }
1708
+ :host([position="top-right"]) { right: max(16px, env(safe-area-inset-right)); top: max(16px, env(safe-area-inset-top)); }
1709
+ :host([position="top-left"]) { left: max(16px, env(safe-area-inset-left)); top: max(16px, env(safe-area-inset-top)); }
1710
+ .fab { position: relative; width: 44px; height: 44px; min-width: 44px; padding: 0; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; background: var(--_bg); color: inherit; border: 1px solid var(--_line); }
1711
+ :host([position]) .fab { width: 56px; height: 56px; background: var(--_accent); border-color: var(--_accent); color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.25); }
1712
+ .fab.ringing, .fab.in-call { background: var(--_accent); border-color: var(--_accent); color: #fff; }
1713
+ .fab.ringing { animation: ring 1s infinite; } .fab.in-call { box-shadow: 0 0 0 3px color-mix(in srgb, var(--_ok) 55%, transparent); }
1714
+ .badge { position: absolute; top: -4px; right: -4px; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px; background: var(--_bad); color: #fff; font-size: 11px; line-height: 18px; text-align: center; font-weight: 700; }
1715
+ .panel, .mini { position: absolute; z-index: 1; width: min(320px, calc(100vw - 16px)); max-height: calc(100vh - 80px); overflow: auto; background: var(--_bg); border: 1px solid var(--_line); border-radius: var(--_r); padding: 14px; box-shadow: 0 10px 30px rgba(0,0,0,.22); }
1716
+ .panel[data-v="down"], .mini[data-v="down"] { top: calc(100% + 8px); } .panel[data-v="up"], .mini[data-v="up"] { bottom: calc(100% + 8px); }
1717
+ .panel[data-h="left"], .mini[data-h="left"] { left: 0; } .panel[data-h="right"], .mini[data-h="right"] { right: 0; }
1718
+ .panel.inline { position: static; width: 100%; max-height: none; box-shadow: none; } .mini { width: min(300px, calc(100vw - 16px)); }
1719
+ .snd { margin-top: 10px; } .snd-panel { display: grid; gap: 4px; margin-top: 6px; } .snd-check { display: flex; align-items: center; gap: 6px; margin: 4px 0; } .snd-toggle { width: 100%; text-align: left; } .snd input[type=range] { padding: 0; }
1720
+ .panel h2 { margin-bottom: 6px; } .panel .hint:empty { display: none; }
1721
+ @keyframes ring { 0%,100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--_accent) 60%, transparent); } 50% { box-shadow: 0 0 0 9px transparent; } }
1722
+ `;
1723
+ var SIDE = { inline: { h: "left", v: "down" } };
1724
+ function renderWidget(s, { S = stringsFor(), dp, open = false, inline = false, side = { h: "left", v: "down" }, calls: calls2 = [], missed = 0, now = Date.now(), canHold = false, canDtmf = false, keypadOpen = false, hasController = false, sound, soundOpen = false, voices = [] } = {}) {
1725
+ var _a2;
1726
+ const active = s.status === "ringing" || s.status === "in-call";
1727
+ const label = iconLabel(S, { status: s.status, missed, open });
1728
+ const live = s.status === "ringing" ? `${S.ringing}: ${(_a2 = s.caller) != null ? _a2 : ""}` : s.status === "in-call" ? S.inCall : "";
1729
+ const callBody = s.status === "ringing" ? html`<div class="who">${s.caller}</div><div class="hint">${S.isCalling}</div><div class="btns"><button class="ok" data-action="answer">${S.answer}</button><button class="danger" data-action="hangup">${S.decline}</button></div>` : html`${renderCallControls(s, { S, now, canHold, canDtmf, keypadOpen })}${keypadOpen && dp ? renderKeypad(dp, { S, mode: "dtmf" }) : ""}`;
1730
+ const idle = !hasController || s.status === "ready";
1731
+ const body = active ? callBody : html`
1732
+ ${s.error ? html`<p class="err" role="alert">${s.error}</p>` : ""}
1733
+ ${s.warning ? html`<p class="status bad" role="status">${s.warning}</p>` : ""}
1734
+ ${hasController && (s.status === "off" || s.status === "error") ? html`<div class="btns"><button class="primary" data-action="start">${s.status === "error" ? S.tryAgain : S.goOnline}</button></div><p class="hint">${S.goOnlineHint}</p>` : ""}
1735
+ ${hasController && s.status === "connecting" ? html`<p class="hint" role="status">${S.connecting}</p>` : ""}
1736
+ ${hasController && s.status === "ready" ? renderLastCall(s, S) : ""}
1737
+ ${s.placing ? html`<p class="status" role="status">${t(S, "placing", { number: s.placing.number })}</p>` : ""}
1738
+ ${idle && dp ? renderKeypad(dp, { S, busy: s.dialing }) : ""}
1739
+ ${hasController && s.status === "ready" ? html`<h3>${S.recent}</h3>${renderRecentCalls(calls2, S)}` : ""}
1740
+ ${sound && idle ? renderSoundOptions(sound, S, { open: soundOpen, voices, idPrefix: "w-snd" }) : ""}`;
1741
+ const panel = html`<div class="panel ${inline ? "inline" : ""}" id="panel" role="dialog" aria-modal="false" aria-label="${S.dialogLabel}" data-h="${side.h}" data-v="${side.v}">${body}</div>`;
1742
+ const mini = html`<div class="mini" role="region" aria-label="${S.dialogLabel}" data-h="${side.h}" data-v="${side.v}">${callBody}</div>`;
1743
+ return html`<div class="w">
1744
+ ${inline ? "" : html`<button type="button" class="fab ${s.status}" id="fab" data-action="toggle" aria-haspopup="dialog" aria-expanded="${String(Boolean(open))}" aria-controls="panel" aria-label="${label}"><slot name="icon">${raw(ICON)}</slot>${missed > 0 && !active ? html`<span class="badge" aria-hidden="true">${missed > 9 ? "9+" : missed}</span>` : ""}</button>`}
1745
+ ${open || inline ? panel : active ? mini : ""}
1746
+ <div class="sr" role="status" aria-live="polite">${live}</div>
1747
+ </div>`.toString();
1748
+ }
1749
+ var TraitOSDialerWidget = class extends PhoneBase {
1750
+ static get observedAttributes() {
1751
+ return [...super.observedAttributes, "open"];
1752
+ }
1753
+ constructor() {
1754
+ super();
1755
+ this.pop = createOpenState({ onChange: (o) => this._opened(o) });
1756
+ }
1757
+ get css() {
1758
+ return css2;
1759
+ }
1760
+ get isOpen() {
1761
+ return this.pop.open;
1762
+ }
1763
+ open() {
1764
+ return this.pop.openIt();
1765
+ }
1766
+ close() {
1767
+ const r = this.pop.close();
1768
+ return r;
1769
+ }
1770
+ toggle() {
1771
+ return this.pop.toggle();
1772
+ }
1773
+ mounted() {
1774
+ super.mounted();
1775
+ this.pop.setInline(this.hasAttribute("inline"));
1776
+ if (this.hasAttribute("open")) this.pop.openIt();
1777
+ this._onDocPointer = (e) => this.pop.onOutside(e.composedPath(), this);
1778
+ this._onDocKey = (e) => {
1779
+ if (this.pop.onKey(e.key)) this._focusIcon();
1780
+ };
1781
+ document.addEventListener("pointerdown", this._onDocPointer, true);
1782
+ document.addEventListener("keydown", this._onDocKey);
1783
+ }
1784
+ unmounted() {
1785
+ document.removeEventListener("pointerdown", this._onDocPointer, true);
1786
+ document.removeEventListener("keydown", this._onDocKey);
1787
+ super.unmounted();
1788
+ }
1789
+ attributeChangedCallback(name) {
1790
+ if (name === "inline") this.pop.setInline(this.hasAttribute("inline"));
1791
+ if (name === "open") this.hasAttribute("open") ? this.pop.openIt() : this.pop.close();
1792
+ this.requestRender();
1793
+ }
1794
+ _opened(open) {
1795
+ var _a2;
1796
+ if (open) (_a2 = this.log) == null ? void 0 : _a2.markSeen();
1797
+ this.emit("traitos-toggle", { open });
1798
+ this.requestRender();
1799
+ if (open && !this.hasAttribute("inline")) setTimeout(() => {
1800
+ var _a3, _b;
1801
+ return (_b = (_a3 = this.shadowRoot) == null ? void 0 : _a3.getElementById("kp-number")) == null ? void 0 : _b.focus();
1802
+ }, 0);
1803
+ }
1804
+ _focusIcon() {
1805
+ setTimeout(() => {
1806
+ var _a2, _b;
1807
+ return (_b = (_a2 = this.shadowRoot) == null ? void 0 : _a2.getElementById("fab")) == null ? void 0 : _b.focus();
1808
+ }, 0);
1809
+ }
1810
+ _side() {
1811
+ var _a2;
1812
+ const place = placementOf({ position: this.getAttribute("position"), inline: this.hasAttribute("inline") });
1813
+ if (place.mode === "floating") return { h: place.corner.endsWith("right") ? "right" : "left", v: place.corner.startsWith("bottom") ? "up" : "down" };
1814
+ if (place.mode === "inline") return SIDE.inline;
1815
+ const r = (_a2 = this.getBoundingClientRect) == null ? void 0 : _a2.call(this);
1816
+ return r ? panelSide(r, { width: window.innerWidth, height: window.innerHeight }) : SIDE.inline;
1817
+ }
1818
+ render() {
1819
+ var _a2, _b, _c;
1820
+ const c = this.controller;
1821
+ const S = this.S;
1822
+ const s = (_a2 = c == null ? void 0 : c.snapshot()) != null ? _a2 : { status: "off", recent: [], error: null };
1823
+ return renderWidget(s, { S, dp: this.dp, open: this.pop.open, inline: this.hasAttribute("inline"), side: this._side(), calls: this.recentCalls(), missed: (_c = (_b = this.log) == null ? void 0 : _b.missedCount()) != null ? _c : 0, now: Date.now(), canHold: !!(c == null ? void 0 : c.canHold), canDtmf: !!(c == null ? void 0 : c.canDtmf), keypadOpen: this.keypadOpen, hasController: !!c, sound: this.sound, soundOpen: this._sndOpen, voices: this.sound.voices() });
1824
+ }
1825
+ onClick(action, node) {
1826
+ if (action === "toggle") {
1827
+ this.pop.toggle();
1828
+ return;
1829
+ }
1830
+ this.phoneClick(action, node);
1831
+ }
1832
+ };
1833
+ define("traitos-dialer-widget", TraitOSDialerWidget);
1834
+
1835
+ // src/core/settingsSections.js
1836
+ var SIP_HANDLE = /^[A-Za-z0-9._-]{3,64}$/;
1837
+ var MAX_STEPS = 4;
1838
+ var RING = { min: 5, max: 60, softphone: 15, phone: 30 };
1839
+ var RULE_OPS = ["gt", "gte", "lt", "lte", "eq", "neq", "contains"];
1840
+ var 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" };
1841
+ var clone = (v) => JSON.parse(JSON.stringify(v));
1842
+ var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1843
+ var intIn = (v, min, max) => Number.isInteger(Number(v)) && String(v).trim() !== "" && Number(v) >= min && Number(v) <= max;
1844
+ var handoff = {
1845
+ id: "handoff",
1846
+ label: "Human handoff",
1847
+ description: "Who is rung, in order, when an agent passes a conversation to a person. If nobody answers, the AI carries on.",
1848
+ needsAgent: true,
1849
+ async load(client, { agentId }) {
1850
+ var _a2, _b, _c, _d, _e;
1851
+ const s = await client.agents.handoffSettings.get(agentId);
1852
+ return {
1853
+ transferNumber: (_a2 = s.transferNumber) != null ? _a2 : "",
1854
+ callerId: (_c = (_b = s.routing) == null ? void 0 : _b.callerId) != null ? _c : "customer",
1855
+ steps: ((_e = (_d = s.routing) == null ? void 0 : _d.steps) != null ? _e : []).map((x) => {
1856
+ var _a3, _b2;
1857
+ return { kind: x.kind, target: x.target, ringSecs: (_b2 = (_a3 = x.ringSecs) != null ? _a3 : RING[x.kind]) != null ? _b2 : RING.phone };
1858
+ })
1859
+ };
1860
+ },
1861
+ validate(m) {
1862
+ const e = {};
1863
+ if (m.transferNumber && !isE164(m.transferNumber)) e.transferNumber = "Use + then country code and number, like +18765550100.";
1864
+ if (m.steps.length > MAX_STEPS) e.steps = `At most ${MAX_STEPS} people can be rung.`;
1865
+ m.steps.forEach((s, i) => {
1866
+ var _a2;
1867
+ if (s.kind !== "softphone" && s.kind !== "phone") e[`steps.${i}.kind`] = "Choose softphone or phone.";
1868
+ else if (s.kind === "phone" && !isE164(s.target)) e[`steps.${i}.target`] = "Use + then country code and number.";
1869
+ else if (s.kind === "softphone" && !SIP_HANDLE.test(String((_a2 = s.target) != null ? _a2 : ""))) e[`steps.${i}.target`] = "A softphone name has 3 to 64 letters, numbers, dots, dashes or underscores.";
1870
+ if (!intIn(s.ringSecs, RING.min, RING.max)) e[`steps.${i}.ringSecs`] = `Ring for ${RING.min} to ${RING.max} seconds.`;
1871
+ });
1872
+ if (m.callerId !== "customer" && m.callerId !== "platform") e.callerId = "Choose which number the person sees.";
1873
+ return e;
1874
+ },
1875
+ toPatch(orig, draft) {
1876
+ const patch = {};
1877
+ if (orig.transferNumber !== draft.transferNumber) patch.transferNumber = draft.transferNumber || null;
1878
+ const routing = (m) => ({ steps: m.steps.map((s) => ({ kind: s.kind, target: String(s.target).trim(), ringSecs: Number(s.ringSecs) })), callerId: m.callerId });
1879
+ if (!same(routing(orig), routing(draft))) patch.routing = draft.steps.length ? routing(draft) : null;
1880
+ return Object.keys(patch).length ? patch : null;
1881
+ },
1882
+ save: (client, { agentId }, patch) => client.agents.handoffSettings.update(agentId, patch),
1883
+ // edits
1884
+ addStep(m, kind = "phone") {
1885
+ if (m.steps.length < MAX_STEPS) m.steps.push({ kind, target: "", ringSecs: RING[kind] });
1886
+ },
1887
+ removeStep(m, i) {
1888
+ m.steps.splice(i, 1);
1889
+ },
1890
+ moveStep(m, i, dir) {
1891
+ const j = i + dir;
1892
+ if (j >= 0 && j < m.steps.length) [m.steps[i], m.steps[j]] = [m.steps[j], m.steps[i]];
1893
+ },
1894
+ setStep(m, i, field2, value) {
1895
+ var _a2;
1896
+ const s = m.steps[i];
1897
+ if (!s) return;
1898
+ s[field2] = field2 === "ringSecs" ? value === "" ? "" : Number(value) : value;
1899
+ if (field2 === "kind") s.ringSecs = (_a2 = RING[value]) != null ? _a2 : s.ringSecs;
1900
+ }
1901
+ };
1902
+ var approvals = {
1903
+ id: "approvals",
1904
+ label: "Approvals",
1905
+ description: "When an agent must ask a person first, how long it waits, and what happens if nobody answers.",
1906
+ needsAgent: false,
1907
+ async load(client, { agentId }) {
1908
+ var _a2, _b, _c, _d;
1909
+ const [s, r] = await Promise.all([client.approvals.settings(), agentId ? client.approvals.rules.list(agentId) : Promise.resolve({ rules: [] })]);
1910
+ return {
1911
+ timeoutMinutes: (_a2 = s.timeoutMinutes) != null ? _a2 : 60,
1912
+ onTimeout: (_b = s.onTimeout) != null ? _b : "escalate",
1913
+ liveWaitSeconds: (_c = s.liveWaitSeconds) != null ? _c : 0,
1914
+ notifyEmail: Boolean(s.notifyEmail),
1915
+ rules: ((_d = r.rules) != null ? _d : []).map((x) => {
1916
+ var _a3;
1917
+ return { tool: x.tool, action: x.action, note: (_a3 = x.note) != null ? _a3 : "", ...x.when ? { when: { ...x.when } } : {} };
1918
+ })
1919
+ };
1920
+ },
1921
+ validate(m) {
1922
+ const e = {};
1923
+ if (!intIn(m.timeoutMinutes, 1, 60 * 24 * 14)) e.timeoutMinutes = "Choose between 1 minute and 14 days (20160).";
1924
+ if (m.onTimeout !== "escalate" && m.onTimeout !== "deny") e.onTimeout = "Choose what happens when nobody answers.";
1925
+ if (!intIn(m.liveWaitSeconds, 0, 600)) e.liveWaitSeconds = "Choose between 0 and 600 seconds.";
1926
+ m.rules.forEach((r, i) => {
1927
+ var _a2, _b, _c;
1928
+ if (!String((_a2 = r.tool) != null ? _a2 : "").trim()) e[`rules.${i}.tool`] = "Name a tool, like refund.create or refund.*.";
1929
+ if (!["ask", "allow", "deny"].includes(r.action)) e[`rules.${i}.action`] = "Choose ask, allow or deny.";
1930
+ if (r.when) {
1931
+ if (!String((_b = r.when.field) != null ? _b : "").trim()) e[`rules.${i}.when.field`] = "Name the field to check.";
1932
+ if (!RULE_OPS.includes(r.when.op)) e[`rules.${i}.when.op`] = "Choose a comparison.";
1933
+ if (String((_c = r.when.value) != null ? _c : "") === "") e[`rules.${i}.when.value`] = "Give a value to compare with.";
1934
+ }
1935
+ });
1936
+ return e;
1937
+ },
1938
+ toPatch(orig, draft) {
1939
+ const patch = {};
1940
+ const settings = {};
1941
+ for (const k of ["timeoutMinutes", "onTimeout", "liveWaitSeconds", "notifyEmail"]) if (orig[k] !== draft[k]) settings[k] = k === "onTimeout" || k === "notifyEmail" ? draft[k] : Number(draft[k]);
1942
+ if (Object.keys(settings).length) patch.settings = settings;
1943
+ 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 } } : {} }));
1944
+ if (!same(rules(orig), rules(draft))) patch.rules = rules(draft);
1945
+ return Object.keys(patch).length ? patch : null;
1946
+ },
1947
+ async save(client, { agentId }, patch) {
1948
+ if (patch.settings) await client.approvals.updateSettings(patch.settings);
1949
+ if (patch.rules) {
1950
+ if (!agentId) throw new Error("Choose an agent to change its approval rules.");
1951
+ await client.approvals.rules.set(agentId, patch.rules);
1952
+ }
1953
+ },
1954
+ addRule(m) {
1955
+ m.rules.push({ tool: "", action: "ask", note: "" });
1956
+ },
1957
+ removeRule(m, i) {
1958
+ m.rules.splice(i, 1);
1959
+ },
1960
+ setRule(m, i, field2, value) {
1961
+ if (m.rules[i]) m.rules[i][field2] = value;
1962
+ },
1963
+ toggleCondition(m, i, on) {
1964
+ var _a2;
1965
+ const r = m.rules[i];
1966
+ if (!r) return;
1967
+ if (on) r.when = (_a2 = r.when) != null ? _a2 : { field: "", op: "gt", value: "" };
1968
+ else delete r.when;
1969
+ },
1970
+ setCondition(m, i, field2, value) {
1971
+ const r = m.rules[i];
1972
+ if (r == null ? void 0 : r.when) r.when[field2] = value;
1973
+ }
1974
+ };
1975
+ var usage = {
1976
+ id: "usage",
1977
+ label: "Usage and spend cap",
1978
+ description: "This month against your plan. Set a cap and conversations pause (with your message) instead of running up overage.",
1979
+ needsAgent: false,
1980
+ async load(client) {
1981
+ var _a2, _b, _c, _d, _e, _f, _g;
1982
+ const u = await client.usage.current();
1983
+ const cap = (_a2 = u.overage) == null ? void 0 : _a2.spendCapCents;
1984
+ return {
1985
+ meters: (_b = u.meters) != null ? _b : [],
1986
+ period: u.period,
1987
+ status: u.status,
1988
+ plan: (_d = (_c = u.plan) == null ? void 0 : _c.name) != null ? _d : "",
1989
+ overageCents: (_f = (_e = u.overage) == null ? void 0 : _e.cents) != null ? _f : 0,
1990
+ spendCap: cap === null || cap === void 0 ? "" : String(cap / 100),
1991
+ fallbackMessage: (_g = u.fallbackMessage) != null ? _g : ""
1992
+ };
1993
+ },
1994
+ validate(m) {
1995
+ const e = {};
1996
+ 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.";
1997
+ if (String(m.fallbackMessage).length > 500) e.fallbackMessage = "Keep this under 500 characters.";
1998
+ return e;
1999
+ },
2000
+ toPatch(orig, draft) {
2001
+ const patch = {};
2002
+ if (orig.spendCap !== draft.spendCap) patch.spendCapCents = draft.spendCap === "" ? null : Math.round(Number(draft.spendCap) * 100);
2003
+ if (orig.fallbackMessage !== draft.fallbackMessage) patch.fallbackMessage = draft.fallbackMessage || null;
2004
+ return Object.keys(patch).length ? patch : null;
2005
+ },
2006
+ save: (client, _ctx, patch) => client.usage.updateSettings(patch)
2007
+ };
2008
+ var 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." }];
2009
+ var dialer = {
2010
+ id: "dialer",
2011
+ label: "Dialer",
2012
+ description: "Your phone lines, how outbound calls are placed, and how this browser rings.",
2013
+ needsAgent: false,
2014
+ async load(client, { storage }) {
2015
+ var _a2;
2016
+ const [lines, mode] = await Promise.allSettled([listLines(client), getOutboundMode(client)]);
2017
+ if (lines.status === "rejected" && mode.status === "rejected") throw mode.reason;
2018
+ const p = loadPrefs(storage);
2019
+ const ls = lines.status === "fulfilled" ? lines.value : [];
2020
+ const ch = (l) => Array.isArray(l.channels) ? l.channels : [];
2021
+ return {
2022
+ mode: mode.status === "fulfilled" ? mode.value : null,
2023
+ lines: ls.map((l) => {
2024
+ var _a3;
2025
+ return { number: l.number, name: (_a3 = l.name) != null ? _a3 : "", whatsapp: ch(l).includes("whatsapp_calling"), phone: ch(l).includes("voice") };
2026
+ }),
2027
+ whatsappEnabled: ls.some((l) => ch(l).includes("whatsapp_calling")),
2028
+ phoneEnabled: ls.some((l) => ch(l).includes("voice")),
2029
+ ringTimeoutSeconds: p.ringTimeoutSeconds,
2030
+ ringWhatsapp: p.ringChannels.whatsapp,
2031
+ ringPhone: p.ringChannels.phone,
2032
+ callerId: (_a2 = p.callerId) != null ? _a2 : ""
2033
+ };
2034
+ },
2035
+ validate(m) {
2036
+ const e = {};
2037
+ if (m.mode !== null && !OUTBOUND_MODES.some((x) => x.id === m.mode)) e.mode = "Choose how outbound calls are placed.";
2038
+ if (!intIn(m.ringTimeoutSeconds, 0, MAX_RING_SECONDS)) e.ringTimeoutSeconds = `Ring for 0 to ${MAX_RING_SECONDS} seconds.`;
2039
+ return e;
2040
+ },
2041
+ toPatch(orig, draft) {
2042
+ const patch = {};
2043
+ if (draft.mode !== null && orig.mode !== draft.mode) patch.mode = draft.mode;
2044
+ const prefs = (m) => normalizePrefs({ ringTimeoutSeconds: m.ringTimeoutSeconds, ringChannels: { whatsapp: m.ringWhatsapp, phone: m.ringPhone }, callerId: m.callerId });
2045
+ if (!same(prefs(orig), prefs(draft))) patch.prefs = prefs(draft);
2046
+ return Object.keys(patch).length ? patch : null;
2047
+ },
2048
+ async save(client, { storage }, patch) {
2049
+ var _a2;
2050
+ if (patch.mode) await setOutboundMode(client, patch.mode);
2051
+ if (patch.prefs) {
2052
+ savePrefs(storage, patch.prefs);
2053
+ (_a2 = globalThis.dispatchEvent) == null ? void 0 : _a2.call(globalThis, new CustomEvent(PREFS_EVENT));
2054
+ }
2055
+ }
2056
+ };
2057
+ var SECTIONS = Object.freeze({ handoff, approvals, usage, dialer });
2058
+
2059
+ // src/core/settingsController.js
2060
+ var SettingsController = class {
2061
+ /**
2062
+ * @param {{client: object, agentId?: string, sections?: string[], storage?: Storage}} options `storage` holds the dialer's browser-only settings
2063
+ */
2064
+ constructor({ client, agentId, sections = ["handoff", "approvals", "usage"], storage }) {
2065
+ this.client = client;
2066
+ this.storage = storage;
2067
+ this.agentId = agentId;
2068
+ this.ids = sections.filter((id) => SECTIONS[id]);
2069
+ this._listeners = /* @__PURE__ */ new Set();
2070
+ this._seq = {};
2071
+ this.state = Object.fromEntries(this.ids.map((id) => [id, this._blank(id)]));
2072
+ }
2073
+ _blank(id) {
2074
+ const needsAgent = SECTIONS[id].needsAgent && !this.agentId;
2075
+ return { id, status: needsAgent ? "needs-agent" : "idle", original: null, draft: null, errors: {}, message: null, dirty: false };
2076
+ }
2077
+ snapshot() {
2078
+ return Object.fromEntries(this.ids.map((id) => [id, { ...this.state[id] }]));
2079
+ }
2080
+ subscribe(fn) {
2081
+ this._listeners.add(fn);
2082
+ return () => this._listeners.delete(fn);
2083
+ }
2084
+ _patch(id, patch) {
2085
+ this.state[id] = { ...this.state[id], ...patch };
2086
+ for (const fn of [...this._listeners]) {
2087
+ try {
2088
+ fn(this.snapshot());
2089
+ } catch {
2090
+ }
2091
+ }
2092
+ }
2093
+ setAgent(agentId) {
2094
+ this.agentId = agentId;
2095
+ for (const id of this.ids) this.state[id] = this._blank(id);
2096
+ return this.loadAll();
2097
+ }
2098
+ loadAll() {
2099
+ return Promise.all(this.ids.map((id) => this.load(id)));
2100
+ }
2101
+ async load(id) {
2102
+ var _a2;
2103
+ const def = SECTIONS[id];
2104
+ if (def.needsAgent && !this.agentId) return this._patch(id, { status: "needs-agent" });
2105
+ const n = this._seq[id] = ((_a2 = this._seq[id]) != null ? _a2 : 0) + 1;
2106
+ this._patch(id, { status: "loading", message: null });
2107
+ try {
2108
+ const model = await def.load(this.client, { agentId: this.agentId, storage: this.storage });
2109
+ if (n !== this._seq[id]) return;
2110
+ this._patch(id, { status: "ready", original: model, draft: clone(model), errors: {}, dirty: false });
2111
+ } catch (error) {
2112
+ if (n !== this._seq[id]) return;
2113
+ this._patch(id, { status: "error", message: (error == null ? void 0 : error.message) || "Could not load this section." });
2114
+ }
2115
+ }
2116
+ /** Change the draft with a function that mutates it (one of the section's edit helpers, or your own). */
2117
+ edit(id, mutate) {
2118
+ const s = this.state[id];
2119
+ if (!s.draft || s.status === "saving") return;
2120
+ const draft = clone(s.draft);
2121
+ mutate(draft, SECTIONS[id]);
2122
+ const errors = SECTIONS[id].validate(draft);
2123
+ this._patch(id, { draft, errors, dirty: SECTIONS[id].toPatch(s.original, draft) !== null, message: null, status: s.status === "saved" ? "ready" : s.status });
2124
+ }
2125
+ /** Set a top-level field, e.g. `set('handoff', 'transferNumber', '+1876…')`. */
2126
+ set(id, field2, value) {
2127
+ this.edit(id, (d) => {
2128
+ d[field2] = value;
2129
+ });
2130
+ }
2131
+ reset(id) {
2132
+ const s = this.state[id];
2133
+ if (s.original) this._patch(id, { draft: clone(s.original), errors: {}, dirty: false, message: null, status: "ready" });
2134
+ }
2135
+ /** Save the section. Resolves true when saved. Validation errors stay on the form; nothing is sent. */
2136
+ async save(id) {
2137
+ const def = SECTIONS[id];
2138
+ const s = this.state[id];
2139
+ if (!s.draft || s.status === "saving") return false;
2140
+ const errors = def.validate(s.draft);
2141
+ if (Object.keys(errors).length) {
2142
+ this._patch(id, { errors, message: "Fix the highlighted fields first." });
2143
+ return false;
2144
+ }
2145
+ const patch = def.toPatch(s.original, s.draft);
2146
+ if (!patch) {
2147
+ this._patch(id, { message: "Nothing to save." });
2148
+ return false;
2149
+ }
2150
+ this._patch(id, { status: "saving", message: null });
2151
+ try {
2152
+ await def.save(this.client, { agentId: this.agentId, storage: this.storage }, patch);
2153
+ await this.load(id);
2154
+ this._patch(id, { status: "saved", message: "Saved." });
2155
+ return true;
2156
+ } catch (error) {
2157
+ this._patch(id, { status: "ready", message: (error == null ? void 0 : error.message) || "Could not save." });
2158
+ return false;
2159
+ }
2160
+ }
2161
+ };
2162
+
2163
+ // src/elements/settings.js
2164
+ var css3 = `
2165
+ section.card { margin-bottom: 14px; } .steps { list-style: none; margin: 0; padding: 0; } .steps > li, .rule { border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 8px 10px; margin: 6px 0; }
2166
+ .meter { margin: 8px 0; } .meter .top { display: flex; justify-content: space-between; font-size: 13px; }
2167
+ .linkish { background: none; border: 0; color: var(--_accent); padding: 2px 4px; }
2168
+ `;
2169
+ var err = (errors, path) => errors[path] ? html`<p class="err" id="e-${path}" role="alert">${errors[path]}</p>` : "";
2170
+ var bad = (errors, path) => errors[path] ? 'aria-invalid="true"' : "";
2171
+ function field(errors, key, label, value, { type = "text", hint = "", attrs = "", section, f, i }) {
2172
+ const id = `${section}-${key}`;
2173
+ return html`<label for="${id}">${label}</label>
2174
+ <input id="${id}" data-key="${key}" data-s="${section}" data-f="${f != null ? f : key}" ${i !== void 0 ? raw(`data-i="${i}"`) : ""} type="${type}" value="${value != null ? value : ""}" ${raw(attrs)} ${raw(bad(errors, key))} />
2175
+ ${hint ? html`<p class="hint">${hint}</p>` : ""}${err(errors, key)}`;
2176
+ }
2177
+ function renderHandoff(s) {
2178
+ const { draft: d, errors: e } = s;
2179
+ return html`
2180
+ ${field(e, "transferNumber", "Transfer number", d.transferNumber, { type: "tel", hint: "A phone number to transfer to. Leave empty for none.", section: "handoff" })}
2181
+ <h3>Who to ring, in order</h3>
2182
+ ${err(e, "steps")}
2183
+ <ol class="steps">${d.steps.map((st, i) => html`<li>
2184
+ <div class="row">
2185
+ <div><label for="h-kind-${i}">Ring a</label><select id="h-kind-${i}" data-key="steps.${i}.kind" data-s="handoff" data-i="${i}" data-f="kind"><option value="softphone" ${st.kind === "softphone" ? "selected" : ""}>Browser softphone</option><option value="phone" ${st.kind === "phone" ? "selected" : ""}>Phone number</option></select></div>
2186
+ <div><label for="h-target-${i}">${st.kind === "phone" ? "Number" : "Softphone name"}</label><input id="h-target-${i}" data-key="steps.${i}.target" data-s="handoff" data-i="${i}" data-f="target" value="${st.target}" placeholder="${st.kind === "phone" ? "+18765550100" : "agent_01"}" ${raw(bad(e, `steps.${i}.target`))} />${err(e, `steps.${i}.target`)}</div>
2187
+ <div class="fixed" style="width:96px"><label for="h-ring-${i}">Seconds</label><input id="h-ring-${i}" data-key="steps.${i}.ringSecs" data-s="handoff" data-i="${i}" data-f="ringSecs" type="number" min="${RING.min}" max="${RING.max}" value="${st.ringSecs}" ${raw(bad(e, `steps.${i}.ringSecs`))} />${err(e, `steps.${i}.ringSecs`)}</div>
2188
+ <div class="fixed"><button type="button" data-action="step-up" data-s="handoff" data-i="${i}" aria-label="Move step ${i + 1} up" ${i === 0 ? "disabled" : ""}>↑</button> <button type="button" data-action="step-down" data-s="handoff" data-i="${i}" aria-label="Move step ${i + 1} down" ${i === d.steps.length - 1 ? "disabled" : ""}>↓</button> <button type="button" class="linkish" data-action="step-remove" data-s="handoff" data-i="${i}" aria-label="Remove step ${i + 1}">Remove</button></div>
2189
+ </div></li>`)}</ol>
2190
+ <button type="button" data-action="step-add" data-s="handoff" ${d.steps.length >= MAX_STEPS ? "disabled" : ""}>Add someone to ring</button>
2191
+ <label for="h-caller">The person sees</label>
2192
+ <select id="h-caller" data-key="callerId" data-s="handoff" data-f="callerId"><option value="customer" ${d.callerId === "customer" ? "selected" : ""}>The customer's number</option><option value="platform" ${d.callerId === "platform" ? "selected" : ""}>Your company number</option></select>${err(e, "callerId")}`;
2193
+ }
2194
+ function renderApprovals(s, agentId) {
2195
+ const { draft: d, errors: e } = s;
2196
+ return html`
2197
+ <div class="row">
2198
+ <div>${field(e, "timeoutMinutes", "Wait for an answer (minutes)", d.timeoutMinutes, { type: "number", section: "approvals", attrs: 'min="1" max="20160"' })}</div>
2199
+ <div><label for="a-on">If nobody answers</label><select id="a-on" data-key="onTimeout" data-s="approvals" data-f="onTimeout"><option value="escalate" ${d.onTimeout === "escalate" ? "selected" : ""}>Escalate to a person</option><option value="deny" ${d.onTimeout === "deny" ? "selected" : ""}>Deny the request</option></select>${err(e, "onTimeout")}</div>
2200
+ <div>${field(e, "liveWaitSeconds", "Live chat wait (seconds)", d.liveWaitSeconds, { type: "number", section: "approvals", attrs: 'min="0" max="600"' })}</div>
2201
+ </div>
2202
+ <label><input type="checkbox" data-key="notifyEmail" data-s="approvals" data-f="notifyEmail" ${d.notifyEmail ? "checked" : ""} />Email admins when something needs approval</label>
2203
+ <h3>Rules for this agent</h3>
2204
+ ${agentId ? "" : html`<p class="hint">Choose an agent to edit its rules.</p>`}
2205
+ ${agentId ? html`${d.rules.map((r, i) => html`<div class="rule">
2206
+ <div class="row">
2207
+ <div><label for="r-tool-${i}">Tool</label><input id="r-tool-${i}" data-key="rules.${i}.tool" data-s="approvals" data-i="${i}" data-f="tool" value="${r.tool}" placeholder="refund.create or refund.*" ${raw(bad(e, `rules.${i}.tool`))} />${err(e, `rules.${i}.tool`)}</div>
2208
+ <div class="fixed"><label for="r-act-${i}">Then</label><select id="r-act-${i}" data-key="rules.${i}.action" data-s="approvals" data-i="${i}" data-f="action">${["ask", "allow", "deny"].map((a) => html`<option value="${a}" ${r.action === a ? "selected" : ""}>${a === "ask" ? "Ask a person" : a === "allow" ? "Allow" : "Deny"}</option>`)}</select></div>
2209
+ <div class="fixed"><button type="button" class="linkish" data-action="rule-remove" data-s="approvals" data-i="${i}" aria-label="Remove rule ${i + 1}">Remove</button></div>
2210
+ </div>
2211
+ <label><input type="checkbox" data-key="rules.${i}.cond" data-s="approvals" data-i="${i}" data-f="cond" ${r.when ? "checked" : ""} />Only when a value matches</label>
2212
+ ${r.when ? html`<div class="row">
2213
+ <div><input aria-label="Field" data-key="rules.${i}.when.field" data-s="approvals" data-i="${i}" data-f="when.field" value="${r.when.field}" placeholder="amount" ${raw(bad(e, `rules.${i}.when.field`))} />${err(e, `rules.${i}.when.field`)}</div>
2214
+ <div class="fixed"><select aria-label="Comparison" data-key="rules.${i}.when.op" data-s="approvals" data-i="${i}" data-f="when.op">${RULE_OPS.map((o) => html`<option value="${o}" ${r.when.op === o ? "selected" : ""}>${RULE_OP_LABEL[o]}</option>`)}</select></div>
2215
+ <div><input aria-label="Value" data-key="rules.${i}.when.value" data-s="approvals" data-i="${i}" data-f="when.value" value="${r.when.value}" placeholder="100" ${raw(bad(e, `rules.${i}.when.value`))} />${err(e, `rules.${i}.when.value`)}</div>
2216
+ </div>` : ""}</div>`)}
2217
+ <button type="button" data-action="rule-add" data-s="approvals">Add a rule</button>` : ""}`;
2218
+ }
2219
+ function renderUsage(s) {
2220
+ const { draft: d, errors: e } = s;
2221
+ return html`
2222
+ <p class="hint">${d.plan ? html`<b>${d.plan}</b> plan, ` : ""}${d.period}${d.status === "paused" ? " \u2014 conversations are paused (cap reached)" : ""}</p>
2223
+ ${d.meters.map((m) => {
2224
+ var _a2, _b;
2225
+ return html`<div class="meter"><div class="top"><span>${m.label}</span><span>${m.used}${m.included === null ? " (unlimited)" : ` of ${m.included}`}</span></div>
2226
+ <div class="bar" role="progressbar" aria-label="${m.label}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${(_a2 = m.percent) != null ? _a2 : 0}"><i style="width:${Math.min(100, (_b = m.percent) != null ? _b : 0)}%"></i></div></div>`;
2227
+ })}
2228
+ ${field(e, "spendCap", "Monthly spend cap (USD)", d.spendCap, { type: "number", hint: "Blank means no cap. Past the cap, conversations pause instead of billing overage.", section: "usage", attrs: 'min="0" step="0.01"' })}
2229
+ <label for="u-msg">Message customers see while paused</label>
2230
+ <textarea id="u-msg" rows="2" data-key="fallbackMessage" data-s="usage" data-f="fallbackMessage">${d.fallbackMessage}</textarea>${err(e, "fallbackMessage")}`;
2231
+ }
2232
+ function renderDialer(s) {
2233
+ const { draft: d, errors: e } = s;
2234
+ const line = (l) => l.name ? `${l.name} \xB7 ${l.number}` : l.number;
2235
+ return html`
2236
+ <h3>Lines</h3>
2237
+ ${d.lines.length ? html`<ul class="steps">${d.lines.map((l) => html`<li>${line(l)} <span class="hint">${[l.whatsapp && "WhatsApp", l.phone && "Phone"].filter(Boolean).join(" \xB7 ")}</span></li>`)}</ul>` : html`<p class="hint">No phone lines yet.</p>`}
2238
+ <p class="hint">Enabled for calling: ${[d.whatsappEnabled && "WhatsApp", d.phoneEnabled && "Phone"].filter(Boolean).join(", ") || "none"}</p>
2239
+ <h3>How outbound calls are placed</h3>
2240
+ ${d.mode === null ? html`<p class="hint">Not available to this account.</p>` : html`<fieldset style="border:0;padding:0;margin:0"><legend class="sr">How outbound calls are placed</legend>${OUTBOUND_MODES.map((m) => html`<label><input type="radio" name="d-mode" data-key="mode.${m.id}" data-s="dialer" data-f="mode" value="${m.id}" ${d.mode === m.id ? "checked" : ""} />${m.label} <span class="hint">${m.hint}</span></label>`)}</fieldset><p class="hint">Changing this needs an organization admin.</p>${err(e, "mode")}`}
2241
+ <h3>This browser</h3>
2242
+ <p class="hint">Saved in this browser only; the server does not store these.</p>
2243
+ <label for="d-ring">Ring timeout (seconds, 0 for the default)</label>
2244
+ <input id="d-ring" type="number" min="0" max="${MAX_RING_SECONDS}" data-key="ringTimeoutSeconds" data-s="dialer" data-f="ringTimeoutSeconds" value="${d.ringTimeoutSeconds}" ${raw(bad(e, "ringTimeoutSeconds"))} />${err(e, "ringTimeoutSeconds")}
2245
+ <label><input type="checkbox" data-key="ringWhatsapp" data-s="dialer" data-f="ringWhatsapp" ${d.ringWhatsapp ? "checked" : ""} ${d.whatsappEnabled ? "" : "disabled"} />Ring this browser for WhatsApp calls${d.whatsappEnabled ? "" : " (not enabled)"}</label>
2246
+ <label><input type="checkbox" data-key="ringPhone" data-s="dialer" data-f="ringPhone" ${d.ringPhone ? "checked" : ""} ${d.phoneEnabled ? "" : "disabled"} />Ring this browser for phone calls${d.phoneEnabled ? "" : " (not enabled)"}</label>
2247
+ <label for="d-caller">Caller ID line</label>
2248
+ <select id="d-caller" data-key="callerId" data-s="dialer" data-f="callerId"><option value="">Default line</option>${d.lines.map((l) => html`<option value="${l.number}" ${d.callerId === l.number ? "selected" : ""}>${line(l)}</option>`)}</select>
2249
+ <p class="hint">Pass the saved line as <code>from</code> when your page places a call.</p>`;
2250
+ }
2251
+ function renderSettings(snapshot, { agentId, ids = Object.keys(snapshot) } = {}) {
2252
+ return html`${ids.map((id) => {
2253
+ const s = snapshot[id];
2254
+ const def = SECTIONS[id];
2255
+ const body = s.status === "needs-agent" ? html`<p class="hint">Choose an agent to edit this section.</p>` : s.status === "loading" || s.status === "idle" ? html`<p class="hint" role="status">Loading…</p>` : s.status === "error" ? html`<p class="err" role="alert">${s.message}</p><button data-action="reload" data-s="${id}">Try again</button>` : html`<form data-submit="save" data-s="${id}" novalidate>
2256
+ ${id === "handoff" ? renderHandoff(s) : id === "approvals" ? renderApprovals(s, agentId) : id === "dialer" ? renderDialer(s) : renderUsage(s)}
2257
+ ${s.message ? html`<p class="${s.status === "saved" ? "status ok" : "status bad"}" role="status">${s.message}</p>` : ""}
2258
+ <div class="actions"><button type="button" data-action="reset" data-s="${id}" ${s.dirty ? "" : "disabled"}>Discard changes</button><button type="submit" class="primary" ${!s.dirty || s.status === "saving" ? "disabled" : ""}>${s.status === "saving" ? "Saving\u2026" : "Save"}</button></div></form>`;
2259
+ return html`<section class="card" aria-labelledby="t-${id}"><h2 id="t-${id}">${def.label}</h2><p class="hint">${def.description}</p>${body}</section>`;
2260
+ })}`.toString();
2261
+ }
2262
+ var TraitOSSettings = class extends TraitElement {
2263
+ static get observedAttributes() {
2264
+ return ["agent-id", "sections"];
2265
+ }
2266
+ get css() {
2267
+ return css3;
2268
+ }
2269
+ set client(v) {
2270
+ this._client = v;
2271
+ this._init();
2272
+ }
2273
+ get client() {
2274
+ return this._client;
2275
+ }
2276
+ set storage(v) {
2277
+ this._storage = v;
2278
+ }
2279
+ mounted() {
2280
+ this._init();
2281
+ }
2282
+ unmounted() {
2283
+ var _a2;
2284
+ (_a2 = this._unsub) == null ? void 0 : _a2.call(this);
2285
+ this.controller = null;
2286
+ }
2287
+ attributeChangedCallback(name, old, val) {
2288
+ var _a2;
2289
+ if (old === val) return;
2290
+ if (name === "agent-id" && this.controller) this.controller.setAgent(val || void 0);
2291
+ if (name === "sections") {
2292
+ this.controller = null;
2293
+ (_a2 = this._unsub) == null ? void 0 : _a2.call(this);
2294
+ this._init();
2295
+ }
2296
+ }
2297
+ _init() {
2298
+ var _a2, _b;
2299
+ if (this.controller || !this._connected || !this._client) return;
2300
+ const sections = ((_a2 = this.getAttribute("sections")) != null ? _a2 : "handoff,approvals,usage").split(",").map((s) => s.trim()).filter(Boolean);
2301
+ this.controller = new SettingsController({ client: this._client, agentId: this.getAttribute("agent-id") || void 0, sections, storage: (_b = this._storage) != null ? _b : typeof localStorage !== "undefined" ? localStorage : void 0 });
2302
+ this._unsub = this.controller.subscribe(() => this.requestRender());
2303
+ this.controller.loadAll();
2304
+ this.requestRender();
2305
+ }
2306
+ render() {
2307
+ if (!this.controller) return html`<div class="card"><p class="hint">Set the <code>client</code> property to load settings.</p></div>`.toString();
2308
+ return renderSettings(this.controller.snapshot(), { agentId: this.controller.agentId, ids: this.controller.ids });
2309
+ }
2310
+ async onClick(action, node) {
2311
+ const c = this.controller;
2312
+ const id = node.dataset.s;
2313
+ const i = node.dataset.i === void 0 ? void 0 : Number(node.dataset.i);
2314
+ if (!c || !id) return;
2315
+ if (action === "save") {
2316
+ const ok = await c.save(id);
2317
+ if (ok) this.emit("traitos-saved", { section: id });
2318
+ else if (c.state[id].status !== "saving" && c.state[id].message) this.emit("traitos-error", { section: id, message: c.state[id].message });
2319
+ } else if (action === "reset") c.reset(id);
2320
+ else if (action === "reload") c.load(id);
2321
+ else if (action === "step-add") c.edit(id, (d, def) => def.addStep(d));
2322
+ else if (action === "step-remove") c.edit(id, (d, def) => def.removeStep(d, i));
2323
+ else if (action === "step-up") c.edit(id, (d, def) => def.moveStep(d, i, -1));
2324
+ else if (action === "step-down") c.edit(id, (d, def) => def.moveStep(d, i, 1));
2325
+ else if (action === "rule-add") c.edit(id, (d, def) => def.addRule(d));
2326
+ else if (action === "rule-remove") c.edit(id, (d, def) => def.removeRule(d, i));
2327
+ }
2328
+ _edit(target) {
2329
+ const c = this.controller;
2330
+ const id = target.dataset.s, f = target.dataset.f, i = target.dataset.i === void 0 ? void 0 : Number(target.dataset.i);
2331
+ if (!c || !id || !f) return;
2332
+ const value = target.type === "checkbox" ? target.checked : target.value;
2333
+ if (id === "dialer" && target.type === "radio" && !target.checked) return;
2334
+ c.edit(id, (d, def) => {
2335
+ if (id === "handoff" && i !== void 0) def.setStep(d, i, f, value);
2336
+ else if (id === "approvals" && i !== void 0) {
2337
+ if (f === "cond") def.toggleCondition(d, i, value);
2338
+ else if (f.startsWith("when.")) def.setCondition(d, i, f.slice(5), value);
2339
+ else def.setRule(d, i, f, value);
2340
+ } else d[f] = value;
2341
+ });
2342
+ }
2343
+ onInput(target) {
2344
+ if (target.type !== "checkbox" && target.type !== "radio" && target.tagName !== "SELECT") this._edit(target);
2345
+ }
2346
+ onChange(target) {
2347
+ if (target.type === "checkbox" || target.type === "radio" || target.tagName === "SELECT") this._edit(target);
2348
+ }
2349
+ };
2350
+ define("traitos-settings", TraitOSSettings);
2351
+
2352
+ // src/core/flowModel.js
2353
+ var TARGET_TYPES = ["agent", "team_member", "department", "external"];
2354
+ var TARGET_LABEL = { agent: "AI agent", team_member: "Team member", department: "Department", external: "Phone number" };
2355
+ var DIGITS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"];
2356
+ var DAYS = [{ n: 0, label: "Sun" }, { n: 1, label: "Mon" }, { n: 2, label: "Tue" }, { n: 3, label: "Wed" }, { n: 4, label: "Thu" }, { n: 5, label: "Fri" }, { n: 6, label: "Sat" }];
2357
+ var emptyFlow = () => ({
2358
+ greeting: "Thanks for calling.",
2359
+ menu: { prompt: "For sales press 1. For support press 2.", timeoutSec: 6, maxDigits: 1, routes: {}, fallbackAgentId: null },
2360
+ spam: { rateLimitPer10Min: 5, press1ScreenUnverified: false },
2361
+ hours: { enabled: false, timezone: "UTC", openHour: 9, closeHour: 17, days: [1, 2, 3, 4, 5], afterHoursAction: "voicemail", afterHoursAgentId: null, voicemailPrompt: "" }
2362
+ });
2363
+ var copy = (f) => JSON.parse(JSON.stringify(f));
2364
+ var edit = (flow, fn) => {
2365
+ const f = copy(flow);
2366
+ fn(f);
2367
+ return f;
2368
+ };
2369
+ function normalizeFlow(flow) {
2370
+ var _a2, _b, _c, _d, _e;
2371
+ const base = emptyFlow();
2372
+ const f = flow != null ? flow : {};
2373
+ return { ...base, ...f, menu: { ...base.menu, ...(_a2 = f.menu) != null ? _a2 : {}, routes: { ...(_c = (_b = f.menu) == null ? void 0 : _b.routes) != null ? _c : {} } }, spam: { ...base.spam, ...(_d = f.spam) != null ? _d : {} }, hours: { ...base.hours, ...(_e = f.hours) != null ? _e : {} } };
2374
+ }
2375
+ var setGreeting = (flow, greeting) => edit(flow, (f) => {
2376
+ f.greeting = greeting;
2377
+ });
2378
+ var setMenu = (flow, patch) => edit(flow, (f) => {
2379
+ Object.assign(f.menu, patch);
2380
+ });
2381
+ var setSpam = (flow, patch) => edit(flow, (f) => {
2382
+ Object.assign(f.spam, patch);
2383
+ });
2384
+ var setHours = (flow, patch) => edit(flow, (f) => {
2385
+ Object.assign(f.hours, patch);
2386
+ });
2387
+ var nextFreeDigit = (flow) => {
2388
+ var _a2;
2389
+ return (_a2 = DIGITS.find((d) => !(d in flow.menu.routes))) != null ? _a2 : null;
2390
+ };
2391
+ function addRoute(flow, digit) {
2392
+ const d = digit != null ? digit : nextFreeDigit(flow);
2393
+ if (!d || d in flow.menu.routes) return flow;
2394
+ return edit(flow, (f) => {
2395
+ f.menu.routes[d] = { extension: d, label: "", targetType: "agent", targetAgentId: null, ringTimeoutSec: 20, enabled: true };
2396
+ });
2397
+ }
2398
+ var removeRoute = (flow, digit) => edit(flow, (f) => {
2399
+ delete f.menu.routes[digit];
2400
+ });
2401
+ function setRoute(flow, digit, patch) {
2402
+ if (!(digit in flow.menu.routes)) return flow;
2403
+ return edit(flow, (f) => {
2404
+ const r = Object.assign(f.menu.routes[digit], patch);
2405
+ if (patch.targetType) {
2406
+ if (r.targetType !== "agent") r.targetAgentId = null;
2407
+ if (r.targetType !== "team_member") r.teamMemberId = null;
2408
+ if (r.targetType !== "department") r.departmentTargets = null;
2409
+ if (r.targetType !== "external") r.externalNumber = null;
2410
+ }
2411
+ });
2412
+ }
2413
+ function moveRoute(flow, from, to) {
2414
+ if (from === to || !(from in flow.menu.routes) || to in flow.menu.routes) return flow;
2415
+ return edit(flow, (f) => {
2416
+ const r = f.menu.routes[from];
2417
+ delete f.menu.routes[from];
2418
+ r.extension = to;
2419
+ f.menu.routes[to] = r;
2420
+ });
2421
+ }
2422
+ var toggleDay = (flow, n) => edit(flow, (f) => {
2423
+ const s = new Set(f.hours.days);
2424
+ s.has(n) ? s.delete(n) : s.add(n);
2425
+ f.hours.days = [...s].sort();
2426
+ });
2427
+ function validateFlow(flow) {
2428
+ var _a2, _b, _c, _d, _e, _f, _g, _h, _i;
2429
+ const e = {};
2430
+ if (!String((_a2 = flow.greeting) != null ? _a2 : "").trim()) e.greeting = "Say something when the call connects.";
2431
+ if (!String((_c = (_b = flow.menu) == null ? void 0 : _b.prompt) != null ? _c : "").trim()) e["menu.prompt"] = "Tell callers what each number does.";
2432
+ const t2 = Number((_d = flow.menu) == null ? void 0 : _d.timeoutSec);
2433
+ if (!(t2 >= 1 && t2 <= 30)) e["menu.timeoutSec"] = "Wait between 1 and 30 seconds.";
2434
+ for (const [d, r] of Object.entries((_f = (_e = flow.menu) == null ? void 0 : _e.routes) != null ? _f : {})) {
2435
+ if (!String((_g = r.label) != null ? _g : "").trim()) e[`routes.${d}.label`] = "Give this choice a name.";
2436
+ if (r.targetType === "agent" && !r.targetAgentId) e[`routes.${d}.target`] = "Choose an AI agent.";
2437
+ else if (r.targetType === "team_member" && !r.teamMemberId) e[`routes.${d}.target`] = "Choose a team member.";
2438
+ else if (r.targetType === "department" && !((_h = r.departmentTargets) == null ? void 0 : _h.length)) e[`routes.${d}.target`] = "Choose at least one person in the department.";
2439
+ else if (r.targetType === "external" && !isE164(r.externalNumber)) e[`routes.${d}.target`] = "Use + then country code and number.";
2440
+ else if (!TARGET_TYPES.includes(r.targetType)) e[`routes.${d}.target`] = "Choose who answers.";
2441
+ }
2442
+ const h = flow.hours;
2443
+ if (h == null ? void 0 : h.enabled) {
2444
+ if (!(Number.isInteger(+h.openHour) && +h.openHour >= 0 && +h.openHour <= 23)) e["hours.openHour"] = "Opening hour is 0 to 23.";
2445
+ if (!(Number.isInteger(+h.closeHour) && +h.closeHour >= 1 && +h.closeHour <= 24)) e["hours.closeHour"] = "Closing hour is 1 to 24.";
2446
+ else if (+h.closeHour <= +h.openHour) e["hours.closeHour"] = "Closing time must be after opening time.";
2447
+ if (!((_i = h.days) == null ? void 0 : _i.length)) e["hours.days"] = "Pick at least one open day.";
2448
+ if (h.afterHoursAction === "agent" && !h.afterHoursAgentId) e["hours.afterHoursAgentId"] = "Choose who answers after hours.";
2449
+ }
2450
+ return e;
2451
+ }
2452
+ function describeFlow(flow, lookup = {}) {
2453
+ var _a2;
2454
+ const name = (list, id) => {
2455
+ var _a3, _b, _c;
2456
+ return (_c = (_b = (_a3 = (list != null ? list : []).find((x) => x.id === id)) == null ? void 0 : _a3.name) != null ? _b : id) != null ? _c : "?";
2457
+ };
2458
+ const routes = Object.entries(flow.menu.routes).sort(([a], [b]) => DIGITS.indexOf(a) - DIGITS.indexOf(b)).map(([digit, r]) => {
2459
+ var _a3, _b;
2460
+ return {
2461
+ digit,
2462
+ label: r.label || "(unnamed)",
2463
+ kind: r.targetType,
2464
+ target: r.targetType === "agent" ? name(lookup.agents, r.targetAgentId) : r.targetType === "team_member" ? name(lookup.team, r.teamMemberId) : r.targetType === "department" ? `${(_b = (_a3 = r.departmentTargets) == null ? void 0 : _a3.length) != null ? _b : 0} people` : r.externalNumber || "?"
2465
+ };
2466
+ });
2467
+ return {
2468
+ steps: [{ kind: "caller", text: "Caller dials" }, ...((_a2 = flow.hours) == null ? void 0 : _a2.enabled) ? [{ kind: "hours", text: `Open ${flow.hours.openHour}:00 to ${flow.hours.closeHour}:00; after hours: ${flow.hours.afterHoursAction === "agent" ? name(lookup.agents, flow.hours.afterHoursAgentId) : "voicemail"}` }] : [], { kind: "greeting", text: flow.greeting }, { kind: "menu", text: flow.menu.prompt }],
2469
+ routes,
2470
+ fallback: flow.menu.fallbackAgentId ? name(lookup.agents, flow.menu.fallbackAgentId) : null
2471
+ };
2472
+ }
2473
+
2474
+ // src/core/flowBuilderController.js
2475
+ var FlowBuilderController = class {
2476
+ constructor({ client, phoneNumberId, agents: agents2 = [], team = [] }) {
2477
+ this.client = client;
2478
+ this.phoneNumberId = phoneNumberId;
2479
+ this.lookup = { agents: agents2, team };
2480
+ this._listeners = /* @__PURE__ */ new Set();
2481
+ this._history = [];
2482
+ this._future = [];
2483
+ this.state = { status: "idle", flow: emptyFlow(), saved: null, enabled: true, localErrors: {}, serverCheck: null, simulation: null, message: null, dirty: false, busy: false };
2484
+ }
2485
+ snapshot() {
2486
+ return { ...this.state, canUndo: this._history.length > 0, canRedo: this._future.length > 0 };
2487
+ }
2488
+ subscribe(fn) {
2489
+ this._listeners.add(fn);
2490
+ return () => this._listeners.delete(fn);
2491
+ }
2492
+ _set(patch) {
2493
+ this.state = { ...this.state, ...patch };
2494
+ for (const fn of [...this._listeners]) {
2495
+ try {
2496
+ fn(this.snapshot());
2497
+ } catch {
2498
+ }
2499
+ }
2500
+ }
2501
+ async load() {
2502
+ this._set({ status: "loading", message: null });
2503
+ try {
2504
+ const res = await this.client.phoneNumbers.flow.get(this.phoneNumberId);
2505
+ const flow = normalizeFlow(res.flow);
2506
+ this._history = [];
2507
+ this._future = [];
2508
+ this._set({ status: "ready", flow, saved: res.flow ? flow : null, enabled: res.enabled !== false, localErrors: validateFlow(flow), dirty: false, serverCheck: null, simulation: null });
2509
+ } catch (error) {
2510
+ this._set({ status: "error", message: (error == null ? void 0 : error.message) || "Could not load this flow." });
2511
+ }
2512
+ }
2513
+ /** Apply an edit function from flowModel (e.g. `(f) => addRoute(f)`). Keeps undo history. */
2514
+ apply(fn) {
2515
+ const next = fn(this.state.flow);
2516
+ if (!next || next === this.state.flow) return;
2517
+ this._history.push(this.state.flow);
2518
+ if (this._history.length > 100) this._history.shift();
2519
+ this._future = [];
2520
+ this._commit(next);
2521
+ }
2522
+ undo() {
2523
+ if (this._history.length) {
2524
+ this._future.push(this.state.flow);
2525
+ this._commit(this._history.pop());
2526
+ }
2527
+ }
2528
+ redo() {
2529
+ if (this._future.length) {
2530
+ this._history.push(this.state.flow);
2531
+ this._commit(this._future.pop());
2532
+ }
2533
+ }
2534
+ _commit(flow) {
2535
+ this._set({ flow, localErrors: validateFlow(flow), dirty: JSON.stringify(flow) !== JSON.stringify(this.state.saved), serverCheck: null, message: null });
2536
+ }
2537
+ setEnabled(enabled) {
2538
+ this._set({ enabled, dirty: true });
2539
+ }
2540
+ /** Ask the server to check the flow. Resolves `{ valid, error? }`; never saves. */
2541
+ async check() {
2542
+ this._set({ busy: true });
2543
+ try {
2544
+ const r = await this.client.flows.validate(this.state.flow);
2545
+ this._set({ serverCheck: r, busy: false });
2546
+ return r;
2547
+ } catch (error) {
2548
+ this._set({ busy: false, message: (error == null ? void 0 : error.message) || "Could not check the flow." });
2549
+ return { valid: false, error: error == null ? void 0 : error.message };
2550
+ }
2551
+ }
2552
+ /** Dry-run a call through the flow at no phone cost. @param {{digits?: string, callerNumber?: string, scenario?: string}} options */
2553
+ async simulate(options = {}) {
2554
+ this._set({ busy: true, simulation: null });
2555
+ try {
2556
+ const simulation = await this.client.flows.simulate(this.state.flow, { ...options, phoneNumber: this.phoneNumberId });
2557
+ this._set({ simulation, busy: false });
2558
+ return simulation;
2559
+ } catch (error) {
2560
+ this._set({ busy: false, message: (error == null ? void 0 : error.message) || "Could not run the simulation." });
2561
+ return null;
2562
+ }
2563
+ }
2564
+ /** Describe the flow in plain English. The draft replaces the current flow (undoable); nothing is saved. */
2565
+ async generate(prompt) {
2566
+ var _a2;
2567
+ if (!String(prompt != null ? prompt : "").trim()) return false;
2568
+ this._set({ busy: true, message: null });
2569
+ try {
2570
+ const res = await this.client.flows.generate(prompt, { currentFlow: this.state.flow, agents: this.lookup.agents.map(({ id, name }) => ({ id, name })) });
2571
+ const draft = (_a2 = res.flow) != null ? _a2 : res.draft;
2572
+ if (!draft) {
2573
+ this._set({ busy: false, message: "No draft came back. Try describing it differently." });
2574
+ return false;
2575
+ }
2576
+ this._set({ busy: false });
2577
+ this.apply(() => normalizeFlow(draft));
2578
+ return true;
2579
+ } catch (error) {
2580
+ this._set({ busy: false, message: (error == null ? void 0 : error.message) || "Could not draft a flow." });
2581
+ return false;
2582
+ }
2583
+ }
2584
+ /** Check locally, then save. Saving changes live call handling. Resolves true when saved. */
2585
+ async save() {
2586
+ var _a2;
2587
+ const errors = validateFlow(this.state.flow);
2588
+ if (Object.keys(errors).length) {
2589
+ this._set({ localErrors: errors, message: "Fix the highlighted fields first." });
2590
+ return false;
2591
+ }
2592
+ this._set({ busy: true, message: null });
2593
+ try {
2594
+ const res = await this.client.phoneNumbers.flow.save(this.phoneNumberId, this.state.flow, { enabled: this.state.enabled });
2595
+ const flow = normalizeFlow((_a2 = res == null ? void 0 : res.flow) != null ? _a2 : this.state.flow);
2596
+ this._history = [];
2597
+ this._future = [];
2598
+ this._set({ busy: false, flow, saved: flow, dirty: false, message: "Saved. New calls use this flow.", serverCheck: null });
2599
+ return true;
2600
+ } catch (error) {
2601
+ this._set({ busy: false, message: (error == null ? void 0 : error.message) || "Could not save the flow." });
2602
+ return false;
2603
+ }
2604
+ }
2605
+ };
2606
+
2607
+ // src/elements/flowBuilder.js
2608
+ var css4 = `
2609
+ .grid { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 16px; } @media (max-width: 760px) { .grid { grid-template-columns: 1fr; } }
2610
+ .route { border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 8px 10px; margin: 8px 0; } .digit { font-weight: 700; font-size: 18px; width: 2ch; }
2611
+ .toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; } .linkish { background: none; border: 0; color: var(--_accent); padding: 2px 4px; }
2612
+ .map { list-style: none; margin: 0; padding: 0; } .map > li { border-left: 3px solid var(--_accent); padding: 4px 10px; margin: 0 0 8px 6px; background: color-mix(in srgb, var(--_accent) 5%, transparent); }
2613
+ .map ul { margin: 4px 0 0; padding-left: 16px; } .days label { display: inline-block; margin: 0 8px 0 0; font-weight: 400; }
2614
+ `;
2615
+ var err2 = (errors, path) => errors[path] ? html`<p class="err" role="alert">${errors[path]}</p>` : "";
2616
+ var bad2 = (errors, path) => raw(errors[path] ? 'aria-invalid="true"' : "");
2617
+ var opts = (list, value, blank) => html`${blank ? html`<option value="">${blank}</option>` : ""}${list.map((x) => html`<option value="${x.id}" ${x.id === value ? "selected" : ""}>${x.name}</option>`)}`;
2618
+ function renderRoute(d, r, e, lookup) {
2619
+ var _a2;
2620
+ const k = `routes.${d}`;
2621
+ const target = r.targetType === "agent" ? html`<select aria-label="AI agent" data-key="${k}.agent" data-d="${d}" data-f="targetAgentId" ${bad2(e, `${k}.target`)}>${opts(lookup.agents, r.targetAgentId, "Choose an agent")}</select>` : r.targetType === "team_member" ? html`<select aria-label="Team member" data-key="${k}.member" data-d="${d}" data-f="teamMemberId" ${bad2(e, `${k}.target`)}>${opts(lookup.team, r.teamMemberId, "Choose a person")}</select>` : r.targetType === "department" ? html`<div role="group" aria-label="People in this department">${lookup.team.map((m) => {
2622
+ var _a3;
2623
+ return html`<label style="font-weight:400"><input type="checkbox" data-action="dept-toggle" data-d="${d}" data-id="${m.id}" ${((_a3 = r.departmentTargets) != null ? _a3 : []).includes(m.id) ? "checked" : ""} />${m.name}</label>`;
2624
+ })}</div>` : html`<input aria-label="Phone number" type="tel" data-key="${k}.number" data-d="${d}" data-f="externalNumber" value="${(_a2 = r.externalNumber) != null ? _a2 : ""}" placeholder="+18765550100" ${bad2(e, `${k}.target`)} />`;
2625
+ return html`<div class="route"><div class="row">
2626
+ <div class="fixed digit" aria-label="Press ${d}">${d}</div>
2627
+ <div><label for="l-${d}">Name</label><input id="l-${d}" data-key="${k}.label" data-d="${d}" data-f="label" value="${r.label}" placeholder="Sales" ${bad2(e, `${k}.label`)} />${err2(e, `${k}.label`)}</div>
2628
+ <div><label for="t-${d}">Who answers</label><select id="t-${d}" data-key="${k}.type" data-d="${d}" data-f="targetType">${TARGET_TYPES.map((t2) => html`<option value="${t2}" ${t2 === r.targetType ? "selected" : ""}>${TARGET_LABEL[t2]}</option>`)}</select></div>
2629
+ <div class="fixed"><button type="button" class="linkish" data-action="route-remove" data-d="${d}" aria-label="Remove choice ${d}">Remove</button></div>
2630
+ </div><div style="margin-top:6px">${target}${err2(e, `${k}.target`)}</div></div>`;
2631
+ }
2632
+ function renderMap(flow, lookup) {
2633
+ const m = describeFlow(flow, lookup);
2634
+ return html`<ol class="map" aria-label="How a call flows">${m.steps.map((s) => html`<li><b>${s.kind === "caller" ? "\u260E" : s.kind === "hours" ? "\u{1F558}" : s.kind === "greeting" ? "\u{1F4AC}" : "\u{1F522}"}</b> ${s.text}</li>`)}
2635
+ <li>Caller presses a number<ul>${m.routes.length ? m.routes.map((r) => html`<li><b>${r.digit}</b> ${r.label} → ${r.target}</li>`) : html`<li>No choices yet</li>`}${m.fallback ? html`<li>No answer → ${m.fallback}</li>` : ""}</ul></li></ol>`;
2636
+ }
2637
+ function renderFlowBuilder(s, lookup = { agents: [], team: [] }, { prompt = "" } = {}) {
2638
+ var _a2;
2639
+ if (s.status === "loading" || s.status === "idle") return html`<div class="card"><p class="hint" role="status">Loading…</p></div>`.toString();
2640
+ if (s.status === "error") return html`<div class="card"><p class="err" role="alert">${s.message}</p><button data-action="reload">Try again</button></div>`.toString();
2641
+ const f = s.flow, e = s.localErrors, h = f.hours;
2642
+ const sim = s.simulation;
2643
+ return html`<div class="card">
2644
+ <div class="toolbar" role="toolbar" aria-label="Flow actions">
2645
+ <button data-action="undo" ${s.canUndo ? "" : "disabled"}>Undo</button><button data-action="redo" ${s.canRedo ? "" : "disabled"}>Redo</button>
2646
+ <button data-action="check" ${s.busy ? "disabled" : ""}>Check with server</button><button data-action="simulate" ${s.busy ? "disabled" : ""}>Try a call</button>
2647
+ <button class="primary" data-action="save" ${!s.dirty || s.busy ? "disabled" : ""}>${s.busy ? "Working\u2026" : "Save"}</button>
2648
+ </div>
2649
+ ${s.message ? html`<p class="status ${s.message.startsWith("Saved") ? "ok" : "bad"}" role="status">${s.message}</p>` : ""}
2650
+ ${s.serverCheck ? html`<p class="status ${s.serverCheck.valid ? "ok" : "bad"}" role="status">${s.serverCheck.valid ? "The server accepts this flow." : `The server found a problem: ${(_a2 = s.serverCheck.error) != null ? _a2 : "invalid flow"}`}</p>` : ""}
2651
+ <div class="grid"><div>
2652
+ <label for="draft">Describe it in words</label><div class="row"><input id="draft" data-key="draft" value="${prompt}" placeholder="Press 1 for sales, 2 for support; closed on Sundays" /><button class="fixed" data-action="generate" ${s.busy ? "disabled" : ""}>Draft it</button></div>
2653
+ <label for="greeting">Greeting</label><textarea id="greeting" rows="2" data-key="greeting" data-f="greeting" ${bad2(e, "greeting")}>${f.greeting}</textarea>${err2(e, "greeting")}
2654
+ <label for="prompt">Menu prompt</label><textarea id="prompt" rows="2" data-key="menu.prompt" data-f="menu.prompt" ${bad2(e, "menu.prompt")}>${f.menu.prompt}</textarea>${err2(e, "menu.prompt")}
2655
+ <div class="row"><div><label for="timeout">Wait for a key (seconds)</label><input id="timeout" type="number" min="1" max="30" data-key="menu.timeoutSec" data-f="menu.timeoutSec" value="${f.menu.timeoutSec}" ${bad2(e, "menu.timeoutSec")} />${err2(e, "menu.timeoutSec")}</div>
2656
+ <div><label for="fallback">If nobody answers</label><select id="fallback" data-key="menu.fallback" data-f="menu.fallbackAgentId">${opts(lookup.agents, f.menu.fallbackAgentId, "Hang up")}</select></div></div>
2657
+ <h3>Choices</h3>
2658
+ ${Object.entries(f.menu.routes).sort(([a], [b]) => DIGITS.indexOf(a) - DIGITS.indexOf(b)).map(([d, r]) => renderRoute(d, r, e, lookup))}
2659
+ <button data-action="route-add" ${DIGITS.every((d) => d in f.menu.routes) ? "disabled" : ""}>Add a choice</button>
2660
+ <h3>Opening hours</h3>
2661
+ <label style="font-weight:400"><input type="checkbox" data-key="hours.enabled" data-f="hours.enabled" ${h.enabled ? "checked" : ""} />Use opening hours</label>
2662
+ ${h.enabled ? html`<div class="row"><div><label for="open">Opens (hour)</label><input id="open" type="number" min="0" max="23" data-key="hours.openHour" data-f="hours.openHour" value="${h.openHour}" ${bad2(e, "hours.openHour")} />${err2(e, "hours.openHour")}</div>
2663
+ <div><label for="close">Closes (hour)</label><input id="close" type="number" min="1" max="24" data-key="hours.closeHour" data-f="hours.closeHour" value="${h.closeHour}" ${bad2(e, "hours.closeHour")} />${err2(e, "hours.closeHour")}</div>
2664
+ <div><label for="tz">Time zone</label><input id="tz" data-key="hours.timezone" data-f="hours.timezone" value="${h.timezone}" placeholder="America/Jamaica" /></div></div>
2665
+ <div class="days" role="group" aria-label="Open days">${DAYS.map((d) => html`<label><input type="checkbox" data-action="day-toggle" data-n="${d.n}" ${h.days.includes(d.n) ? "checked" : ""} />${d.label}</label>`)}</div>${err2(e, "hours.days")}
2666
+ <label for="after">After hours</label><select id="after" data-key="hours.after" data-f="hours.afterHoursAction"><option value="voicemail" ${h.afterHoursAction === "voicemail" ? "selected" : ""}>Take a voicemail</option><option value="agent" ${h.afterHoursAction === "agent" ? "selected" : ""}>Let an AI agent answer</option></select>
2667
+ ${h.afterHoursAction === "agent" ? html`<select aria-label="After-hours agent" data-key="hours.afterAgent" data-f="hours.afterHoursAgentId" ${bad2(e, "hours.afterHoursAgentId")}>${opts(lookup.agents, h.afterHoursAgentId, "Choose an agent")}</select>${err2(e, "hours.afterHoursAgentId")}` : ""}` : ""}
2668
+ <h3>Spam</h3>
2669
+ <div class="row"><div><label for="rate">Calls per number, per 10 minutes</label><input id="rate" type="number" min="1" data-key="spam.rate" data-f="spam.rateLimitPer10Min" value="${f.spam.rateLimitPer10Min}" /></div></div>
2670
+ <label style="font-weight:400"><input type="checkbox" data-key="spam.press1" data-f="spam.press1ScreenUnverified" ${f.spam.press1ScreenUnverified ? "checked" : ""} />Ask unverified callers to press 1 first</label>
2671
+ <label style="font-weight:400"><input type="checkbox" data-key="enabled" data-f="enabled" ${s.enabled ? "checked" : ""} />This flow answers calls</label>
2672
+ </div><div><h3>Call map</h3>${renderMap(f, lookup)}
2673
+ ${sim ? html`<h3>Test call</h3><pre style="white-space:pre-wrap;font-size:12.5px" aria-label="Simulation result">${JSON.stringify(sim, null, 2)}</pre>` : ""}
2674
+ </div></div></div>`.toString();
2675
+ }
2676
+ var TraitOSFlowBuilder = class extends TraitElement {
2677
+ static get observedAttributes() {
2678
+ return ["phone-number-id"];
2679
+ }
2680
+ get css() {
2681
+ return css4;
2682
+ }
2683
+ set client(v) {
2684
+ this._client = v;
2685
+ this._init();
2686
+ }
2687
+ get client() {
2688
+ return this._client;
2689
+ }
2690
+ set agents(v) {
2691
+ this._agents = v != null ? v : [];
2692
+ this._rebuild();
2693
+ }
2694
+ set team(v) {
2695
+ this._team = v != null ? v : [];
2696
+ this._rebuild();
2697
+ }
2698
+ mounted() {
2699
+ this._init();
2700
+ }
2701
+ unmounted() {
2702
+ var _a2;
2703
+ (_a2 = this._unsub) == null ? void 0 : _a2.call(this);
2704
+ this.controller = null;
2705
+ }
2706
+ attributeChangedCallback(n, o, v) {
2707
+ var _a2;
2708
+ if (o !== v && this.controller) {
2709
+ this.controller = null;
2710
+ (_a2 = this._unsub) == null ? void 0 : _a2.call(this);
2711
+ this._init();
2712
+ }
2713
+ }
2714
+ _rebuild() {
2715
+ var _a2, _b;
2716
+ if (this.controller) {
2717
+ this.controller.lookup = { agents: (_a2 = this._agents) != null ? _a2 : [], team: (_b = this._team) != null ? _b : [] };
2718
+ this.requestRender();
2719
+ }
2720
+ }
2721
+ _init() {
2722
+ var _a2, _b;
2723
+ const id = this.getAttribute("phone-number-id");
2724
+ if (this.controller || !this._connected || !this._client || !id) return;
2725
+ this.controller = new FlowBuilderController({ client: this._client, phoneNumberId: id, agents: (_a2 = this._agents) != null ? _a2 : [], team: (_b = this._team) != null ? _b : [] });
2726
+ this._unsub = this.controller.subscribe(() => this.requestRender());
2727
+ this.controller.load();
2728
+ this.requestRender();
2729
+ }
2730
+ render() {
2731
+ var _a2;
2732
+ if (!this.controller) return html`<div class="card"><p class="hint">Set the <code>client</code> property and a <code>phone-number-id</code> to edit a flow.</p></div>`.toString();
2733
+ return renderFlowBuilder(this.controller.snapshot(), this.controller.lookup, { prompt: (_a2 = this._prompt) != null ? _a2 : "" });
2734
+ }
2735
+ async onClick(action, node) {
2736
+ const c = this.controller;
2737
+ if (!c) return;
2738
+ const d = node.dataset.d;
2739
+ if (action === "save") {
2740
+ const ok = await c.save();
2741
+ this.emit(ok ? "traitos-saved" : "traitos-error", { phoneNumberId: c.phoneNumberId, message: c.state.message });
2742
+ } else if (action === "undo") c.undo();
2743
+ else if (action === "redo") c.redo();
2744
+ else if (action === "reload") c.load();
2745
+ else if (action === "check") c.check();
2746
+ else if (action === "simulate") c.simulate();
2747
+ else if (action === "generate") {
2748
+ if (await c.generate(this._prompt)) {
2749
+ this._prompt = "";
2750
+ }
2751
+ } else if (action === "route-add") c.apply((f) => addRoute(f));
2752
+ else if (action === "route-remove") c.apply((f) => removeRoute(f, d));
2753
+ else if (action === "day-toggle") c.apply((f) => toggleDay(f, Number(node.dataset.n)));
2754
+ else if (action === "dept-toggle") c.apply((f) => {
2755
+ var _a2, _b;
2756
+ const cur = (_b = (_a2 = f.menu.routes[d]) == null ? void 0 : _a2.departmentTargets) != null ? _b : [];
2757
+ const id = node.dataset.id;
2758
+ return setRoute(f, d, { departmentTargets: cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id] });
2759
+ });
2760
+ }
2761
+ _edit(t2) {
2762
+ const c = this.controller;
2763
+ const key = t2.dataset.key, f = t2.dataset.f;
2764
+ if (key === "draft") {
2765
+ this._prompt = t2.value;
2766
+ return;
2767
+ }
2768
+ if (!c || !f) return;
2769
+ const v = t2.type === "checkbox" ? t2.checked : t2.value;
2770
+ if (f === "enabled") return c.setEnabled(v);
2771
+ if (t2.dataset.d) return c.apply((flow) => setRoute(flow, t2.dataset.d, { [f]: v === "" && f.endsWith("Id") ? null : v }));
2772
+ const num = (x) => x === "" ? x : Number(x);
2773
+ const map = {
2774
+ greeting: () => setGreeting(c.state.flow, v),
2775
+ "menu.prompt": () => setMenu(c.state.flow, { prompt: v }),
2776
+ "menu.timeoutSec": () => setMenu(c.state.flow, { timeoutSec: num(v) }),
2777
+ "menu.fallbackAgentId": () => setMenu(c.state.flow, { fallbackAgentId: v || null }),
2778
+ "spam.rateLimitPer10Min": () => setSpam(c.state.flow, { rateLimitPer10Min: num(v) }),
2779
+ "spam.press1ScreenUnverified": () => setSpam(c.state.flow, { press1ScreenUnverified: v }),
2780
+ "hours.enabled": () => setHours(c.state.flow, { enabled: v }),
2781
+ "hours.openHour": () => setHours(c.state.flow, { openHour: num(v) }),
2782
+ "hours.closeHour": () => setHours(c.state.flow, { closeHour: num(v) }),
2783
+ "hours.timezone": () => setHours(c.state.flow, { timezone: v }),
2784
+ "hours.afterHoursAction": () => setHours(c.state.flow, { afterHoursAction: v }),
2785
+ "hours.afterHoursAgentId": () => setHours(c.state.flow, { afterHoursAgentId: v || null })
2786
+ };
2787
+ if (map[f]) c.apply(() => map[f]());
2788
+ }
2789
+ onInput(t2) {
2790
+ if (t2.type !== "checkbox" && t2.tagName !== "SELECT") this._edit(t2);
2791
+ }
2792
+ onChange(t2) {
2793
+ if (t2.type === "checkbox" || t2.tagName === "SELECT") this._edit(t2);
2794
+ }
2795
+ };
2796
+ define("traitos-flow-builder", TraitOSFlowBuilder);
2797
+
2798
+ // src/core/telnyxAdapter.js
2799
+ function telnyxAdapter(TelnyxRTC, { remoteElement } = {}) {
2800
+ let rtc = null;
2801
+ const handlers = { ready: [], error: [], close: [], call: [] };
2802
+ const emit = (name, arg) => handlers[name].forEach((fn) => fn(arg));
2803
+ const wrap = (call) => ({
2804
+ direction: call.direction,
2805
+ state: call.state,
2806
+ remoteCallerName: call.remoteCallerName,
2807
+ remoteCallerNumber: call.remoteCallerNumber,
2808
+ answer: () => call.answer(),
2809
+ hangup: () => call.hangup(),
2810
+ mute: (on) => on ? call.muteAudio() : call.unmuteAudio(),
2811
+ hold: (on) => on ? call.hold() : call.unhold(),
2812
+ dtmf: (digit) => call.dtmf(digit)
2813
+ });
2814
+ return {
2815
+ on(name, fn) {
2816
+ var _a2;
2817
+ (_a2 = handlers[name]) == null ? void 0 : _a2.push(fn);
2818
+ },
2819
+ async connect({ token }) {
2820
+ rtc = new TelnyxRTC({ login_token: token });
2821
+ if (remoteElement) rtc.remoteElement = remoteElement;
2822
+ rtc.on("telnyx.ready", () => emit("ready"));
2823
+ rtc.on("telnyx.error", (e) => emit("error", e instanceof Error ? e : new Error((e == null ? void 0 : e.message) || "Telnyx error")));
2824
+ rtc.on("telnyx.socket.close", () => emit("close"));
2825
+ rtc.on("telnyx.notification", (n) => {
2826
+ if ((n == null ? void 0 : n.type) === "callUpdate" && n.call) emit("call", wrap(n.call));
2827
+ });
2828
+ rtc.connect();
2829
+ },
2830
+ async disconnect() {
2831
+ rtc == null ? void 0 : rtc.disconnect();
2832
+ rtc = null;
2833
+ }
2834
+ };
2835
+ }
2836
+
2837
+ // src/core/tokenManager.js
2838
+ var TokenManager = class {
2839
+ /**
2840
+ * @param {{setToken: (t: string) => void}} client
2841
+ * @param {() => Promise<string | {token: string, expiresIn?: number, expiresAt?: string}>} provider
2842
+ * @param {{refreshAt?: number, minDelayMs?: number, retryMs?: number, onError?: (e: Error) => void, now?: () => number, timers?: {set: Function, clear: Function}}} [options]
2843
+ * `refreshAt` is the fraction of the lifetime after which to renew (default 0.8)
2844
+ */
2845
+ constructor(client, provider, { refreshAt = 0.8, minDelayMs = 5e3, retryMs = 5e3, onError, now = Date.now, timers } = {}) {
2846
+ this.client = client;
2847
+ this.provider = provider;
2848
+ this.refreshAt = refreshAt;
2849
+ this.minDelayMs = minDelayMs;
2850
+ this.retryMs = retryMs;
2851
+ this.onError = onError;
2852
+ this.now = now;
2853
+ this.timers = timers != null ? timers : { set: (fn, ms) => setTimeout(fn, ms), clear: (t2) => clearTimeout(t2) };
2854
+ this._timer = null;
2855
+ this._stopped = false;
2856
+ this.expiresAt = null;
2857
+ }
2858
+ /** Fetch the first token (rejects if it fails: do not show the UI without one), then keep renewing. */
2859
+ async start() {
2860
+ this._stopped = false;
2861
+ await this.refresh();
2862
+ }
2863
+ async refresh() {
2864
+ const out = await this.provider();
2865
+ const token = typeof out === "string" ? out : out == null ? void 0 : out.token;
2866
+ if (!token) throw new Error("The token provider did not return a token.");
2867
+ this.client.setToken(token);
2868
+ const ttlMs = typeof out === "object" && out ? Number.isFinite(out.expiresIn) ? out.expiresIn * 1e3 : out.expiresAt ? Date.parse(out.expiresAt) - this.now() : null : null;
2869
+ this.expiresAt = ttlMs ? this.now() + ttlMs : null;
2870
+ if (ttlMs && !this._stopped) this._schedule(Math.max(this.minDelayMs, ttlMs * this.refreshAt));
2871
+ return token;
2872
+ }
2873
+ _schedule(ms) {
2874
+ if (this._timer) this.timers.clear(this._timer);
2875
+ this._timer = this.timers.set(async () => {
2876
+ var _a2;
2877
+ this._timer = null;
2878
+ if (this._stopped) return;
2879
+ try {
2880
+ await this.refresh();
2881
+ } catch (error) {
2882
+ (_a2 = this.onError) == null ? void 0 : _a2.call(this, error);
2883
+ if (!this._stopped) this._schedule(this.retryMs);
2884
+ }
2885
+ }, ms);
2886
+ }
2887
+ stop() {
2888
+ this._stopped = true;
2889
+ if (this._timer) this.timers.clear(this._timer);
2890
+ this._timer = null;
2891
+ }
2892
+ };
2893
+
2894
+ // src/index.js
2895
+ function defineAll() {
2896
+ }
2897
+
2898
+ // ../sdk/src/index.js
2899
+ var src_exports = {};
2900
+ __export(src_exports, {
2901
+ AuthenticationError: () => AuthenticationError,
2902
+ CallSession: () => CallSession,
2903
+ ConflictError: () => ConflictError,
2904
+ ConnectionError: () => ConnectionError,
2905
+ HybridAgent: () => HybridAgent,
2906
+ NotFoundError: () => NotFoundError,
2907
+ PermissionError: () => PermissionError,
2908
+ RateLimitError: () => RateLimitError,
2909
+ ServerError: () => ServerError,
2910
+ SseParser: () => SseParser,
2911
+ TraitOSClient: () => TraitOSClient,
2912
+ TraitOSError: () => TraitOSError,
2913
+ ValidationError: () => ValidationError,
2914
+ WebhookSignatureError: () => WebhookSignatureError,
2915
+ constructWebhookEvent: () => constructWebhookEvent,
2916
+ errorClassFor: () => errorClassFor,
2917
+ mapServerStatus: () => mapServerStatus,
2918
+ normalizeBaseUrl: () => normalizeBaseUrl,
2919
+ paginate: () => paginate,
2920
+ safeCalculate: () => safeCalculate,
2921
+ signWebhook: () => signWebhook,
2922
+ verifyWebhook: () => verifyWebhook
2923
+ });
2924
+
2925
+ // ../sdk/src/baseUrl.js
2926
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
2927
+ function normalizeBaseUrl(baseUrl, { allowInsecureHttp = false } = {}) {
2928
+ let u;
2929
+ try {
2930
+ u = new URL(String(baseUrl));
2931
+ } catch {
2932
+ throw new Error(`Invalid baseUrl: ${JSON.stringify(String(baseUrl).slice(0, 80))}`);
2933
+ }
2934
+ if (u.username || u.password) throw new Error("baseUrl must not contain a user name or password. Pass the token separately.");
2935
+ const loopback = LOOPBACK_HOSTS.has(u.hostname) || u.hostname.endsWith(".localhost") || /^127\./.test(u.hostname);
2936
+ if (u.protocol === "http:") {
2937
+ if (!loopback && !allowInsecureHttp) throw new Error(`Refusing to send credentials over plain http to ${u.host}. Use https, or pass allowInsecureHttp: true on a trusted network.`);
2938
+ } else if (u.protocol !== "https:") {
2939
+ throw new Error(`baseUrl must start with https:// (got ${u.protocol})`);
2940
+ }
2941
+ return `${u.origin}${u.pathname}`.replace(/\/+$/, "");
2942
+ }
2943
+
2944
+ // ../sdk/src/errors.js
2945
+ var TraitOSError = class extends Error {
2946
+ /**
2947
+ * @param {string} message
2948
+ * @param {{status?: number, code?: string|null, body?: any, retryAfter?: number|null, requestId?: string|null}} [details]
2949
+ */
2950
+ constructor(message, { status, code = null, body, retryAfter = null, requestId = null } = {}) {
2951
+ super(message);
2952
+ this.name = new.target.name;
2953
+ this.status = status;
2954
+ this.code = code;
2955
+ this.body = body;
2956
+ this.retryAfter = retryAfter;
2957
+ this.requestId = requestId;
2958
+ }
2959
+ };
2960
+ var AuthenticationError = class extends TraitOSError {
2961
+ };
2962
+ var PermissionError = class extends TraitOSError {
2963
+ };
2964
+ var NotFoundError = class extends TraitOSError {
2965
+ };
2966
+ var ConflictError = class extends TraitOSError {
2967
+ };
2968
+ var ValidationError = class extends TraitOSError {
2969
+ };
2970
+ var RateLimitError = class extends TraitOSError {
2971
+ };
2972
+ var ServerError = class extends TraitOSError {
2973
+ };
2974
+ var ConnectionError = class extends TraitOSError {
2975
+ };
2976
+ var WebhookSignatureError = class extends TraitOSError {
2977
+ };
2978
+ function errorClassFor(status) {
2979
+ if (status === 401) return AuthenticationError;
2980
+ if (status === 403) return PermissionError;
2981
+ if (status === 404) return NotFoundError;
2982
+ if (status === 409) return ConflictError;
2983
+ if (status === 400 || status === 422) return ValidationError;
2984
+ if (status === 429) return RateLimitError;
2985
+ if (status >= 500) return ServerError;
2986
+ return TraitOSError;
2987
+ }
2988
+
2989
+ // ../sdk/src/http.js
2990
+ var RETRY_STATUS = /* @__PURE__ */ new Set([429, 502, 503, 504]);
2991
+ var SAFE_TO_REPEAT = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
2992
+ var MAX_BACKOFF_MS = 8e3;
2993
+ var defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
2994
+ function parseRetryAfter(value, now = Date.now()) {
2995
+ if (value === void 0 || value === null || value === "") return null;
2996
+ const n = Number(value);
2997
+ if (Number.isFinite(n)) return Math.max(0, n);
2998
+ const t2 = Date.parse(value);
2999
+ return Number.isFinite(t2) ? Math.max(0, (t2 - now) / 1e3) : null;
3000
+ }
3001
+ function backoffMs(attempt, retryAfterSecs = null, random = Math.random) {
3002
+ if (retryAfterSecs !== null) return Math.min(retryAfterSecs * 1e3, 3e4);
3003
+ const base = Math.min(MAX_BACKOFF_MS, 500 * 2 ** attempt);
3004
+ return Math.round(base / 2 + random() * (base / 2));
3005
+ }
3006
+ function createTransport(cfg) {
3007
+ var _a2;
3008
+ const sleep = (_a2 = cfg.sleep) != null ? _a2 : defaultSleep;
3009
+ const buildHeaders = (options) => {
3010
+ const isForm = typeof FormData !== "undefined" && options.body instanceof FormData;
3011
+ const token = cfg.getToken();
3012
+ return {
3013
+ ...isForm ? {} : { "Content-Type": "application/json" },
3014
+ ...token ? { Authorization: `Bearer ${token}` } : {},
3015
+ ...cfg.headers,
3016
+ ...options.headers
3017
+ };
3018
+ };
3019
+ async function raw3(path, options = {}) {
3020
+ var _a3, _b;
3021
+ const headers = { Accept: "text/event-stream", ...buildHeaders({ ...options, body: void 0 }), ...options.headers };
3022
+ delete headers["Content-Type"];
3023
+ let response;
3024
+ try {
3025
+ response = await fetch(`${cfg.baseUrl}${cfg.apiPath}${path}`, { ...options, headers });
3026
+ } catch (cause) {
3027
+ if ((cause == null ? void 0 : cause.name) === "AbortError") throw cause;
3028
+ throw new ConnectionError((cause == null ? void 0 : cause.message) || "Network error", { code: "network_error" });
3029
+ }
3030
+ if (!response.ok) {
3031
+ const body = await response.json().catch(() => ({ error: "Request failed" }));
3032
+ const Err = errorClassFor(response.status);
3033
+ throw new Err(body.message || body.error || `HTTP error! status: ${response.status}`, {
3034
+ status: response.status,
3035
+ code: typeof body.error === "string" && /^[a-z][a-z0-9_]*$/.test(body.error) ? body.error : null,
3036
+ body,
3037
+ retryAfter: parseRetryAfter((_b = (_a3 = response.headers) == null ? void 0 : _a3.get) == null ? void 0 : _b.call(_a3, "retry-after"))
3038
+ });
3039
+ }
3040
+ return response;
3041
+ }
3042
+ async function request(path, options = {}) {
3043
+ var _a3, _b, _c, _d, _e, _f, _g;
3044
+ const method = String((_a3 = options.method) != null ? _a3 : "GET").toUpperCase();
3045
+ const headers = buildHeaders(options);
3046
+ const url = `${cfg.baseUrl}${cfg.apiPath}${path}`;
3047
+ const { retries, ...init } = options;
3048
+ const maxRetries = retries != null ? retries : cfg.maxRetries;
3049
+ for (let attempt = 0; ; attempt++) {
3050
+ let response;
3051
+ try {
3052
+ response = await fetch(url, { signal: AbortSignal.timeout(cfg.timeoutMs), ...init, headers });
3053
+ } catch (cause) {
3054
+ const canRetry = attempt < maxRetries && SAFE_TO_REPEAT.has(method) && !((_b = init.signal) == null ? void 0 : _b.aborted);
3055
+ if (canRetry) {
3056
+ await sleep(backoffMs(attempt));
3057
+ continue;
3058
+ }
3059
+ const timedOut = (cause == null ? void 0 : cause.name) === "TimeoutError";
3060
+ throw new ConnectionError(timedOut ? `Request timed out after ${cfg.timeoutMs}ms` : (cause == null ? void 0 : cause.message) || "Network error", { code: timedOut ? "timeout" : "network_error" });
3061
+ }
3062
+ if (response.ok) {
3063
+ if (response.status === 204) return null;
3064
+ return response.json();
3065
+ }
3066
+ const retryAfter = parseRetryAfter((_d = (_c = response.headers) == null ? void 0 : _c.get) == null ? void 0 : _d.call(_c, "retry-after"));
3067
+ const mayRetry = RETRY_STATUS.has(response.status) && attempt < maxRetries && (SAFE_TO_REPEAT.has(method) || response.status === 429);
3068
+ if (mayRetry) {
3069
+ await sleep(backoffMs(attempt, retryAfter));
3070
+ continue;
3071
+ }
3072
+ const body = await response.json().catch(() => ({ error: "Request failed" }));
3073
+ const Err = errorClassFor(response.status);
3074
+ throw new Err(body.message || body.error || `HTTP error! status: ${response.status}`, {
3075
+ status: response.status,
3076
+ code: typeof body.error === "string" && /^[a-z][a-z0-9_]*$/.test(body.error) ? body.error : null,
3077
+ body,
3078
+ retryAfter,
3079
+ requestId: (_g = (_f = (_e = response.headers) == null ? void 0 : _e.get) == null ? void 0 : _f.call(_e, "x-request-id")) != null ? _g : null
3080
+ });
3081
+ }
3082
+ }
3083
+ request.raw = raw3;
3084
+ return request;
3085
+ }
3086
+
3087
+ // ../sdk/src/util.js
3088
+ function qs(params = {}) {
3089
+ const p = new URLSearchParams();
3090
+ for (const [k, v] of Object.entries(params)) {
3091
+ if (v === void 0 || v === null || v === "") continue;
3092
+ p.set(k, Array.isArray(v) ? v.join(",") : String(v));
3093
+ }
3094
+ const s = p.toString();
3095
+ return s ? `?${s}` : "";
3096
+ }
3097
+ var enc = encodeURIComponent;
3098
+ var json2 = (method, body) => ({ method, body: JSON.stringify(body != null ? body : {}) });
3099
+
3100
+ // ../sdk/src/resources/auth.js
3101
+ function auth(client) {
3102
+ const request = (path, options) => client._request(path, options);
3103
+ const api = {
3104
+ /**
3105
+ * Log in with credentials and set token on the client
3106
+ * @param {string} email
3107
+ * @param {string} password
3108
+ */
3109
+ login: async (email, password) => {
3110
+ const data = await request("/auth/login", {
3111
+ method: "POST",
3112
+ body: JSON.stringify({ email, password })
3113
+ });
3114
+ if (data.token) {
3115
+ client.setToken(data.token);
3116
+ }
3117
+ return data;
3118
+ },
3119
+ /**
3120
+ * Register a new organization and user
3121
+ */
3122
+ register: async ({ email, password, organizationName, organizationId }) => {
3123
+ const data = await request("/auth/register", {
3124
+ method: "POST",
3125
+ body: JSON.stringify({ email, password, organizationName, organizationId })
3126
+ });
3127
+ if (data.token) {
3128
+ client.setToken(data.token);
3129
+ }
3130
+ return data;
3131
+ },
3132
+ /**
3133
+ * For a server that holds an API key: create a short-lived, narrowly scoped token to hand to ONE browser session
3134
+ * (a softphone, a settings page, a live feed). Never put the API key itself in a browser.
3135
+ * Scopes: `events` (read the live feed), `softphone` (take and place calls), `settings` (handoff routing, call flows,
3136
+ * approval rules, usage; needs an admin). Lifetime: 30 seconds to 15 minutes (default 10).
3137
+ * @param {{scopes: ('events'|'softphone'|'settings')[], ttlSeconds?: number}} options
3138
+ * @returns {Promise<{token: string, tokenType: 'Bearer', expiresIn: number, expiresAt: string, scopes: string[]}>}
3139
+ */
3140
+ createBrowserToken: ({ scopes, ttlSeconds }) => request("/auth/browser-tokens", json2("POST", { scopes, ...ttlSeconds ? { ttlSeconds } : {} }))
3141
+ };
3142
+ return api;
3143
+ }
3144
+
3145
+ // ../sdk/src/resources/agents.js
3146
+ function agents(client) {
3147
+ const request = (path, options) => client._request(path, options);
3148
+ const api = {
3149
+ /** List agents for organization */
3150
+ list: () => request("/agents"),
3151
+ /** Get detailed agent state */
3152
+ get: (id) => request(`/agents/${enc(id)}`),
3153
+ /** Create a new agent */
3154
+ create: (name, description, model = null, skills2 = []) => request("/agents", {
3155
+ method: "POST",
3156
+ body: JSON.stringify({ name, description, model, skills: skills2 })
3157
+ }),
3158
+ /** Configure/update an agent */
3159
+ configure: (id, { name, description, model, skills: skills2 } = {}) => request(`/agents/${enc(id)}/configure`, {
3160
+ method: "POST",
3161
+ body: JSON.stringify({ name, description, model, skills: skills2 })
3162
+ }),
3163
+ /** Delete an agent */
3164
+ delete: (id) => request(`/agents/${enc(id)}`, {
3165
+ method: "DELETE"
3166
+ }),
3167
+ /** Send a chat prompt to the agent */
3168
+ chat: (id, prompt, conversationId = "default", skillName = null) => request(`/agents/${enc(id)}/chat`, {
3169
+ method: "POST",
3170
+ body: JSON.stringify({ prompt, conversationId, skillName })
3171
+ }),
3172
+ /** Assign skills to an agent */
3173
+ updateSkills: (id, skills2 = []) => request(`/agents/${enc(id)}/skills`, {
3174
+ method: "POST",
3175
+ body: JSON.stringify({ skills: skills2 })
3176
+ }),
3177
+ /** Get the agent's model routing (primary, fast, fallback, tiers). */
3178
+ getModelSettings: (id) => request(`/agents/${enc(id)}/model-settings`),
3179
+ /**
3180
+ * Update the agent's model routing (partial). Org admin.
3181
+ * @param {string} id
3182
+ * @param {{primary?: string|null, fast?: string|null, fallback?: string[], tiers?: object, usePlatformKey?: boolean}} settings
3183
+ */
3184
+ setModelSettings: (id, settings) => request(`/agents/${enc(id)}/model-settings`, json2("PUT", settings)),
3185
+ /**
3186
+ * How an agent hands a conversation to a person: transfer number, branches and the WhatsApp routing plan.
3187
+ * Reading is open to any member; changing needs an org admin.
3188
+ */
3189
+ handoffSettings: {
3190
+ /** @returns {Promise<{agentId: string, transferNumber: string|null, branches: object[], routing: import('../types.js').HandoffRouting|null}>} */
3191
+ get: (id) => request(`/agents/${enc(id)}/handoff-settings`),
3192
+ /** Send only what you change. @param {string} id @param {{transferNumber?: string|null, branches?: object[], routing?: import('../types.js').HandoffRouting|null}} patch */
3193
+ update: (id, patch) => request(`/agents/${enc(id)}/handoff-settings`, json2("PUT", patch))
3194
+ },
3195
+ /** Get memory audit trail */
3196
+ getMemory: (id) => request(`/agents/${enc(id)}/memory`),
3197
+ /** Get telemetry audit traces */
3198
+ getTraces: (id) => request(`/agents/${enc(id)}/traces`),
3199
+ /** Get goals progress */
3200
+ getGoals: (id) => request(`/agents/${enc(id)}/goals`),
3201
+ /**
3202
+ * Connect to the agent's real-time WebSocket stream.
3203
+ * Works in browsers and Node.js environments supporting WebSocket globally.
3204
+ * @param {string} id - The agent ID
3205
+ * @param {object} [options]
3206
+ * @param {any} [options.WebSocketClass] - Pass a custom WebSocket class (e.g. from 'ws' npm package in Node.js) if not defined globally.
3207
+ */
3208
+ connect: (id, options = {}) => {
3209
+ const WS = options.WebSocketClass || (typeof WebSocket !== "undefined" ? WebSocket : null);
3210
+ if (!WS) {
3211
+ throw new Error('WebSocket is not defined in this environment. Please pass options.WebSocketClass (e.g., import ws from "ws").');
3212
+ }
3213
+ const wsUrl = client.baseUrl.replace(/^http/, "ws") + `/agents/trait-agent/${enc(id)}?token=${enc(client.token || "")}`;
3214
+ return new WS(wsUrl);
3215
+ }
3216
+ };
3217
+ return api;
3218
+ }
3219
+
3220
+ // ../sdk/src/resources/skills.js
3221
+ function skills(client) {
3222
+ const request = (path, options) => client._request(path, options);
3223
+ const api = {
3224
+ /** List all skills */
3225
+ list: () => request("/skills"),
3226
+ /** Register a custom skill */
3227
+ register: (manifest) => request("/skills/register", {
3228
+ method: "POST",
3229
+ body: JSON.stringify(manifest)
3230
+ }),
3231
+ /** Get kernel run stats */
3232
+ stats: () => request("/skills/stats")
3233
+ };
3234
+ return api;
3235
+ }
3236
+
3237
+ // ../sdk/src/resources/tasks.js
3238
+ function tasks(client) {
3239
+ const request = (path, options) => client._request(path, options);
3240
+ const api = {
3241
+ /**
3242
+ * Execute a named or custom structured task
3243
+ * @param {string} task - Name of the task (e.g. 'recommend_vehicle', 'verify_license', 'custom')
3244
+ * @param {object} payload - Task input payload
3245
+ * @param {string} [agentId] - Optional agent ID scope
3246
+ */
3247
+ run: (task, payload = {}, agentId = null) => request("/tasks", {
3248
+ method: "POST",
3249
+ body: JSON.stringify({ task, payload, ...agentId ? { agentId } : {} })
3250
+ }),
3251
+ /** Get count of items awaiting review across tools and dashboards */
3252
+ pending: () => request("/tasks/pending")
3253
+ };
3254
+ return api;
3255
+ }
3256
+
3257
+ // ../sdk/src/resources/approvals.js
3258
+ function approvals2(client) {
3259
+ const request = (path, options) => client._request(path, options);
3260
+ const api = {
3261
+ /**
3262
+ * List approvals.
3263
+ * @param {{status?: import('../types.js').ApprovalStatus, kind?: string, agentId?: string, limit?: number, offset?: number}} [filters]
3264
+ * @returns {Promise<{approvals: import('../types.js').Approval[]}>}
3265
+ */
3266
+ list: (filters = {}) => request(`/approvals${qs(filters)}`),
3267
+ /** @returns {Promise<{pending: number, byKind: Record<string, number>}>} */
3268
+ count: () => request("/approvals/count"),
3269
+ /** @param {string} id @returns {Promise<import('../types.js').Approval>} */
3270
+ get: (id) => request(`/approvals/${enc(id)}`),
3271
+ /**
3272
+ * Approve a pending request. Rejects with `error.status === 409` if it was already answered or expired.
3273
+ * @param {string} id
3274
+ * @param {string} [reason] - up to 500 characters
3275
+ * @returns {Promise<{approval: import('../types.js').Approval}>}
3276
+ */
3277
+ approve: (id, reason) => request(`/approvals/${enc(id)}/approve`, json2("POST", reason ? { reason } : {})),
3278
+ /**
3279
+ * Deny a pending request.
3280
+ * @param {string} id
3281
+ * @param {string} [reason]
3282
+ * @returns {Promise<{approval: import('../types.js').Approval}>}
3283
+ */
3284
+ deny: (id, reason) => request(`/approvals/${enc(id)}/deny`, json2("POST", reason ? { reason } : {})),
3285
+ /** How long requests wait and what happens when nobody answers. */
3286
+ settings: () => request("/approvals/settings"),
3287
+ /**
3288
+ * @param {{timeoutMinutes?: number, onTimeout?: 'escalate'|'deny', liveWaitSeconds?: number, notifyEmail?: boolean}} patch
3289
+ */
3290
+ updateSettings: (patch) => request("/approvals/settings", json2("PUT", patch)),
3291
+ /** Starter rule templates and the available comparisons. */
3292
+ ruleTemplates: () => request("/approvals/rule-templates"),
3293
+ rules: {
3294
+ /** @param {string} agentId @returns {Promise<{rules: (import('../types.js').ApprovalRule & {sentence: string})[]}>} */
3295
+ list: (agentId) => request(`/approvals/agents/${enc(agentId)}/rules`),
3296
+ /**
3297
+ * Replace the agent's rules.
3298
+ * @param {string} agentId
3299
+ * @param {import('../types.js').ApprovalRule[]} rules
3300
+ */
3301
+ set: (agentId, rules) => request(`/approvals/agents/${enc(agentId)}/rules`, json2("PUT", { rules })),
3302
+ /**
3303
+ * See what the rules would do for a sample request. Pass `rules` to test unsaved edits.
3304
+ * @param {string} agentId
3305
+ * @param {{toolName: string, args?: object, rules?: import('../types.js').ApprovalRule[]}} sample
3306
+ */
3307
+ preview: (agentId, sample) => request(`/approvals/agents/${enc(agentId)}/rules/preview`, json2("POST", sample))
3308
+ }
3309
+ };
3310
+ return api;
3311
+ }
3312
+
3313
+ // ../sdk/src/resources/reports.js
3314
+ function reports(client) {
3315
+ const request = (path, options) => client._request(path, options);
3316
+ const api = {
3317
+ /**
3318
+ * @param {{days?: number, agentId?: string}} [filters] - days 1 to 365, default 7
3319
+ * @returns {Promise<import('../types.js').ReportSummary>}
3320
+ */
3321
+ summary: (filters = {}) => request(`/reports/summary${qs(filters)}`),
3322
+ /**
3323
+ * @param {{agentId?: string, outcome?: import('../types.js').Outcome, conversationId?: string, days?: number, limit?: number, offset?: number}} [filters]
3324
+ * @returns {Promise<{traces: object[]}>}
3325
+ */
3326
+ traces: (filters = {}) => request(`/reports/traces${qs(filters)}`),
3327
+ /** One trace with its plain-language `story`. */
3328
+ trace: (id) => request(`/reports/traces/${enc(id)}`),
3329
+ /** @param {string} id @param {'up'|'down'|null} feedback */
3330
+ feedback: (id, feedback) => request(`/reports/traces/${enc(id)}/feedback`, json2("POST", { feedback })),
3331
+ /**
3332
+ * Re-run a conversation in the sandbox on another model and/or with extra instructions. Org admin; costs tokens.
3333
+ * @param {string} traceId
3334
+ * @param {{model?: string, instructions?: string}} options - at least one is required
3335
+ */
3336
+ replay: (traceId, options) => request(`/reports/traces/${enc(traceId)}/replay`, json2("POST", options)),
3337
+ /** @param {{conversationId?: string, limit?: number}} [filters] */
3338
+ replays: (filters = {}) => request(`/reports/replays${qs(filters)}`),
3339
+ /** @param {string} id */
3340
+ getReplay: (id) => request(`/reports/replays/${enc(id)}`),
3341
+ /** Retention and judge settings. */
3342
+ settings: () => request("/reports/settings"),
3343
+ /** @param {{retentionDays?: number, judgeEnabled?: boolean, judgeModel?: string}} patch */
3344
+ updateSettings: (patch) => request("/reports/settings", json2("PUT", patch))
3345
+ };
3346
+ return api;
3347
+ }
3348
+
3349
+ // ../sdk/src/resources/evals.js
3350
+ function evals(client) {
3351
+ const request = (path, options) => client._request(path, options);
3352
+ const api = {
3353
+ /** @param {{agentId?: string}} [filters] @returns {Promise<{suites: import('../types.js').EvalSuite[]}>} */
3354
+ suites: (filters = {}) => request(`/evals/suites${qs(filters)}`),
3355
+ /** @param {string} id @returns {Promise<import('../types.js').EvalSuite>} */
3356
+ getSuite: (id) => request(`/evals/suites/${enc(id)}`),
3357
+ /** @param {{agentId: string, name: string, cases: import('../types.js').EvalCase[]}} suite @returns {Promise<import('../types.js').EvalSuite>} */
3358
+ createSuite: (suite) => request("/evals/suites", json2("POST", suite)),
3359
+ /** @param {string} id @param {{name?: string, cases?: import('../types.js').EvalCase[]}} patch */
3360
+ updateSuite: (id, patch) => request(`/evals/suites/${enc(id)}`, json2("PUT", patch)),
3361
+ /** @param {string} id */
3362
+ deleteSuite: (id) => request(`/evals/suites/${enc(id)}`, { method: "DELETE" }),
3363
+ /**
3364
+ * Run every case. Resolves even when cases fail: check `ok` / `passed`.
3365
+ * @param {string} suiteId
3366
+ * @param {{model?: string, trigger?: 'ci'|'api'}} [options]
3367
+ * @returns {Promise<import('../types.js').EvalRun>}
3368
+ */
3369
+ run: (suiteId, options = {}) => request(`/evals/suites/${enc(suiteId)}/run`, json2("POST", options)),
3370
+ /** Past runs of a suite. @param {string} suiteId @param {{limit?: number}} [filters] */
3371
+ runs: (suiteId, filters = {}) => request(`/evals/suites/${enc(suiteId)}/runs${qs(filters)}`),
3372
+ /** One stored run (results per case). @param {string} runId @returns {Promise<import('../types.js').EvalRun>} */
3373
+ results: (runId) => request(`/evals/runs/${enc(runId)}`)
3374
+ };
3375
+ return api;
3376
+ }
3377
+
3378
+ // ../sdk/src/resources/usage.js
3379
+ function usage2(client) {
3380
+ const request = (path, options) => client._request(path, options);
3381
+ const api = {
3382
+ /** Current period: meters (resolved conversations, voice minutes, messages), overage and status. @returns {Promise<import('../types.js').Usage>} */
3383
+ current: () => request("/billing/usage"),
3384
+ /** Up to 12 previous periods. @returns {Promise<import('../types.js').Usage[]>} */
3385
+ history: () => request("/billing/usage/history"),
3386
+ /** The organization's plan row (agent limit, messages limit, API rate limit per minute, ...). */
3387
+ limits: () => request("/billing/my-limits"),
3388
+ /**
3389
+ * Spend cap and the message customers see while conversations are paused. Org admin.
3390
+ * @param {{spendCapCents?: number|null, fallbackMessage?: string|null}} patch
3391
+ */
3392
+ updateSettings: (patch) => request("/billing/usage/settings", json2("PUT", patch)),
3393
+ /** Last 24 invoices. */
3394
+ invoices: () => request("/billing/invoices")
3395
+ };
3396
+ return api;
3397
+ }
3398
+
3399
+ // ../sdk/src/resources/handoffs.js
3400
+ function handoffs(client) {
3401
+ const request = (path, options) => client._request(path, options);
3402
+ const api = {
3403
+ /** @param {{status?: 'active'|'open'|'transfer_pending'|'transferred'|'resolved', assignee?: string}} [filters] */
3404
+ list: (filters = {}) => request(`/handoffs${qs(filters)}`),
3405
+ /** Supervisor numbers: open, transfer pending, unassigned, SLA breaches. */
3406
+ summary: () => request("/handoffs/summary"),
3407
+ /** Pick a request up. @param {string} id */
3408
+ claim: (id) => request(`/handoffs/${enc(id)}/claim`, json2("POST")),
3409
+ /** Give a request back. @param {string} id */
3410
+ release: (id) => request(`/handoffs/${enc(id)}/release`, json2("POST")),
3411
+ /** Assign a request to a teammate. @param {string} id @param {string} assigneeId */
3412
+ assign: (id, assigneeId) => request(`/handoffs/${enc(id)}/assign`, json2("POST", { assigneeId })),
3413
+ /** Mark a request handled. @param {string} id */
3414
+ resolve: (id) => request(`/handoffs/${enc(id)}/resolve`, json2("POST")),
3415
+ /**
3416
+ * An agent's handover settings: transfer number, branches and the WhatsApp `routing` plan.
3417
+ * @param {string} agentId
3418
+ * @returns {Promise<{agentId: string, transferNumber: string|null, branches: object[], routing: import('../types.js').HandoffRouting|null}>}
3419
+ */
3420
+ /** @deprecated Use `agents.handoffSettings.get`. */
3421
+ settings: (agentId) => request(`/telephony/handoff-settings/${enc(agentId)}`),
3422
+ /**
3423
+ * Update handover settings. Send only what you change: a body with just `routing` leaves the transfer number and branches alone.
3424
+ * @param {string} agentId
3425
+ * @param {{transferNumber?: string|null, branches?: object[], routing?: import('../types.js').HandoffRouting|null}} patch
3426
+ */
3427
+ updateSettings: (agentId, patch) => request(`/telephony/handoff-settings/${enc(agentId)}`, json2("PUT", patch)),
3428
+ /** The WhatsApp handoff routing plan, or null when none is set. @param {string} agentId */
3429
+ getRouting: async (agentId) => {
3430
+ var _a2;
3431
+ return (_a2 = (await api.settings(agentId)).routing) != null ? _a2 : null;
3432
+ },
3433
+ /**
3434
+ * Set (or, with null, clear) the WhatsApp handoff routing plan: who rings, in order, when an agent passes a live call to a person.
3435
+ * @param {string} agentId
3436
+ * @param {import('../types.js').HandoffRouting|null} routing
3437
+ */
3438
+ setRouting: (agentId, routing) => api.updateSettings(agentId, { routing })
3439
+ };
3440
+ return api;
3441
+ }
3442
+
3443
+ // ../sdk/src/resources/calls.js
3444
+ function calls(client) {
3445
+ const call = (id, suffix = "") => `/calls/${enc(id)}${suffix}`;
3446
+ return {
3447
+ /** The most recent calls, newest first. @param {{limit?: number}} [options] @returns {Promise<{calls: {id: string, direction: string, from: string, to: string, status: string, startedAt: string|null, durationSeconds: number|null}[]}>} */
3448
+ list: ({ limit } = {}) => client._request(`/calls${qs({ limit })}`),
3449
+ /** How outbound calls are placed: `direct` (default) or `agent-first`. Changing it needs an org admin. */
3450
+ outboundSettings: {
3451
+ /** @returns {Promise<{mode: 'direct'|'agent-first'}>} */
3452
+ get: () => client._request("/telephony/outbound-call-settings"),
3453
+ /** @param {{mode: 'direct'|'agent-first'}} settings */
3454
+ update: (settings) => client._request("/telephony/outbound-call-settings", json2("PUT", settings))
3455
+ },
3456
+ /**
3457
+ * Place an outbound call.
3458
+ * WhatsApp: `{ channel?: 'whatsapp', to, from, sipHostname, sipPassword, mediaEncryption?, agentId?, agentSipUsername?, sdp?, sdpType? }`
3459
+ * Phone: `{ channel: 'phone', to, agentSipUsername, from?, agentId? }` (bridged to the agent's browser softphone)
3460
+ * @param {object} options
3461
+ */
3462
+ create: (options) => client._request("/calls", json2("POST", options)),
3463
+ /** Live state of a call, including a handoff leg (`bridge`). @param {string} id */
3464
+ get: (id) => client._request(call(id)),
3465
+ /** End or cancel a call. @param {string} id */
3466
+ hangup: (id) => client._request(call(id, "/hangup"), json2("POST")),
3467
+ /**
3468
+ * Hand the call to a person while the customer stays connected. Give one `target`, an ordered `targets` list,
3469
+ * or neither to use the agent's saved routing plan.
3470
+ * @param {string} id
3471
+ * @param {{target?: string, targets?: {kind: 'softphone'|'phone', target: string, ringSecs?: number}[], from?: string, timeoutSecs?: number}} [options]
3472
+ */
3473
+ handoff: (id, options = {}) => client._request(call(id, "/handoff"), json2("POST", options)),
3474
+ /** Drop the person's leg only. `resumeAi` (default true) hands the call back to the AI. */
3475
+ endHandoff: (id, { resumeAi = true } = {}) => client._request(call(id, "/handoff"), json2("DELETE", { resumeAi })),
3476
+ /** Silence or restore the AI on the call. */
3477
+ muteAi: (id, muted) => client._request(call(id, "/ai-mute"), json2("POST", { muted })),
3478
+ /** Short-lived token for the call's audio WebSocket (reconnect with a fresh one). */
3479
+ audioToken: (id) => client._request(call(id, "/audio-token"), json2("POST")),
3480
+ /** Negotiate a direct WebRTC browser leg. @param {string} id @param {{sdp: string, type?: string}} offer */
3481
+ webrtc: (id, { sdp, type = "offer" } = {}) => client._request(call(id, "/webrtc"), json2("POST", { sdp, type }))
3482
+ };
3483
+ }
3484
+
3485
+ // ../sdk/src/resources/whatsapp.js
3486
+ function whatsapp(client) {
3487
+ return {
3488
+ /** Has the customer allowed WhatsApp calls? WhatsApp refuses calls to anyone who has not. */
3489
+ callPermissions: {
3490
+ /**
3491
+ * @param {string} to customer number, E.164
3492
+ * @param {{agentId?: string, from?: string}} [options] pick the WhatsApp account when the organization has several
3493
+ * @returns {Promise<{to: string, granted: boolean, status: string, permanent: boolean, expiresAt: string|null, canRequest: boolean, canCall: boolean}>}
3494
+ */
3495
+ get: (to, { agentId, from } = {}) => client._request(`/whatsapp/call-permissions${qs({ to, agentId, from })}`),
3496
+ /**
3497
+ * Ask the customer to allow calls (WhatsApp's permission prompt). Needs the customer to have messaged in the last 24
3498
+ * hours; otherwise you get `needsTemplate: true` and send your own approved template. The answer arrives as a
3499
+ * `call.permission.granted` / `call.permission.denied` event.
3500
+ * @param {string} to
3501
+ * @param {{agentId?: string, from?: string, text?: string}} [options]
3502
+ */
3503
+ request: (to, { agentId, from, text } = {}) => client._request("/whatsapp/call-permissions", json2("POST", { to, agentId, from, text }))
3504
+ }
3505
+ };
3506
+ }
3507
+
3508
+ // ../sdk/src/resources/phoneNumbers.js
3509
+ function phoneNumbers(client) {
3510
+ return {
3511
+ /** The organization's phone lines and the channels each takes (`voice` = phone, `whatsapp_calling`, `whatsapp`). @returns {Promise<{numbers: object[]}>} */
3512
+ list: () => client._request("/telephony/numbers"),
3513
+ /** The call flow (TraitFlow) a number runs before it reaches an agent. */
3514
+ flow: {
3515
+ /** @returns {Promise<{enabled: boolean, flow: import('../types.js').TraitFlow|null}>} */
3516
+ get: (phoneNumberId) => client._request(`/phone-numbers/${enc(phoneNumberId)}/flow`),
3517
+ /**
3518
+ * Validate and save a flow. Changes live call handling; needs an org admin. Rejects with a `ValidationError` if invalid.
3519
+ * @param {string} phoneNumberId
3520
+ * @param {import('../types.js').TraitFlow} flow
3521
+ * @param {{enabled?: boolean}} [options]
3522
+ */
3523
+ save: (phoneNumberId, flow, { enabled = true } = {}) => client._request(`/phone-numbers/${enc(phoneNumberId)}/flow`, json2("PUT", { flow, enabled }))
3524
+ }
3525
+ };
3526
+ }
3527
+
3528
+ // ../sdk/src/resources/softphone.js
3529
+ function softphone(client) {
3530
+ return {
3531
+ /** Login credentials for the WebRTC client. @returns {Promise<{token: string, sipUsername: string|null}>} */
3532
+ token: () => client._request("/softphone/token", json2("POST")),
3533
+ /**
3534
+ * Say this browser can take calls. Registration lasts 120 seconds: repeat it every 60 seconds while the softphone is open.
3535
+ * @param {{sipUsername: string, ringTimeoutSeconds?: number, number?: string, numbers?: string[]}} options `numbers` limits which lines ring here
3536
+ */
3537
+ register: (options) => client._request("/softphone/registrations", json2("POST", options)),
3538
+ /** Stop ringing this browser. @param {string} sipUsername */
3539
+ unregister: (sipUsername) => client._request("/softphone/registrations", json2("DELETE", { sipUsername }))
3540
+ };
3541
+ }
3542
+
3543
+ // ../sdk/src/resources/flows.js
3544
+ function flows(client) {
3545
+ return {
3546
+ /** @deprecated Use `phoneNumbers.flow.get`. */
3547
+ get: (phoneNumberId) => client.phoneNumbers.flow.get(phoneNumberId),
3548
+ /** @deprecated Use `phoneNumbers.flow.save`. */
3549
+ save: (phoneNumberId, flow, options) => client.phoneNumbers.flow.save(phoneNumberId, flow, options),
3550
+ /**
3551
+ * Check a flow. Resolves `{ valid: true, flow }` with the normalised flow, or `{ valid: false, error }` for a bad flow.
3552
+ * Other failures (not signed in, server down) still reject.
3553
+ * @param {import('../types.js').TraitFlow} flow
3554
+ * @returns {Promise<{valid: boolean, flow?: import('../types.js').TraitFlow, error?: string}>}
3555
+ */
3556
+ validate: async (flow) => {
3557
+ var _a2;
3558
+ try {
3559
+ return await client._request("/flows/validate", json2("POST", { flow }));
3560
+ } catch (error) {
3561
+ if (error.status === 400 && ((_a2 = error.body) == null ? void 0 : _a2.valid) === false) return error.body;
3562
+ throw error;
3563
+ }
3564
+ },
3565
+ /**
3566
+ * Describe a flow in plain English and get a draft back, grounded in your agents and team numbers. Pass `currentFlow`
3567
+ * to get suggested changes against it. Nothing is saved.
3568
+ * @param {string} prompt
3569
+ * @param {{currentFlow?: import('../types.js').TraitFlow, agents?: {id: string, name: string}[]}} [options]
3570
+ */
3571
+ generate: (prompt, options = {}) => client._request("/flows/generate", json2("POST", { prompt, ...options })),
3572
+ /**
3573
+ * Dry-run a call through a flow at no phone cost.
3574
+ * @param {import('../types.js').TraitFlow} flow
3575
+ * @param {{digits?: string, callerNumber?: string, scenario?: string, phoneNumber?: string, defaultAgentId?: string}} [options]
3576
+ */
3577
+ simulate: (flow, options = {}) => client._request("/flows/simulate", json2("POST", { flow, ...options }))
3578
+ };
3579
+ }
3580
+
3581
+ // ../sdk/src/pagination.js
3582
+ async function* paginate(fetchPage, { start, maxItems = Infinity } = {}) {
3583
+ var _a2;
3584
+ let cursor = start;
3585
+ let seen = 0;
3586
+ for (; ; ) {
3587
+ const page = await fetchPage(cursor);
3588
+ for (const item of (_a2 = page.data) != null ? _a2 : []) {
3589
+ if (seen++ >= maxItems) return;
3590
+ yield item;
3591
+ }
3592
+ if (!page.hasMore || page.nextCursor === null || page.nextCursor === void 0 || page.nextCursor === cursor) return;
3593
+ cursor = page.nextCursor;
3594
+ }
3595
+ }
3596
+
3597
+ // ../sdk/src/sse.js
3598
+ var SseParser = class {
3599
+ constructor() {
3600
+ this.buf = "";
3601
+ this.cur = { data: [] };
3602
+ this.lastId = void 0;
3603
+ }
3604
+ /** @param {string} chunk @returns {{id?: string, event: string, data: string, retry?: number}[]} */
3605
+ push(chunk) {
3606
+ var _a2;
3607
+ this.buf += chunk;
3608
+ const out = [];
3609
+ let nl;
3610
+ while ((nl = this.buf.search(/\r\n|\n|\r/)) !== -1) {
3611
+ const line = this.buf.slice(0, nl);
3612
+ const sep = this.buf.slice(nl).startsWith("\r\n") ? 2 : 1;
3613
+ if (this.buf[nl] === "\r" && nl + 1 === this.buf.length) break;
3614
+ this.buf = this.buf.slice(nl + sep);
3615
+ if (line === "") {
3616
+ if (this.cur.data.length || this.cur.event) out.push({ id: this.cur.id, event: (_a2 = this.cur.event) != null ? _a2 : "message", data: this.cur.data.join("\n"), retry: this.cur.retry });
3617
+ this.cur = { data: [] };
3618
+ continue;
3619
+ }
3620
+ if (line.startsWith(":")) continue;
3621
+ const i = line.indexOf(":");
3622
+ const field2 = i === -1 ? line : line.slice(0, i);
3623
+ let value = i === -1 ? "" : line.slice(i + 1);
3624
+ if (value.startsWith(" ")) value = value.slice(1);
3625
+ if (field2 === "data") this.cur.data.push(value);
3626
+ else if (field2 === "event") this.cur.event = value;
3627
+ else if (field2 === "id") {
3628
+ this.cur.id = value;
3629
+ this.lastId = value;
3630
+ } else if (field2 === "retry" && /^\d+$/.test(value)) this.cur.retry = Number(value);
3631
+ }
3632
+ return out;
3633
+ }
3634
+ };
3635
+ var sleepAbortable = (ms, signal) => new Promise((resolve) => {
3636
+ var _a2;
3637
+ if (signal == null ? void 0 : signal.aborted) return resolve();
3638
+ const t2 = setTimeout(done, ms);
3639
+ function done() {
3640
+ var _a3;
3641
+ (_a3 = signal == null ? void 0 : signal.removeEventListener) == null ? void 0 : _a3.call(signal, "abort", done);
3642
+ clearTimeout(t2);
3643
+ resolve();
3644
+ }
3645
+ (_a2 = signal == null ? void 0 : signal.addEventListener) == null ? void 0 : _a2.call(signal, "abort", done, { once: true });
3646
+ });
3647
+ async function* streamEvents(open, { types = [], after, signal, reconnectDelayMs = 250, maxRetryDelayMs = 1e4 } = {}) {
3648
+ let cursor = after;
3649
+ let failures = 0;
3650
+ const dec = new TextDecoder();
3651
+ while (!(signal == null ? void 0 : signal.aborted)) {
3652
+ const params = new URLSearchParams();
3653
+ if (types.length) params.set("types", types.join(","));
3654
+ if (cursor !== void 0 && cursor !== null) params.set("after", String(cursor));
3655
+ let response;
3656
+ try {
3657
+ response = await open(`/events/stream${params.size ? `?${params}` : ""}`, {
3658
+ signal,
3659
+ headers: cursor !== void 0 && cursor !== null ? { "Last-Event-ID": String(cursor) } : {}
3660
+ });
3661
+ } catch (error) {
3662
+ if ((signal == null ? void 0 : signal.aborted) || (error == null ? void 0 : error.name) === "AbortError") return;
3663
+ if (error instanceof AuthenticationError || error instanceof PermissionError || error instanceof TraitOSError && error.status && error.status < 500 && error.status !== 429) throw error;
3664
+ failures++;
3665
+ await sleepAbortable(Math.min(maxRetryDelayMs, reconnectDelayMs * 2 ** failures), signal);
3666
+ continue;
3667
+ }
3668
+ failures = 0;
3669
+ const parser = new SseParser();
3670
+ try {
3671
+ const reader = response.body.getReader();
3672
+ for (; ; ) {
3673
+ const { done, value } = await reader.read();
3674
+ if (done) break;
3675
+ const msgs = parser.push(dec.decode(value, { stream: true }));
3676
+ if (!msgs.length && parser.lastId) cursor = Number(parser.lastId);
3677
+ for (const msg of msgs) {
3678
+ if (!msg.data) continue;
3679
+ let envelope;
3680
+ try {
3681
+ envelope = JSON.parse(msg.data);
3682
+ } catch {
3683
+ continue;
3684
+ }
3685
+ const seq = msg.id !== void 0 && msg.id !== "" ? Number(msg.id) : void 0;
3686
+ if (seq !== void 0) cursor = seq;
3687
+ yield { seq, ...envelope };
3688
+ }
3689
+ }
3690
+ } catch (error) {
3691
+ if ((signal == null ? void 0 : signal.aborted) || (error == null ? void 0 : error.name) === "AbortError") return;
3692
+ failures++;
3693
+ await sleepAbortable(Math.min(maxRetryDelayMs, reconnectDelayMs * 2 ** failures), signal);
3694
+ continue;
3695
+ }
3696
+ await sleepAbortable(reconnectDelayMs, signal);
3697
+ }
3698
+ }
3699
+
3700
+ // ../sdk/src/resources/events.js
3701
+ function events(client) {
3702
+ const api = {
3703
+ /**
3704
+ * One page, oldest first.
3705
+ * @param {{after?: number, types?: string[]|string, limit?: number}} [filters]
3706
+ * @returns {Promise<{data: object[], nextCursor: number, hasMore: boolean}>}
3707
+ */
3708
+ list: (filters = {}) => client._request(`/events${qs({ after: filters.after, types: filters.types, limit: filters.limit })}`),
3709
+ /** Every event after a cursor, page by page. @param {{after?: number, types?: string[]|string, limit?: number, maxItems?: number}} [filters] */
3710
+ iterate: ({ maxItems, ...filters } = {}) => {
3711
+ var _a2;
3712
+ return paginate((after) => api.list({ ...filters, after }), { start: (_a2 = filters.after) != null ? _a2 : 0, maxItems });
3713
+ },
3714
+ /** The event types TraitOS emits. @returns {Promise<{data: string[]}>} */
3715
+ types: () => client._request("/events/types"),
3716
+ /**
3717
+ * A live async stream that reconnects by itself and resumes where it left off.
3718
+ *
3719
+ * const ac = new AbortController();
3720
+ * for await (const event of client.events.stream({ types: ['call.*'], signal: ac.signal })) { ... }
3721
+ *
3722
+ * @param {{types?: string[], after?: number, signal?: AbortSignal}} [options] omit `after` to start from now; `after: 0` replays retained history
3723
+ */
3724
+ stream: (options = {}) => streamEvents(client._open, options),
3725
+ /**
3726
+ * Callback form of `stream`. Returns `{ close(), done }`; `done` resolves when closed, or rejects if the stream gives up
3727
+ * (for example the token is no longer valid).
3728
+ * @param {(event: object) => void} handler
3729
+ * @param {{types?: string[], after?: number, onError?: (error: Error) => void}} [options]
3730
+ */
3731
+ subscribe(handler, { onError, ...options } = {}) {
3732
+ const controller = new AbortController();
3733
+ const done = (async () => {
3734
+ try {
3735
+ for await (const event of api.stream({ ...options, signal: controller.signal })) handler(event);
3736
+ } catch (error) {
3737
+ if (onError) onError(error);
3738
+ else throw error;
3739
+ }
3740
+ })();
3741
+ return { close: () => controller.abort(), done };
3742
+ }
3743
+ };
3744
+ return api;
3745
+ }
3746
+
3747
+ // ../sdk/src/webhookSignature.js
3748
+ var DEFAULT_TOLERANCE_SECONDS = 300;
3749
+ var enc2 = new TextEncoder();
3750
+ var toHex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
3751
+ function safeEqual(a, b) {
3752
+ if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
3753
+ let diff = 0;
3754
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
3755
+ return diff === 0;
3756
+ }
3757
+ async function hmacHex(secret, payload) {
3758
+ const key = await crypto.subtle.importKey("raw", enc2.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
3759
+ return toHex(await crypto.subtle.sign("HMAC", key, enc2.encode(payload)));
3760
+ }
3761
+ function header(headers, name) {
3762
+ var _a2;
3763
+ if (!headers) return void 0;
3764
+ if (typeof headers.get === "function") return (_a2 = headers.get(name)) != null ? _a2 : void 0;
3765
+ const lower = name.toLowerCase();
3766
+ for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === lower) return Array.isArray(v) ? v[0] : v;
3767
+ return void 0;
3768
+ }
3769
+ async function verifyWebhook(rawBody, headers, secret, { toleranceSeconds = DEFAULT_TOLERANCE_SECONDS, now = Date.now() } = {}) {
3770
+ if (typeof rawBody !== "string") throw new WebhookSignatureError("Pass the raw request body as a string, not parsed JSON.", { code: "invalid_body" });
3771
+ if (!secret) throw new WebhookSignatureError("No webhook secret was given.", { code: "missing_secret" });
3772
+ const sigV2 = header(headers, "x-traitos-signature-v2");
3773
+ const timestamp = header(headers, "x-traitos-timestamp");
3774
+ if (!sigV2 || !timestamp) {
3775
+ throw new WebhookSignatureError("Missing X-TraitOS-Signature-V2 or X-TraitOS-Timestamp header.", { code: "missing_signature" });
3776
+ }
3777
+ const ts = Number(timestamp);
3778
+ if (!Number.isFinite(ts)) throw new WebhookSignatureError("Invalid X-TraitOS-Timestamp.", { code: "invalid_timestamp" });
3779
+ if (toleranceSeconds > 0 && Math.abs(now / 1e3 - ts) > toleranceSeconds) {
3780
+ throw new WebhookSignatureError("The webhook timestamp is outside the allowed window (possible replay).", { code: "timestamp_out_of_range" });
3781
+ }
3782
+ const expected = await hmacHex(secret, `${timestamp}.${rawBody}`);
3783
+ if (!safeEqual(expected, sigV2.trim().toLowerCase())) throw new WebhookSignatureError("Signature does not match.", { code: "signature_mismatch" });
3784
+ return true;
3785
+ }
3786
+ async function constructWebhookEvent(rawBody, headers, secret, options) {
3787
+ await verifyWebhook(rawBody, headers, secret, options);
3788
+ try {
3789
+ return JSON.parse(rawBody);
3790
+ } catch {
3791
+ throw new WebhookSignatureError("The body is not valid JSON.", { code: "invalid_body" });
3792
+ }
3793
+ }
3794
+ async function signWebhook(rawBody, secret, { timestamp = Math.floor(Date.now() / 1e3), eventId } = {}) {
3795
+ const ts = String(timestamp);
3796
+ return {
3797
+ "X-TraitOS-Signature": await hmacHex(secret, rawBody),
3798
+ "X-TraitOS-Timestamp": ts,
3799
+ "X-TraitOS-Signature-V2": await hmacHex(secret, `${ts}.${rawBody}`),
3800
+ ...eventId ? { "X-TraitOS-Event-Id": eventId } : {}
3801
+ };
3802
+ }
3803
+
3804
+ // ../sdk/src/resources/webhooks.js
3805
+ function webhooks(client) {
3806
+ return {
3807
+ /** @returns {Promise<{webhooks: {id: string, url: string, events: string[], status: string, created_at: number}[]}>} */
3808
+ list: () => client._request("/webhooks"),
3809
+ /**
3810
+ * @param {{url: string, events: string[]}} webhook `url` must be a public https endpoint
3811
+ * @returns {Promise<{id: string, url: string, secret: string, events: string[], status: string}>}
3812
+ */
3813
+ create: ({ url, events: events2 }) => client._request("/webhooks", json2("POST", { url, events: events2 })),
3814
+ /** Stop sending to an endpoint. @param {string} id */
3815
+ delete: (id) => client._request(`/webhooks/${enc(id)}`, { method: "DELETE" }),
3816
+ /** Send a test delivery. @param {{url: string, secret?: string}} options */
3817
+ test: (options) => client._request("/webhooks/test", json2("POST", options)),
3818
+ /** Check a delivery's signature. Resolves true or throws `WebhookSignatureError`. Pass the RAW body. */
3819
+ verify: verifyWebhook,
3820
+ /** Verify, then parse into `{ id, type, created_at, data }`. */
3821
+ constructEvent: constructWebhookEvent,
3822
+ /** Sign a payload as TraitOS does, to test your handler locally. */
3823
+ sign: signWebhook
3824
+ };
3825
+ }
3826
+
3827
+ // ../sdk/src/resources/apiKeys.js
3828
+ function apiKeys(client) {
3829
+ return {
3830
+ /** The scopes a key can be limited to. */
3831
+ scopes: () => client._request("/apikeys/scopes"),
3832
+ list: () => client._request("/apikeys"),
3833
+ /** @param {{name: string, scopes?: string[], rateLimitPerMin?: number, expiresInDays?: number}} options */
3834
+ create: (options) => client._request("/apikeys", json2("POST", options)),
3835
+ /** Revoke a key. @param {string} id */
3836
+ revoke: (id) => client._request(`/apikeys/${enc(id)}`, { method: "DELETE" })
3837
+ };
3838
+ }
3839
+
3840
+ // ../sdk/src/resources/contacts.js
3841
+ function contacts(client) {
3842
+ const companies = {
3843
+ list: (filters = {}) => client._request(`/contacts/companies${qs(filters)}`),
3844
+ create: (company) => client._request("/contacts/companies", json2("POST", company)),
3845
+ update: (id, patch) => client._request(`/contacts/companies/${enc(id)}`, json2("PUT", patch)),
3846
+ delete: (id) => client._request(`/contacts/companies/${enc(id)}`, { method: "DELETE" })
3847
+ };
3848
+ return {
3849
+ /** @param {Record<string, string|number>} [filters] e.g. `{ search: 'ana', limit: 50 }` */
3850
+ list: (filters = {}) => client._request(`/contacts${qs(filters)}`),
3851
+ get: (id) => client._request(`/contacts/${enc(id)}`),
3852
+ /** @param {{name: string, emails?: string[], phones?: string[], addresses?: object[], company?: string|object|null, metadata?: object}} contact */
3853
+ create: (contact) => client._request("/contacts", json2("POST", contact)),
3854
+ update: (id, patch) => client._request(`/contacts/${enc(id)}`, json2("PUT", patch)),
3855
+ delete: (id) => client._request(`/contacts/${enc(id)}`, { method: "DELETE" }),
3856
+ /** The contact's conversation and call history. */
3857
+ history: (id) => client._request(`/contacts/${enc(id)}/history`),
3858
+ /** Stop an agent contacting this person. @param {string} id @param {string} [reason] up to 240 characters */
3859
+ block: (id, reason) => client._request(`/contacts/${enc(id)}/block`, json2("POST", reason ? { reason } : {})),
3860
+ /** Find a contact by `phone`, `email` or your own id (`externalId` + `system`). Never creates one. Resolves `{ contact }` (null when none). */
3861
+ lookup: ({ phone, email, externalId, system } = {}) => client._request(`/contacts/lookup${qs({ phone, email, externalId, system })}`),
3862
+ /**
3863
+ * Find or create the contact for a person and tie it to your customer id, in one call: looks up `externalId` first, then the
3864
+ * phone / email, and creates the contact when nobody matches. Resolves `{ contact, created, conflicts? }`.
3865
+ * @param {{phone?: string, email?: string, name?: string, externalId?: string, system?: string}} person `system` names your side (default "default"; e.g. "cbs")
3866
+ */
3867
+ resolve: (person) => client._request("/contacts/resolve", json2("POST", person)),
3868
+ /** Set (or replace) your id for a contact. Events for that contact then carry `contact.externalIds[system]`. */
3869
+ linkExternalId: (id, system, externalId) => client._request(`/contacts/${enc(id)}/external-ids/${enc(system)}`, json2("PUT", { externalId })),
3870
+ /** Remove your id from a contact. */
3871
+ unlinkExternalId: (id, system) => client._request(`/contacts/${enc(id)}/external-ids/${enc(system)}`, { method: "DELETE" }),
3872
+ /** The living profile: numbers, emails, your ids, last contact time and channel, call and message counts, last call outcome / sentiment / intent / summary. */
3873
+ profile: (id) => client._request(`/contacts/${enc(id)}/profile`),
3874
+ mergeDuplicates: (options = {}) => client._request("/contacts/merge-duplicates", json2("POST", options)),
3875
+ companies
3876
+ };
3877
+ }
3878
+
3879
+ // ../sdk/src/resources/sms.js
3880
+ function sms(client) {
3881
+ const base = (agentId) => `/agents/${enc(agentId)}/sms`;
3882
+ return {
3883
+ /** Is SMS set up for this agent? */
3884
+ status: (agentId) => client._request(`${base(agentId)}/status`),
3885
+ /** Recent threads, newest first. */
3886
+ threads: (agentId) => client._request(base(agentId)),
3887
+ /** One thread with its messages. */
3888
+ thread: (agentId, threadId) => client._request(`${base(agentId)}/${enc(threadId)}`),
3889
+ /** @param {string} agentId @param {{to: string, body: string, contactName?: string, from?: string}} message `to` is E.164 */
3890
+ send: (agentId, { to, body, contactName, from }) => client._request(`${base(agentId)}/send`, json2("POST", { to, body, contact_name: contactName, from })),
3891
+ /** Reply in an existing thread. */
3892
+ reply: (agentId, threadId, body) => client._request(`${base(agentId)}/${enc(threadId)}/reply`, json2("POST", { body })),
3893
+ deleteThread: (agentId, threadId) => client._request(`${base(agentId)}/${enc(threadId)}`, { method: "DELETE" })
3894
+ };
3895
+ }
3896
+
3897
+ // ../sdk/src/resources/knowledge.js
3898
+ function knowledge(client) {
3899
+ const base = (agentId) => `/knowledge/${enc(agentId)}`;
3900
+ const src = (agentId, sourceId) => `${base(agentId)}/sources/${enc(sourceId)}`;
3901
+ return {
3902
+ sources: (agentId) => client._request(`${base(agentId)}/sources`),
3903
+ /** The stored chunks of one source. */
3904
+ chunks: (agentId, sourceId) => client._request(`${src(agentId, sourceId)}/chunks`),
3905
+ /** Add any source type. @param {string} agentId @param {{sourceType: string, sourceConfig?: object, skillName?: string, decayRate?: number, confidence?: number, label?: string}} source */
3906
+ ingest: (agentId, source) => client._request(`${base(agentId)}/ingest`, json2("POST", source)),
3907
+ /** @param {string} agentId @param {{url: string, label?: string, skillName?: string, decayRate?: number}} options */
3908
+ ingestUrl: (agentId, options) => client._request(`${base(agentId)}/ingest/url`, json2("POST", options)),
3909
+ /** Pull from a JSON API. @param {string} agentId @param {{url: string, method?: string, headers?: object, body?: any, responseType?: string, label?: string, skillName?: string}} options */
3910
+ ingestApi: (agentId, options) => client._request(`${base(agentId)}/ingest/api`, json2("POST", options)),
3911
+ /** Everything under a bucket prefix. @param {string} agentId @param {{prefix?: string, bucket?: string, skillName?: string}} [options] */
3912
+ ingestBucketPrefix: (agentId, options = {}) => client._request(`${base(agentId)}/ingest/r2-prefix`, json2("POST", options)),
3913
+ /** Upload a file. @param {string} agentId @param {FormData} form a `FormData` carrying the file */
3914
+ upload: (agentId, form) => client._request(`${base(agentId)}/ingest/upload`, { method: "POST", body: form }),
3915
+ /** See what a source would store, without storing it. */
3916
+ preview: (agentId, source) => client._request(`${base(agentId)}/preview`, json2("POST", source)),
3917
+ /** Fetch a source again. */
3918
+ reingest: (agentId, sourceId) => client._request(`${src(agentId, sourceId)}/reingest`, json2("POST")),
3919
+ /** @param {{label?: string, skillName?: string, decayRate?: number}} patch */
3920
+ updateSource: (agentId, sourceId, patch) => client._request(src(agentId, sourceId), json2("PATCH", patch)),
3921
+ deleteSource: (agentId, sourceId) => client._request(src(agentId, sourceId), { method: "DELETE" })
3922
+ };
3923
+ }
3924
+
3925
+ // ../sdk/src/resources/whatsappCalls.js
3926
+ function whatsappCalls(client) {
3927
+ const request = (path, options) => client._request(path, options);
3928
+ const api = {
3929
+ /**
3930
+ * Place an outbound WhatsApp call through the TraitOS Voice Gateway (optionally negotiating a direct WebRTC SDP leg).
3931
+ * @param {{to: string, from: string, sipHostname?: string, sipPassword?: string, mediaEncryption?: 'DTLS'|'SDES', agentId?: string, agentSipUsername?: string, sdp?: string, sdpType?: string}} options
3932
+ */
3933
+ outbound: (options) => request("/telephony/calls/whatsapp-outbound", json2("POST", options)),
3934
+ /** Negotiate a direct UDP/Opus WebRTC browser leg onto an active `wacall_…` gateway call. */
3935
+ webrtc: (id, { sdp, type = "offer" } = {}) => request("/telephony/calls/whatsapp-webrtc", json2("POST", { id, sdp, type })),
3936
+ /** Live state of a call, including the handoff leg (`bridge`). @param {string} id a `wacall_…` id */
3937
+ status: (id) => request(`/telephony/calls/whatsapp-status${qs({ id })}`),
3938
+ /** Short-lived token for the audio WebSocket (reconnect with a fresh one). @param {string} id */
3939
+ audioToken: (id) => request("/telephony/calls/whatsapp-audio-token", json2("POST", { id })),
3940
+ /**
3941
+ * Hand the call to a person. Give one `target`, an ordered `targets` list, or neither to use the agent's saved routing plan.
3942
+ * @param {string} id
3943
+ * @param {{target?: string, targets?: {kind: 'softphone'|'phone', target: string, ringSecs?: number}[], from?: string, timeoutSecs?: number}} [options]
3944
+ */
3945
+ handoff: (id, options = {}) => request("/telephony/calls/whatsapp-bridge", json2("POST", { id, ...options })),
3946
+ /** Drop the person's leg only; the customer stays connected. `resumeAi` (default true) hands the call back to the AI. */
3947
+ endHandoff: (id, { resumeAi = true } = {}) => request("/telephony/calls/whatsapp-bridge/hangup", json2("POST", { id, resumeAi })),
3948
+ /** Silence or restore the AI on the call. @param {string} id @param {boolean} muted */
3949
+ muteAi: (id, muted) => request("/telephony/calls/whatsapp-bridge/ai-mute", json2("POST", { id, muted })),
3950
+ /** End or cancel an outbound WhatsApp call. @param {string} id */
3951
+ hangup: (id) => request("/telephony/calls/whatsapp-hangup", json2("POST", { id })),
3952
+ /**
3953
+ * Has the customer allowed WhatsApp calls? WhatsApp refuses calls to anyone who has not (the call ends with
3954
+ * `failureCode: 'call_permission_required'`). Resolves `{ to, granted, status, permanent, expiresAt, canRequest, canCall }`.
3955
+ * @param {string} to customer number, E.164
3956
+ * @param {{agentId?: string, from?: string}} [options] pick the WhatsApp account when the organization has several
3957
+ */
3958
+ permission: (to, { agentId, from } = {}) => request(`/telephony/whatsapp/call-permission${qs({ to, agentId, from })}`),
3959
+ /**
3960
+ * Ask the customer to allow WhatsApp calls (WhatsApp's permission prompt; needs the customer to have messaged in the last
3961
+ * 24 hours, otherwise `needsTemplate: true` and you send your own approved template). Skips customers who already allowed
3962
+ * calls (`alreadyGranted`) and answers `rateLimited` when WhatsApp will not let you ask again yet. The customer's answer
3963
+ * arrives as a `call.permission.granted` / `call.permission.denied` webhook event.
3964
+ * @param {string} to customer number, E.164
3965
+ * @param {{agentId?: string, from?: string, text?: string}} [options]
3966
+ */
3967
+ requestPermission: (to, { agentId, from, text } = {}) => request("/telephony/whatsapp/call-permission/request", json2("POST", { to, agentId, from, text }))
3968
+ };
3969
+ return api;
3970
+ }
3971
+
3972
+ // ../sdk/src/resources/phoneCalls.js
3973
+ function phoneCalls(client) {
3974
+ const request = (path, options) => client._request(path, options);
3975
+ const api = {
3976
+ /**
3977
+ * Place a phone call from the organization's number and bridge it to the agent's softphone once the customer answers.
3978
+ * @param {{to: string, agentSipUsername: string, from?: string, agentId?: string}} options
3979
+ */
3980
+ outbound: (options) => request("/telephony/calls/pstn-outbound", json2("POST", options))
3981
+ };
3982
+ return api;
3983
+ }
3984
+
3985
+ // ../sdk/src/resources/partners.js
3986
+ function partners(client) {
3987
+ return {
3988
+ tenants: {
3989
+ /** @param {{status?: string, externalId?: string, limit?: number, cursor?: string}} [params] */
3990
+ list: (params) => client._request(`/partner/orgs${qs(params)}`),
3991
+ /**
3992
+ * Create a tenant. Safe to repeat: the same `externalId` returns the existing tenant (`created: false`).
3993
+ * @param {{name: string, externalId?: string, billing?: 'self'|'partner', limits?: {maxResolved?: number|null, maxVoiceMinutes?: number|null, maxMessages?: number|null},
3994
+ * domain?: string, contactEmail?: string, businessProfile?: object, mintApiKey?: boolean, voiceWebhook?: object,
3995
+ * cloneAgentId?: string, agentName?: string}} options
3996
+ * @returns {Promise<{ok: boolean, created: boolean, org: object, apiKey?: {key: string}}>} the API key is shown once
3997
+ */
3998
+ create: (options) => client._request("/partner/orgs", json2("POST", options)),
3999
+ /** @param {string} orgId */
4000
+ get: (orgId) => client._request(`/partner/orgs/${enc(orgId)}`),
4001
+ /**
4002
+ * Change a tenant. `billing: 'partner'` on an existing tenant starts next month, so nothing is billed twice.
4003
+ * @param {string} orgId
4004
+ * @param {{name?: string, status?: 'active'|'suspended', billing?: 'self'|'partner', limits?: object|null, externalId?: string, domain?: string, contactEmail?: string}} changes
4005
+ */
4006
+ update: (orgId, changes) => client._request(`/partner/orgs/${enc(orgId)}`, json2("PATCH", changes)),
4007
+ /** Mint a key for one tenant. @param {string} orgId @param {{name?: string, revokeExisting?: boolean}} [options] */
4008
+ createApiKey: (orgId, options = {}) => client._request(`/partner/orgs/${enc(orgId)}/api-keys`, json2("POST", options))
4009
+ },
4010
+ /** Usage across the partner and its tenants for a month. @param {{period?: string}} [params] period is YYYY-MM */
4011
+ usage: (params) => client._request(`/partner/usage${qs(params)}`),
4012
+ /** The month's statement: pooled usage, overage, and each organization's share. @param {{period?: string}} [params] */
4013
+ billing: (params) => client._request(`/partner/billing${qs(params)}`),
4014
+ /** Copy skills from a blueprint agent to tenants' agents. @param {{sourceAgentId: string, skillNames?: string[], childOrgIds?: string[], overwrite?: boolean}} options */
4015
+ syncSkills: (options) => client._request("/partner/skills/sync", json2("POST", options))
4016
+ };
4017
+ }
4018
+
4019
+ // ../sdk/src/resources/larynx.js
4020
+ function larynx(client) {
4021
+ return {
4022
+ /** What this deployment can do: engine (`signal` or `neural`), gate modes, spoken-challenge availability, limits. */
4023
+ capabilities: () => client._request("/larynx/capabilities"),
4024
+ /** The organization's settings (thresholds, mode, failMode, appliesTo, retention). */
4025
+ getSettings: () => client._request("/larynx/settings"),
4026
+ /** Change settings; send only what changes. A 400 means an out-of-range value. */
4027
+ updateSettings: (settings) => client._request("/larynx/settings", json2("PUT", settings)),
4028
+ /** Enroll or refine a voiceprint. `consent: true` is required. @param {{contactId?: string, phone?: string, displayName?: string, audioBase64: string, consent: true, consentSource?: string}} options */
4029
+ enroll: (options) => client._request("/larynx/enroll", json2("POST", options)),
4030
+ listProfiles: () => client._request("/larynx/profiles"),
4031
+ getProfile: (id) => client._request(`/larynx/profiles/${enc(id)}`),
4032
+ /** Rename, link to a CRM contact, or pause (`status: 'revoked'`) / resume (`'active'`) a voiceprint. */
4033
+ updateProfile: (id, patch) => client._request(`/larynx/profiles/${enc(id)}`, json2("PATCH", patch)),
4034
+ deleteProfile: (id) => client._request(`/larynx/profiles/${enc(id)}`, { method: "DELETE" }),
4035
+ /** Verify a clip: bot risk plus speaker match when a voiceprint is enrolled. Use the telephony call id as `callId`. */
4036
+ verify: (options) => client._request("/larynx/verify", json2("POST", options)),
4037
+ /** Who is speaking? Compares the clip with every enrolled voiceprint. */
4038
+ identify: (options) => client._request("/larynx/identify", json2("POST", options)),
4039
+ /** Issue a single-use spoken liveness challenge (`kind`: `digits` or `words`). */
4040
+ challenge: (options = {}) => client._request("/larynx/challenge", json2("POST", options)),
4041
+ /** Mid-call multi-speaker / speaker-swap check. */
4042
+ diarize: (options) => client._request("/larynx/diarize", json2("POST", options)),
4043
+ /** Audit log, newest first. */
4044
+ listVerifications: (filter = {}) => client._request(`/larynx/verifications${qs(filter)}`),
4045
+ /** Verification state for one call. */
4046
+ forCall: (callId) => client._request(`/larynx/calls/${enc(callId)}`)
4047
+ };
4048
+ }
4049
+
4050
+ // ../sdk/src/hybrid.js
4051
+ function safeCalculate(expression) {
4052
+ const src = String(expression != null ? expression : "");
4053
+ if (src.length > 200) throw new Error("Expression is too long");
4054
+ const tokens = [];
4055
+ const re = /\s*(?:(\d+\.?\d*|\.\d+)|(\*\*|[-+*/()]))/y;
4056
+ let pos = 0;
4057
+ while (pos < src.trimEnd().length) {
4058
+ re.lastIndex = pos;
4059
+ const m = re.exec(src);
4060
+ if (!m) throw new Error("Invalid expression");
4061
+ tokens.push(m[1] !== void 0 ? { n: Number(m[1]) } : { op: m[2] });
4062
+ pos = re.lastIndex;
4063
+ }
4064
+ if (!tokens.length) throw new Error("Invalid expression");
4065
+ let i = 0;
4066
+ const peek = () => tokens[i];
4067
+ const take = () => tokens[i++];
4068
+ const isOp = (t2, ...ops) => t2 && t2.op !== void 0 && ops.includes(t2.op);
4069
+ const expr = (depth) => {
4070
+ if (depth > 50) throw new Error("Expression is too deeply nested");
4071
+ let v = term(depth);
4072
+ while (isOp(peek(), "+", "-")) v = take().op === "+" ? v + term(depth) : v - term(depth);
4073
+ return v;
4074
+ };
4075
+ const term = (depth) => {
4076
+ let v = power(depth);
4077
+ while (isOp(peek(), "*", "/")) v = take().op === "*" ? v * power(depth) : v / power(depth);
4078
+ return v;
4079
+ };
4080
+ const power = (depth) => {
4081
+ const base = unary(depth);
4082
+ if (isOp(peek(), "**")) {
4083
+ take();
4084
+ return base ** power(depth);
4085
+ }
4086
+ return base;
4087
+ };
4088
+ const unary = (depth) => {
4089
+ if (isOp(peek(), "+", "-")) return take().op === "-" ? -unary(depth + 1) : unary(depth + 1);
4090
+ return primary(depth);
4091
+ };
4092
+ const primary = (depth) => {
4093
+ const t2 = take();
4094
+ if (t2 && t2.n !== void 0) return t2.n;
4095
+ if (isOp(t2, "(")) {
4096
+ const v = expr(depth + 1);
4097
+ if (!isOp(take(), ")")) throw new Error("Invalid expression");
4098
+ return v;
4099
+ }
4100
+ throw new Error("Invalid expression");
4101
+ };
4102
+ const result = expr(0);
4103
+ if (i !== tokens.length) throw new Error("Invalid expression");
4104
+ if (!Number.isFinite(result)) throw new Error("Result is not a finite number");
4105
+ return result;
4106
+ }
4107
+ var HybridAgent = class {
4108
+ /**
4109
+ * @param {TraitOSClient} client
4110
+ * @param {string} agentId
4111
+ * @param {object} [options]
4112
+ * @param {Record<string, Function>} [options.localTools]
4113
+ * @param {Record<string, any>} [options.localMemory]
4114
+ */
4115
+ constructor(client, agentId, { localTools = {}, localMemory = {} } = {}) {
4116
+ this.client = client;
4117
+ this.agentId = agentId;
4118
+ this.localTools = {
4119
+ // Basic client-side math, evaluated by a small parser (no eval / Function).
4120
+ calculate: (args) => ({ result: safeCalculate(args == null ? void 0 : args.expression) }),
4121
+ ...localTools
4122
+ };
4123
+ this.localMemory = {
4124
+ preferences: [],
4125
+ ...localMemory
4126
+ };
4127
+ }
4128
+ /**
4129
+ * Set local memory value
4130
+ */
4131
+ setLocalMemory(type, value) {
4132
+ if (!this.localMemory[type]) {
4133
+ this.localMemory[type] = [];
4134
+ }
4135
+ this.localMemory[type].push({ text: value, timestamp: Date.now() });
4136
+ }
4137
+ /**
4138
+ * Execute chat prompts in Hybrid mode.
4139
+ * Decides whether to handle locally or delegate to the TraitOS Durable Object backend.
4140
+ */
4141
+ async chat(prompt, conversationId = "default", skillName = null) {
4142
+ const lowerPrompt = prompt.toLowerCase();
4143
+ const mathMatch = lowerPrompt.match(/(?:calculate|math|compute)\s+(.+)/);
4144
+ if (mathMatch && this.localTools.calculate) {
4145
+ try {
4146
+ const execution = this.localTools.calculate({ expression: mathMatch[1] });
4147
+ return {
4148
+ response: `[Local Hybrid Engine] I resolved this using your local hardware. Result: ${execution.result}`,
4149
+ source: "local_execution",
4150
+ toolUsed: "calculate"
4151
+ };
4152
+ } catch (err3) {
4153
+ }
4154
+ }
4155
+ if (lowerPrompt.includes("local preference") || lowerPrompt.includes("what do you remember about me")) {
4156
+ const prefs = this.localMemory.preferences.map((p) => p.text).join(", ");
4157
+ if (prefs) {
4158
+ return {
4159
+ response: `[Local Hybrid Engine] Reading from local memory: I remember that ${prefs}.`,
4160
+ source: "local_memory"
4161
+ };
4162
+ }
4163
+ }
4164
+ const remoteResponse = await this.client.agents.chat(this.agentId, prompt, conversationId, skillName);
4165
+ if (remoteResponse.response && (remoteResponse.response.includes("prefer") || remoteResponse.response.includes("always"))) {
4166
+ this.setLocalMemory("preferences", remoteResponse.response);
4167
+ }
4168
+ return {
4169
+ ...remoteResponse,
4170
+ source: "edge_delegation"
4171
+ };
4172
+ }
4173
+ };
4174
+
4175
+ // ../sdk/src/call.js
4176
+ var RANK = { idle: 0, connecting: 1, ringing: 2, active: 3, ended: 4 };
4177
+ var ANSWERED = /* @__PURE__ */ new Set(["connected", "active", "accepted", "connect", "answer", "answered", "in-call"]);
4178
+ var ENDED = /* @__PURE__ */ new Set(["completed", "stopped", "ended", "terminated", "hangup", "rejected", "missed", "canceled", "cancelled"]);
4179
+ function mapServerStatus(status, failureCode = null) {
4180
+ const s = String(status != null ? status : "").toLowerCase();
4181
+ if (!s) return null;
4182
+ if (failureCode === "call_permission_required") return { state: "ended", reason: "call_permission_required" };
4183
+ if (s === "ringing" || s === "in-progress" || s === "dialing") return { state: "ringing" };
4184
+ if (ANSWERED.has(s)) return { state: "active" };
4185
+ if (s === "failed") return { state: "ended", reason: "failed" };
4186
+ if (s === "no_answer" || s === "no-answer") return { state: "ended", reason: "no_answer" };
4187
+ if (ENDED.has(s)) return { state: "ended", reason: s === "completed" || s === "stopped" ? "completed" : s };
4188
+ return null;
4189
+ }
4190
+ var CallSession = class {
4191
+ /**
4192
+ * @param {import('./index.js').TraitOSClient} client
4193
+ * @param {{rtc?: {RTCPeerConnection: any, getUserMedia: () => Promise<any>, onRemoteStream?: (s: any) => void, iceServers?: any[]},
4194
+ * pollMs?: number, ringTimeoutSecs?: number, iceWaitMs?: number}} [options]
4195
+ */
4196
+ constructor(client, { rtc = null, pollMs = 2e3, ringTimeoutSecs = 45, iceWaitMs = 2e3 } = {}) {
4197
+ this.client = client;
4198
+ this.rtc = rtc;
4199
+ this.pollMs = pollMs;
4200
+ this.ringTimeoutSecs = ringTimeoutSecs;
4201
+ this.iceWaitMs = iceWaitMs;
4202
+ this.state = "idle";
4203
+ this.id = null;
4204
+ this.endReason = null;
4205
+ this.mode = "direct";
4206
+ this.muted = false;
4207
+ this.startedAt = null;
4208
+ this._listeners = /* @__PURE__ */ new Set();
4209
+ this._cancelled = false;
4210
+ this._pc = null;
4211
+ this._stream = null;
4212
+ this._poll = null;
4213
+ this._ringTimer = null;
4214
+ }
4215
+ /** Subscribe to state changes; returns an unsubscribe function. */
4216
+ on(event, fn) {
4217
+ if (event !== "state") throw new Error(`Unknown event: ${event}`);
4218
+ this._listeners.add(fn);
4219
+ return () => this._listeners.delete(fn);
4220
+ }
4221
+ snapshot() {
4222
+ return { state: this.state, id: this.id, mode: this.mode, muted: this.muted, endReason: this.endReason, startedAt: this.startedAt };
4223
+ }
4224
+ _emit() {
4225
+ for (const fn of [...this._listeners]) {
4226
+ try {
4227
+ fn(this.snapshot());
4228
+ } catch {
4229
+ }
4230
+ }
4231
+ }
4232
+ /** Move forward only. Returns true when the state changed. */
4233
+ _transition(state, reason = null) {
4234
+ var _a2;
4235
+ if (RANK[state] <= RANK[this.state]) return false;
4236
+ this.state = state;
4237
+ if (state === "active") {
4238
+ this.startedAt = (_a2 = this.startedAt) != null ? _a2 : Date.now();
4239
+ this._clearRingTimer();
4240
+ }
4241
+ if (state === "ended") {
4242
+ this.endReason = reason || "completed";
4243
+ this._cleanup();
4244
+ }
4245
+ this._emit();
4246
+ return true;
4247
+ }
4248
+ /** Feed a server event or status (WebSocket push, webhook, or the poll). Safe to call any number of times, in any order. */
4249
+ applyServerEvent(ev = {}) {
4250
+ var _a2, _b, _c, _d;
4251
+ if (ev.callId && this.id && ev.callId !== this.id) return false;
4252
+ const m = mapServerStatus((_b = (_a2 = ev.status) != null ? _a2 : ev.callState) != null ? _b : ev.state, (_d = (_c = ev.failureCode) != null ? _c : ev.failure_code) != null ? _d : null);
4253
+ return m ? this._transition(m.state, m.reason) : false;
4254
+ }
4255
+ async dial({ mode = "direct", ...options } = {}) {
4256
+ var _a2, _b, _c, _d, _e;
4257
+ if (this.state !== "idle") throw new Error("This session already placed a call; create a new CallSession.");
4258
+ if (mode !== "direct" && mode !== "agent-first") throw new Error("mode must be 'direct' or 'agent-first'");
4259
+ this.mode = mode;
4260
+ this._transition("connecting");
4261
+ try {
4262
+ const sdp = this.rtc && mode === "direct" ? await this._offer() : void 0;
4263
+ const res = await this.client.calls.create({
4264
+ ...options,
4265
+ channel: "whatsapp",
4266
+ softphoneFirst: mode === "agent-first",
4267
+ ...sdp ? { sdp, sdpType: "offer" } : {}
4268
+ });
4269
+ const id = (_d = (_c = (_a2 = res == null ? void 0 : res.id) != null ? _a2 : res == null ? void 0 : res.call_id) != null ? _c : (_b = res == null ? void 0 : res.data) == null ? void 0 : _b.id) != null ? _d : null;
4270
+ this.id = id;
4271
+ if (this._cancelled || this.state === "ended") {
4272
+ if (id) await this.client.calls.hangup(id).catch(() => {
4273
+ });
4274
+ return this.snapshot();
4275
+ }
4276
+ const answer = (_e = res == null ? void 0 : res.session) == null ? void 0 : _e.sdp;
4277
+ if (answer && this._pc) await this._pc.setRemoteDescription({ type: res.session.type || "answer", sdp: answer });
4278
+ this._transition("ringing");
4279
+ this._startPolling();
4280
+ this._startRingTimer();
4281
+ return this.snapshot();
4282
+ } catch (error) {
4283
+ this._transition("ended", "failed");
4284
+ throw error;
4285
+ }
4286
+ }
4287
+ async hangup(reason = "hangup") {
4288
+ this._cancelled = true;
4289
+ const id = this.id;
4290
+ this._transition("ended", reason);
4291
+ if (id) await this.client.calls.hangup(id).catch(() => {
4292
+ });
4293
+ }
4294
+ mute(muted = true) {
4295
+ var _a2, _b, _c;
4296
+ this.muted = Boolean(muted);
4297
+ for (const track of (_c = (_b = (_a2 = this._stream) == null ? void 0 : _a2.getAudioTracks) == null ? void 0 : _b.call(_a2)) != null ? _c : []) track.enabled = !this.muted;
4298
+ this._emit();
4299
+ }
4300
+ async _offer() {
4301
+ var _a2;
4302
+ const { RTCPeerConnection, getUserMedia, onRemoteStream, iceServers } = this.rtc;
4303
+ this._stream = await getUserMedia();
4304
+ const pc = new RTCPeerConnection(iceServers ? { iceServers } : void 0);
4305
+ this._pc = pc;
4306
+ for (const track of this._stream.getTracks()) pc.addTrack(track, this._stream);
4307
+ if (onRemoteStream) pc.ontrack = (e) => {
4308
+ var _a3;
4309
+ return onRemoteStream((_a3 = e.streams) == null ? void 0 : _a3[0]);
4310
+ };
4311
+ await pc.setLocalDescription(await pc.createOffer());
4312
+ await new Promise((resolve) => {
4313
+ var _a3;
4314
+ if (pc.iceGatheringState === "complete") return resolve();
4315
+ const done = () => {
4316
+ var _a4;
4317
+ clearTimeout(timer);
4318
+ (_a4 = pc.removeEventListener) == null ? void 0 : _a4.call(pc, "icegatheringstatechange", check);
4319
+ resolve();
4320
+ };
4321
+ const check = () => {
4322
+ if (pc.iceGatheringState === "complete") done();
4323
+ };
4324
+ const timer = setTimeout(done, this.iceWaitMs);
4325
+ (_a3 = pc.addEventListener) == null ? void 0 : _a3.call(pc, "icegatheringstatechange", check);
4326
+ });
4327
+ return (_a2 = pc.localDescription) == null ? void 0 : _a2.sdp;
4328
+ }
4329
+ _startPolling() {
4330
+ if (!this.id || this._poll || this.pollMs <= 0) return;
4331
+ this._poll = setInterval(async () => {
4332
+ if (this.state === "ended") return;
4333
+ const status = await this.client.calls.get(this.id).catch(() => null);
4334
+ if (status) this.applyServerEvent(status);
4335
+ }, this.pollMs);
4336
+ }
4337
+ // The no-answer timeout applies only to a call that is ringing, never to the dial request itself.
4338
+ _startRingTimer() {
4339
+ if (this.ringTimeoutSecs <= 0 || this.state !== "ringing") return;
4340
+ this._ringTimer = setTimeout(() => {
4341
+ if (this.state === "ringing") this.hangup("no_answer");
4342
+ }, this.ringTimeoutSecs * 1e3);
4343
+ }
4344
+ _clearRingTimer() {
4345
+ if (this._ringTimer) {
4346
+ clearTimeout(this._ringTimer);
4347
+ this._ringTimer = null;
4348
+ }
4349
+ }
4350
+ _cleanup() {
4351
+ var _a2, _b, _c, _d;
4352
+ this._clearRingTimer();
4353
+ if (this._poll) {
4354
+ clearInterval(this._poll);
4355
+ this._poll = null;
4356
+ }
4357
+ try {
4358
+ (_a2 = this._pc) == null ? void 0 : _a2.close();
4359
+ } catch {
4360
+ }
4361
+ for (const track of (_d = (_c = (_b = this._stream) == null ? void 0 : _b.getTracks) == null ? void 0 : _c.call(_b)) != null ? _d : []) {
4362
+ try {
4363
+ track.stop();
4364
+ } catch {
4365
+ }
4366
+ }
4367
+ this._pc = null;
4368
+ this._stream = null;
4369
+ }
4370
+ };
4371
+
4372
+ // ../sdk/src/index.js
4373
+ var DEFAULT_TIMEOUT_MS = 3e4;
4374
+ var DEFAULT_MAX_RETRIES = 2;
4375
+ var TraitOSClient = class _TraitOSClient {
4376
+ /**
4377
+ * @param {object} config
4378
+ * @param {string} [config.baseUrl] - Base URL of the TraitOS server (defaults to http://localhost:8788)
4379
+ * @param {string} [config.token] - A user token, an API key, or a browser token (see `auth.createBrowserToken`)
4380
+ * @param {number} [config.timeoutMs] - Give up on a request after this long (default 30000)
4381
+ * @param {number} [config.maxRetries] - Retries for failures that are safe to repeat (default 2; 0 turns retries off)
4382
+ * @param {boolean} [config.allowInsecureHttp] - Allow plain http to a non-loopback host (trusted networks only; default false)
4383
+ * @param {string|null} [config.apiVersion] - API version path (default 'v1'). `null` uses the original unversioned `/api`.
4384
+ * @param {string} [config.orgId] - Act inside this child organization (partner admins only). See `asOrg`.
4385
+ * @param {(ms: number) => Promise<void>} [config.sleep] - Replace the retry wait (for tests)
4386
+ */
4387
+ constructor({ baseUrl = "http://localhost:8788", token, timeoutMs = DEFAULT_TIMEOUT_MS, maxRetries = DEFAULT_MAX_RETRIES, allowInsecureHttp = false, apiVersion = "v1", orgId, sleep } = {}) {
4388
+ this.baseUrl = normalizeBaseUrl(baseUrl, { allowInsecureHttp });
4389
+ this.timeoutMs = timeoutMs;
4390
+ this.maxRetries = maxRetries;
4391
+ this.apiVersion = apiVersion;
4392
+ this.orgId = orgId != null ? orgId : null;
4393
+ Object.defineProperty(this, "_config", { value: { baseUrl: this.baseUrl, timeoutMs, maxRetries, allowInsecureHttp, apiVersion, sleep }, enumerable: false });
4394
+ Object.defineProperty(this, "token", { value: token, writable: true, enumerable: false, configurable: true });
4395
+ const transport = createTransport({
4396
+ baseUrl: this.baseUrl,
4397
+ apiPath: apiVersion ? `/api/${apiVersion}` : "/api",
4398
+ getToken: () => this.token,
4399
+ timeoutMs,
4400
+ maxRetries,
4401
+ headers: orgId ? { "X-TraitOS-Org-Id": String(orgId) } : void 0,
4402
+ sleep
4403
+ });
4404
+ Object.defineProperty(this, "_request", { value: transport, enumerable: false });
4405
+ Object.defineProperty(this, "_open", { value: transport.raw, enumerable: false });
4406
+ this.auth = auth(this);
4407
+ this.agents = agents(this);
4408
+ this.skills = skills(this);
4409
+ this.tasks = tasks(this);
4410
+ this.approvals = approvals2(this);
4411
+ this.reports = reports(this);
4412
+ this.evals = evals(this);
4413
+ this.usage = usage2(this);
4414
+ this.handoffs = handoffs(this);
4415
+ this.calls = calls(this);
4416
+ this.whatsapp = whatsapp(this);
4417
+ this.phoneNumbers = phoneNumbers(this);
4418
+ this.softphone = softphone(this);
4419
+ this.flows = flows(this);
4420
+ this.sms = sms(this);
4421
+ this.knowledge = knowledge(this);
4422
+ this.contacts = contacts(this);
4423
+ this.larynx = larynx(this);
4424
+ this.events = events(this);
4425
+ this.webhooks = webhooks(this);
4426
+ this.apiKeys = apiKeys(this);
4427
+ this.partners = partners(this);
4428
+ this.whatsappCalls = whatsappCalls(this);
4429
+ this.phoneCalls = phoneCalls(this);
4430
+ }
4431
+ /** Set/update the authentication token. */
4432
+ setToken(token) {
4433
+ this.token = token;
4434
+ }
4435
+ /**
4436
+ * A client that acts inside one of your child organizations, with the same credentials. Only a partner admin's token may do this,
4437
+ * and only for its own children; the server refuses anything else. The new client copies the token as it is now.
4438
+ * const tenant = client.asOrg('org_abc123');
4439
+ * await tenant.agents.list();
4440
+ * @param {string} orgId
4441
+ */
4442
+ asOrg(orgId) {
4443
+ if (!orgId || typeof orgId !== "string") throw new TypeError("asOrg(orgId) needs a child organization id");
4444
+ return new _TraitOSClient({ ...this._config, token: this.token, orgId });
4445
+ }
4446
+ /**
4447
+ * Create a new Hybrid Client-Side Agent
4448
+ * @param {string} agentId
4449
+ * @param {object} [options]
4450
+ */
4451
+ createHybridAgent(agentId, options = {}) {
4452
+ return new HybridAgent(this, agentId, options);
4453
+ }
4454
+ };
4455
+
4456
+ // src/browser.js
4457
+ var _a;
4458
+ if (typeof window !== "undefined") {
4459
+ window.TraitOSUI = index_exports;
4460
+ window.TraitOS = { ...(_a = window.TraitOS) != null ? _a : {}, ...src_exports };
4461
+ }
4462
+ })();