@nac3/runtime 2.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,708 @@
1
+ // Generated by build.mjs -- do not edit. Source: yujin.app/nac-spec/js/nac-chat-client.js
2
+ const _g = typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : {});
3
+ /* ===============================================================
4
+ nac-chat-client.js -- self-contained NAC chat client.
5
+
6
+ Drop-in for any NAC v2.1 page that wants to operate the UI
7
+ via the Yujin LLM intermediary backend (Claude Sonnet primary
8
+ / DeepSeek fallback) with text + voice.
9
+
10
+ Provides:
11
+ - Backend POST to /crm/api/v1/yujin/nac-demo
12
+ - User + bot bubble rendering
13
+ - Half-duplex TTS<->STT (fix C1)
14
+ - STT debounce (fix C5)
15
+ - Locale switch pre-filter (fix C7-bis)
16
+ - Confirm-dialog YES/NO routing (fix C3)
17
+ - Dispatcher for the 8 v2.0 kinds + 9 v2.1 data-table kinds
18
+
19
+ Public API:
20
+ NacChat.init({
21
+ endpoint: '/crm/api/v1/yujin/nac-demo',
22
+ sessionId: 'optional-string',
23
+ lang: 'es',
24
+ chatLog: HTMLElement, // <ol> or <div> for bubbles
25
+ input: HTMLInputElement, // text entry
26
+ sendBtn: HTMLElement, // optional
27
+ micBtn: HTMLElement, // optional, push-to-talk
28
+ handsFreeBtn: HTMLElement, // optional, always-on toggle
29
+ ttsBtn: HTMLElement, // optional, TTS toggle
30
+ langSelect:HTMLSelectElement // optional
31
+ })
32
+ NacChat.send(text)
33
+ NacChat.botSpeak(text)
34
+ NacChat.setLang(code)
35
+ NacChat.snapshotTree() // returns the tree posted to backend
36
+ NacChat.onAction(kind, fn) // override or extend a kind handler
37
+
38
+ ASCII-only.
39
+ =============================================================== */
40
+ (function (global) {
41
+ 'use strict';
42
+
43
+ var NacChat = {
44
+ _endpoint: '/crm/api/v1/yujin/nac-demo',
45
+ _sessionId: 'sess_' + Math.random().toString(36).slice(2, 10),
46
+ _lang: 'es',
47
+ _ttsEnabled: true,
48
+ _voiceAlwaysOn: false,
49
+ _history: [],
50
+ _chatLog: null,
51
+ _input: null,
52
+ _langSelect:null,
53
+ _customHandlers: Object.create(null),
54
+ _ttsBusyUntil: 0,
55
+ _ttsRecentBuf: [],
56
+ _TTS_RECENT_MAX: 8,
57
+ _TTS_RECENT_TTL_MS: 30000,
58
+ _sttBuffer: '',
59
+ _sttFlushTimer: null,
60
+ _STT_SILENCE_MS: 1100,
61
+ _recognizer: null
62
+ };
63
+
64
+ /* ---------- BCP47 locale map for STT/TTS ---------- */
65
+ var TTS_BCP47 = {
66
+ es: 'es-ES', en: 'en-US', pt: 'pt-BR', fr: 'fr-FR', it: 'it-IT',
67
+ de: 'de-DE', ja: 'ja-JP', zh: 'zh-CN', hi: 'hi-IN', ar: 'ar-SA'
68
+ };
69
+
70
+ /* ---------- locale switch dictionary (fix C7-bis) ---------- */
71
+ var LOCALE_NAMES = {
72
+ 'espanol': 'es', 'castellano': 'es', 'spanish': 'es', 'espanhol': 'es', 'espagnol': 'es', 'spanisch': 'es', 'spagnolo': 'es',
73
+ 'ingles': 'en', 'english': 'en', 'ingles_pt': 'en', 'inglese': 'en', 'englisch': 'en', 'anglais': 'en', 'ingles_pt2': 'en',
74
+ 'portugues':'pt','portuguese':'pt','portugais':'pt','portoghese':'pt','portugiesisch':'pt',
75
+ 'frances': 'fr', 'french': 'fr', 'francese': 'fr', 'franzosisch': 'fr',
76
+ 'italiano':'it', 'italian': 'it', 'italien': 'it', 'italienisch': 'it',
77
+ 'aleman': 'de', 'german': 'de', 'allemand': 'de', 'deutsch': 'de', 'tedesco': 'de', 'alemao': 'de',
78
+ 'japones': 'ja', 'japanese': 'ja', 'japonais': 'ja', 'giapponese': 'ja',
79
+ 'chino': 'zh', 'chinese': 'zh', 'chinois': 'zh', 'cinese': 'zh',
80
+ 'hindi': 'hi',
81
+ 'arabe': 'ar', 'arabic': 'ar', 'arabo': 'ar',
82
+ 'es': 'es', 'en': 'en', 'pt': 'pt', 'fr': 'fr', 'it': 'it',
83
+ 'de': 'de', 'ja': 'ja', 'zh': 'zh', 'hi': 'hi', 'ar': 'ar'
84
+ };
85
+ var LOCALE_SWITCH_VERB = /\b(cambia|cambiar|cambialo|cambiame|switch|change|use|using|set|pon|poner|usa|usar|wechseln|cambiare|mudar?|changer|to)\b/;
86
+ var LOCALE_TRIGGER = /\b(idioma|language|sprache|lingua|langue)\b/;
87
+
88
+ function _normalizeForFilter(s) {
89
+ return String(s || '').toLowerCase()
90
+ .normalize('NFD')
91
+ .replace(/[̀-ͯ]/g, '')
92
+ .replace(/[^a-z0-9\s]/g, ' ')
93
+ .replace(/\s+/g, ' ')
94
+ .trim();
95
+ }
96
+ function _detectLangSwitch(text) {
97
+ /* Bare 2-letter locale codes ('de','es','en',...) collide with
98
+ common words/prepositions in several languages: 'de' is the
99
+ Spanish/Portuguese preposition, 'es' is German "is", 'en' is
100
+ Spanish "in", etc. Accept them only when an explicit
101
+ LOCALE_TRIGGER ('idioma'/'language'/'sprache'/...) is also
102
+ present; full names ('espanol','deutsch','english') keep
103
+ working with just a switch verb. Fixes "cambia de pestana"
104
+ and "cambia precio de mouse 40" being misrouted to German.
105
+ Pablo report 2026-05-09. */
106
+ var norm = _normalizeForFilter(text);
107
+ if (!norm) return null;
108
+ var hasVerb = LOCALE_SWITCH_VERB.test(norm);
109
+ var hasTrigger = LOCALE_TRIGGER.test(norm);
110
+ var tokens = norm.split(' ').filter(Boolean);
111
+ var found = null;
112
+ var foundIs2Letter = false;
113
+ for (var i = 0; i < tokens.length; i++) {
114
+ var tok = tokens[i];
115
+ if (!LOCALE_NAMES[tok]) continue;
116
+ var is2 = tok.length === 2;
117
+ if (is2 && !hasTrigger) continue;
118
+ found = LOCALE_NAMES[tok];
119
+ foundIs2Letter = is2;
120
+ break;
121
+ }
122
+ if (!found) return null;
123
+ if (hasVerb || hasTrigger) return found;
124
+ if (tokens.length <= 3 && !foundIs2Letter) return found;
125
+ return null;
126
+ }
127
+
128
+ /* ---------- TTS feedback filter (fix C1) ---------- */
129
+ function _ttsRememberUtterance(text) {
130
+ if (!text) return;
131
+ NacChat._ttsRecentBuf.push({
132
+ norm: _normalizeForFilter(text),
133
+ ts: Date.now()
134
+ });
135
+ while (NacChat._ttsRecentBuf.length > NacChat._TTS_RECENT_MAX) {
136
+ NacChat._ttsRecentBuf.shift();
137
+ }
138
+ }
139
+ function _isBotEcho(text) {
140
+ if (!text) return false;
141
+ var norm = _normalizeForFilter(text);
142
+ if (!norm) return false;
143
+ var now = Date.now();
144
+ while (NacChat._ttsRecentBuf.length
145
+ && now - NacChat._ttsRecentBuf[0].ts > NacChat._TTS_RECENT_TTL_MS) {
146
+ NacChat._ttsRecentBuf.shift();
147
+ }
148
+ for (var i = 0; i < NacChat._ttsRecentBuf.length; i++) {
149
+ var entry = NacChat._ttsRecentBuf[i].norm;
150
+ if (!entry) continue;
151
+ if (entry === norm) return true;
152
+ if (entry.length > 8 && entry.indexOf(norm) >= 0) return true;
153
+ if (norm.length > 8 && norm.indexOf(entry) >= 0) return true;
154
+ var a = entry.split(' '), b = norm.split(' ');
155
+ if (a.length >= 3 && b.length >= 3) {
156
+ var setA = new Set(a), hit = 0;
157
+ for (var k = 0; k < b.length; k++) if (setA.has(b[k])) hit++;
158
+ if (hit / Math.max(a.length, b.length) >= 0.7) return true;
159
+ }
160
+ }
161
+ return false;
162
+ }
163
+
164
+ /* ---------- DOM helpers ---------- */
165
+ function $(sel, root) { return (root || document).querySelector(sel); }
166
+ function _bubble(role, text) {
167
+ if (!NacChat._chatLog) return;
168
+ var li = document.createElement('div');
169
+ li.className = 'nac-chat-bubble ' + role;
170
+ li.textContent = text;
171
+ NacChat._chatLog.appendChild(li);
172
+ NacChat._chatLog.scrollTop = NacChat._chatLog.scrollHeight;
173
+ }
174
+
175
+ /* ---------- TTS ---------- */
176
+ function botSpeak(text, opts) {
177
+ opts = opts || {};
178
+ if (!opts.skipBubble) _bubble('bot', text);
179
+ _ttsRememberUtterance(text);
180
+ if (!NacChat._ttsEnabled || !('speechSynthesis' in window)) return;
181
+ try {
182
+ var u = new SpeechSynthesisUtterance(text);
183
+ u.lang = TTS_BCP47[NacChat._lang] || 'en-US';
184
+ u.rate = 1.05; u.pitch = 1.0;
185
+ var charsPerSec = 14;
186
+ var estMs = Math.max(800, Math.round((text.length / charsPerSec) * 1500));
187
+ NacChat._ttsBusyUntil = Math.max(NacChat._ttsBusyUntil, Date.now()) + estMs;
188
+ u.onend = function () { NacChat._ttsBusyUntil = Date.now(); };
189
+ u.onerror = function () { NacChat._ttsBusyUntil = Date.now(); };
190
+ window.speechSynthesis.speak(u);
191
+ } catch (e) { /* swallow; TTS best-effort */ }
192
+ }
193
+ NacChat.botSpeak = botSpeak;
194
+
195
+ /* ---------- Confirm-dialog YES/NO routing (fix C3) ---------- */
196
+ function _findPendingConfirm() {
197
+ return document.querySelector(
198
+ '[data-nac-role="confirm-dialog"][data-nac-state="pending"]');
199
+ }
200
+ function _maybeAnswerPendingConfirm(rawText) {
201
+ var dialog = _findPendingConfirm();
202
+ if (!dialog) return false;
203
+ var id = dialog.getAttribute('data-nac-id');
204
+ var norm = _normalizeForFilter(rawText);
205
+ var tokens = norm.split(' ').filter(Boolean);
206
+ var YES = ['si','yes','ya','oui','ja','sim','hai','ok','okay','aprobar','aprob','confirmar','confirma','confirmo','dale','adelante'];
207
+ var NO = ['no','nope','non','nein','nao','iie','la','cancel','cancela','cancelar','cancelo','aborta','abortar','para'];
208
+ function hit(arr) { for (var i = 0; i < tokens.length; i++) if (arr.indexOf(tokens[i]) >= 0) return true; return false; }
209
+ var isYes = hit(YES), isNo = hit(NO);
210
+ if (!isYes && !isNo) return false;
211
+ var btn = document.querySelector('[data-nac-id="' + id + (isYes ? '.confirm' : '.cancel') + '"]');
212
+ if (!btn) return false;
213
+ btn.click();
214
+ botSpeak(isYes ? 'Confirmado.' : 'Cancelado.', { skipBubble: true });
215
+ return true;
216
+ }
217
+ document.addEventListener('nac:confirm:requested', function (e) {
218
+ try {
219
+ var prompt = (e && e.detail && e.detail.prompt) || '';
220
+ if (!prompt) return;
221
+ var hints = {
222
+ es: 'Decime si o no.', en: 'Say yes or no.', pt: 'Diga sim ou nao.',
223
+ fr: 'Dites oui ou non.', it: 'Dimmi si o no.', de: 'Sag ja oder nein.',
224
+ ja: 'はい か いいえ で答えて。', zh: '请说 是 或 否。',
225
+ hi: 'haan ya nahin.', ar: 'قل نعم او لا.'
226
+ };
227
+ botSpeak(prompt + ' ' + (hints[NacChat._lang] || hints.es), { skipBubble: true });
228
+ } catch (_) {}
229
+ }, true);
230
+
231
+ /* ---------- Locale switch (fix C7-bis) ---------- */
232
+ function _maybeChangeLocaleLocally(text) {
233
+ var code = _detectLangSwitch(text);
234
+ if (!code) return false;
235
+ /* Caller paints the user bubble BEFORE invoking us so the
236
+ visual order is "user said X" -> "bot replies Y". The
237
+ previous version painted the bot bubble inside this
238
+ function and the user bubble after it, producing the
239
+ ack-before-prompt visual bug Pablo reported on
240
+ 2026-05-09. */
241
+ if (code === NacChat._lang) {
242
+ botSpeak('Ya estoy en ese idioma.');
243
+ return true;
244
+ }
245
+ NacChat.setLang(code);
246
+ var ack = {
247
+ es: 'Cambie a espanol.', en: 'Switched to English.',
248
+ pt: 'Mudei para portugues.', fr: 'Bascule en francais.',
249
+ it: 'Sono passato all italiano.', de: 'Auf Deutsch umgestellt.',
250
+ ja: '日本語に切り替えました。', zh: '已切换到中文。',
251
+ hi: 'Hindi mein switch kar diya.', ar: 'تم التغيير الى العربية.'
252
+ };
253
+ botSpeak(ack[code] || ('Switched to ' + code + '.'));
254
+ return true;
255
+ }
256
+
257
+ /* ---------- Snapshot ---------- */
258
+ NacChat.snapshotTree = function () {
259
+ if (!global.NAC || typeof global.NAC.describe !== 'function') return null;
260
+ try {
261
+ var snap = global.NAC.describe();
262
+ var plugins = (snap.plugins || []).map(function (p) {
263
+ var m = null;
264
+ try {
265
+ if (typeof global.NAC.manifest === 'function' && p && p.plugin) {
266
+ m = global.NAC.manifest(p.plugin);
267
+ }
268
+ } catch (_) {}
269
+ return {
270
+ plugin: p.plugin || '',
271
+ state: p.state || '',
272
+ elements: p.elements || [],
273
+ manifest: m || null
274
+ };
275
+ });
276
+ var out = { active: snap.active || null, plugins: plugins };
277
+ try {
278
+ if (typeof global.NAC.describe_v2 === 'function') {
279
+ var v2 = global.NAC.describe_v2();
280
+ if (v2) {
281
+ out.v2_scope_entries = v2.v2_scope_entries || [];
282
+ out.sitemap = v2.sitemap || null;
283
+ out.tenant_prefix = v2.tenant_prefix || null;
284
+ out.nac_version_v2 = v2.nac_version || null;
285
+ out.data_tables = v2.data_tables || [];
286
+ }
287
+ }
288
+ } catch (_) {}
289
+ console.log('[nac-chat] snapshot plugins (' + plugins.length + '):',
290
+ plugins.map(function (p) { return p.plugin; }).join(', '));
291
+ if (out.data_tables && out.data_tables.length) {
292
+ console.log('[nac-chat] data_tables:',
293
+ out.data_tables.map(function (t) {
294
+ return t.table_id + ' (' + t.subkind + ')';
295
+ }).join(', '));
296
+ }
297
+ return out;
298
+ } catch (e) {
299
+ console.warn('[nac-chat] snapshot failed:', e && e.message);
300
+ return null;
301
+ }
302
+ };
303
+
304
+ /* ---------- Direct DOM dispatch helpers ---------- */
305
+ /* These bypass NAC.click() / NAC.fill() polling for
306
+ nac:action:succeeded so demos and brownfield adopters that
307
+ have not wired the ack event on every handler still work
308
+ end-to-end. The host is still responsible for the side
309
+ effect; we just don't wait for the conformance ack. */
310
+ function _directClick(nacId) {
311
+ if (!nacId) throw new Error('click: nac_id required');
312
+ var el = document.querySelector('[data-nac-id="' + nacId + '"]');
313
+ if (!el) throw new Error('click: element not found ' + nacId);
314
+ try { el.click(); return { ok: true, dispatched: 'direct' }; }
315
+ catch (e) { throw new Error('click threw: ' + (e && e.message)); }
316
+ }
317
+ function _directClickByVerb(plugin, verb) {
318
+ if (!verb) throw new Error('click_by_verb: verb required');
319
+ /* Resolve verb -> nac_id by walking the v1 manifest cache.
320
+ NAC.manifest(plugin) returns {actions:[{verb, nac_id}]}. */
321
+ var manifest = null;
322
+ try { if (typeof global.NAC.manifest === 'function') manifest = global.NAC.manifest(plugin); }
323
+ catch (_) {}
324
+ var actions = manifest && manifest.actions || [];
325
+ var match = actions.filter(function (a) { return a && a.verb === verb; })[0];
326
+ var nacId = match && (match.nac_id || match.id);
327
+ if (!nacId) {
328
+ /* Fallback: walk the DOM looking for an element under this
329
+ plugin whose data-nac-action matches the verb. */
330
+ var root = plugin
331
+ ? document.querySelector('[data-nac-plugin="' + plugin + '"]')
332
+ : document;
333
+ var hit = root && root.querySelector('[data-nac-action="' + verb + '"][data-nac-id]');
334
+ if (!hit) throw new Error('click_by_verb: no nac_id for verb=' + verb + ' plugin=' + plugin);
335
+ try { hit.click(); return { ok: true, dispatched: 'direct_dom_walk' }; }
336
+ catch (e) { throw new Error('click_by_verb threw: ' + e.message); }
337
+ }
338
+ return _directClick(nacId);
339
+ }
340
+ function _directFill(nacId, value) {
341
+ if (!nacId) throw new Error('fill: nac_id required');
342
+ var el = document.querySelector('[data-nac-id="' + nacId + '"]');
343
+ if (!el) throw new Error('fill: element not found ' + nacId);
344
+ try {
345
+ el.focus();
346
+ el.value = value == null ? '' : String(value);
347
+ el.dispatchEvent(new Event('input', { bubbles: true }));
348
+ el.dispatchEvent(new Event('change', { bubbles: true }));
349
+ return { ok: true };
350
+ } catch (e) { throw new Error('fill threw: ' + e.message); }
351
+ }
352
+ function _directSelect(nacId, value) {
353
+ if (!nacId) throw new Error('select: nac_id required');
354
+ var el = document.querySelector('[data-nac-id="' + nacId + '"]');
355
+ if (!el) throw new Error('select: element not found ' + nacId);
356
+ try {
357
+ if (el.tagName === 'SELECT') {
358
+ el.value = value;
359
+ el.dispatchEvent(new Event('change', { bubbles: true }));
360
+ } else {
361
+ /* radio/checkbox: find the option with matching value */
362
+ var opt = el.querySelector('[value="' + value + '"]');
363
+ if (opt) {
364
+ opt.checked = true;
365
+ opt.dispatchEvent(new Event('change', { bubbles: true }));
366
+ } else {
367
+ el.value = value;
368
+ el.dispatchEvent(new Event('change', { bubbles: true }));
369
+ }
370
+ }
371
+ return { ok: true };
372
+ } catch (e) { throw new Error('select threw: ' + e.message); }
373
+ }
374
+
375
+ /* ---------- Backend dispatch ---------- */
376
+ async function _backendCall(text) {
377
+ var snap = NacChat.snapshotTree();
378
+ var body = {
379
+ session_id: NacChat._sessionId,
380
+ prompt: text,
381
+ lang: NacChat._lang,
382
+ history: NacChat._history.slice(-8),
383
+ nac_tree: snap
384
+ };
385
+ try {
386
+ var resp = await fetch(NacChat._endpoint, {
387
+ method: 'POST',
388
+ headers: { 'Content-Type': 'application/json' },
389
+ body: JSON.stringify(body)
390
+ });
391
+ if (!resp.ok) {
392
+ return { ok: false, error: 'http_' + resp.status };
393
+ }
394
+ var json = await resp.json();
395
+ return json && json.ok !== false ? { ok: true, data: json } : { ok: false, error: (json && json.error) || 'backend_error' };
396
+ } catch (e) {
397
+ return { ok: false, error: 'fetch_' + (e && e.message || 'unknown') };
398
+ }
399
+ }
400
+
401
+ /* ---------- Action dispatcher ---------- */
402
+ async function _dispatchAction(a) {
403
+ if (NacChat._customHandlers[a.kind]) {
404
+ return await NacChat._customHandlers[a.kind](a);
405
+ }
406
+ if (!global.NAC) throw new Error('NAC runtime missing');
407
+ switch (a.kind) {
408
+ case 'click':
409
+ /* 2026-05-09 fix: NAC.click() polls for nac:action:
410
+ succeeded with a 5s timeout. Many demos / adopters
411
+ do not wire that ack event on every handler, so the
412
+ click visually executes (modal opens, button fires)
413
+ but the promise rejects on timeout and the chat
414
+ reports 'action failed'. We dispatch the DOM click
415
+ directly here -- the side effect happens; ack is
416
+ best-effort. Spec sec 18 requires the ack only at
417
+ NAC-3 conformance level. */
418
+ return _directClick(a.nac_id);
419
+ case 'click_by_verb':
420
+ /* Same reasoning. We resolve verb -> nac_id locally
421
+ then dispatch the DOM click directly. */
422
+ return _directClickByVerb(a.plugin || null, a.verb);
423
+ case 'fill':
424
+ return _directFill(a.nac_id, a.value);
425
+ case 'select':
426
+ return _directSelect(a.nac_id, a.value);
427
+ case 'tab': return await global.NAC.tab(a.plugin, a.tab_key);
428
+ case 'tab_by_label': return await global.NAC.tab_by_label(a.plugin || null, a.label);
429
+ case 'drag_drop': return await global.NAC.drag_drop(a.nac_id, a.target_nac_id,
430
+ typeof a.to_index === 'number' ? { to_index: a.to_index } : undefined);
431
+ case 'go_to_section': return await global.NAC.go_to_section(a.nac_id);
432
+ case 'say': if (a.text) botSpeak(a.text); return { ok: true };
433
+ case 'change_locale':
434
+ if (typeof a.locale === 'string' && a.locale.length === 2) {
435
+ NacChat.setLang(a.locale);
436
+ return { ok: true };
437
+ }
438
+ throw new Error('change_locale: missing locale');
439
+ /* v2.1 sec 18 */
440
+ case 'dt_add_row': {
441
+ if (typeof global.NAC.dt_add_row !== 'function') throw new Error('dt_add_row missing -- runtime older than v2.1');
442
+ var r = global.NAC.dt_add_row(a.table_id, a.values || {});
443
+ if (r && r.ok === false) throw new Error('dt_add_row: ' + r.error + (r.column ? ' (' + r.column + ')' : ''));
444
+ return { ok: true, row_id: r && r.row_id };
445
+ }
446
+ case 'dt_remove_row':
447
+ if (typeof global.NAC.dt_remove_row !== 'function') throw new Error('dt_remove_row missing');
448
+ global.NAC.dt_remove_row(a.table_id, a.row_id); return { ok: true };
449
+ case 'dt_edit_cell': {
450
+ if (typeof global.NAC.dt_edit_cell !== 'function') throw new Error('dt_edit_cell missing');
451
+ var r2 = global.NAC.dt_edit_cell(a.table_id, a.row_id, a.column, a.value);
452
+ if (r2 && r2.ok === false) throw new Error('dt_edit_cell: ' + r2.error);
453
+ return { ok: true };
454
+ }
455
+ case 'dt_set_cell': {
456
+ if (typeof global.NAC.dt_set_cell !== 'function') throw new Error('dt_set_cell missing');
457
+ var r3 = global.NAC.dt_set_cell(a.table_id, a.row, a.col, a.value);
458
+ if (r3 && r3.ok === false) throw new Error('dt_set_cell: ' + r3.error);
459
+ return { ok: true };
460
+ }
461
+ case 'dt_select':
462
+ if (typeof global.NAC.dt_select !== 'function') throw new Error('dt_select missing');
463
+ return global.NAC.dt_select(a.table_id, a.target);
464
+ case 'dt_commit': {
465
+ if (typeof global.NAC.dt_commit !== 'function') throw new Error('dt_commit missing');
466
+ var rc = global.NAC.dt_commit(a.table_id);
467
+ if (rc && rc.ok === false) {
468
+ throw new Error('dt_commit blocked: ' +
469
+ (rc.errors || []).map(function (e) { return e.code; }).join(', '));
470
+ }
471
+ return { ok: true, final_state: rc && rc.final_state };
472
+ }
473
+ case 'dt_discard':
474
+ if (typeof global.NAC.dt_discard !== 'function') throw new Error('dt_discard missing');
475
+ global.NAC.dt_discard(a.table_id); return { ok: true };
476
+ case 'dt_read_aggregate':
477
+ if (typeof global.NAC.dt_read_aggregate !== 'function') throw new Error('dt_read_aggregate missing');
478
+ return { ok: true, value: global.NAC.dt_read_aggregate(a.table_id, a.agg_key, a.column) };
479
+ default:
480
+ throw new Error('unknown action kind: ' + a.kind);
481
+ }
482
+ }
483
+
484
+ /* ---------- Send pipeline ---------- */
485
+ NacChat.send = async function (text) {
486
+ text = (text || '').trim();
487
+ if (!text) return;
488
+ /* TTS interrupt: a fresh user turn cancels pending bot speech. */
489
+ if ('speechSynthesis' in window) {
490
+ try { window.speechSynthesis.cancel(); } catch (_) {}
491
+ NacChat._ttsBusyUntil = 0;
492
+ }
493
+ /* Paint the user bubble FIRST so visual order is always
494
+ "user said X" -> "bot replies Y", regardless of whether
495
+ the path is local short-circuit or backend round-trip. */
496
+ _bubble('user', text);
497
+ /* Short-circuits BEFORE the LLM round-trip. */
498
+ if (_maybeAnswerPendingConfirm(text)) { return; }
499
+ if (_maybeChangeLocaleLocally(text)) { return; }
500
+
501
+ NacChat._history.push({ role: 'user', text: text });
502
+
503
+ var resp = await _backendCall(text);
504
+ if (!resp.ok) {
505
+ botSpeak('Falla del backend: ' + resp.error);
506
+ return;
507
+ }
508
+ var d = resp.data;
509
+ /* Prefer the structured shape {message, actions[]} but be
510
+ tolerant to legacy shapes that returned only {reply} or
511
+ a single action. */
512
+ var message = d.message || d.reply || '';
513
+ var actions = Array.isArray(d.actions) ? d.actions : (d.action ? [d.action] : []);
514
+ /* 2026-05-09 diagnostic: log EXACTLY what the backend
515
+ returned so 'chat says X but nothing happens' is
516
+ distinguishable from 'chat dispatched X but it failed
517
+ silently'. If the LLM only emits a {message} with no
518
+ actions, this log makes it obvious. */
519
+ console.log('[nac-chat] backend response: message="' + message
520
+ + '" actions=' + JSON.stringify(actions));
521
+ if (message) {
522
+ _bubble('bot', message);
523
+ _ttsRememberUtterance(message);
524
+ if (NacChat._ttsEnabled && 'speechSynthesis' in window) {
525
+ try {
526
+ var u = new SpeechSynthesisUtterance(message);
527
+ u.lang = TTS_BCP47[NacChat._lang] || 'en-US'; u.rate = 1.05;
528
+ window.speechSynthesis.speak(u);
529
+ } catch (_) {}
530
+ }
531
+ NacChat._history.push({ role: 'assistant', text: message });
532
+ }
533
+ for (var i = 0; i < actions.length; i++) {
534
+ try {
535
+ await _dispatchAction(actions[i]);
536
+ } catch (e) {
537
+ console.warn('[nac-chat] action failed:', actions[i], e && e.message);
538
+ _bubble('bot', 'No pude ejecutar: ' + (e && e.message || e));
539
+ }
540
+ }
541
+ };
542
+
543
+ /* ---------- STT ---------- */
544
+ function _ensureRecognizer() {
545
+ if (NacChat._recognizer) return NacChat._recognizer;
546
+ var Cls = window.SpeechRecognition || window.webkitSpeechRecognition;
547
+ if (!Cls) return null;
548
+ var r = new Cls();
549
+ r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
550
+ r.continuous = false;
551
+ r.interimResults = true;
552
+ function flushBuffer() {
553
+ var text = (NacChat._sttBuffer || '').trim();
554
+ NacChat._sttBuffer = '';
555
+ if (NacChat._sttFlushTimer) { clearTimeout(NacChat._sttFlushTimer); NacChat._sttFlushTimer = null; }
556
+ if (!text) return;
557
+ if (_isBotEcho(text)) {
558
+ console.log('[nac-chat-stt] dropping bot-echo:', text);
559
+ return;
560
+ }
561
+ if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
562
+ console.log('[nac-chat-stt] dropping during TTS:', text);
563
+ return;
564
+ }
565
+ NacChat.send(text);
566
+ }
567
+ r.onresult = function (e) {
568
+ if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
569
+ return; /* half-duplex */
570
+ }
571
+ for (var i = e.resultIndex; i < e.results.length; i++) {
572
+ var res = e.results[i];
573
+ if (!res.isFinal) continue;
574
+ var txt = (res[0] && res[0].transcript || '').trim();
575
+ if (!txt) continue;
576
+ NacChat._sttBuffer = NacChat._sttBuffer ? (NacChat._sttBuffer + ' ' + txt) : txt;
577
+ if (NacChat._sttFlushTimer) clearTimeout(NacChat._sttFlushTimer);
578
+ NacChat._sttFlushTimer = setTimeout(flushBuffer, NacChat._STT_SILENCE_MS);
579
+ }
580
+ };
581
+ r.onend = function () {
582
+ if (NacChat._voiceAlwaysOn) {
583
+ try {
584
+ r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
585
+ r.continuous = true;
586
+ r.start();
587
+ return;
588
+ } catch (_) {}
589
+ }
590
+ _setMicState('idle');
591
+ };
592
+ r.onerror = function (e) {
593
+ var fatal = e.error === 'not-allowed' || e.error === 'service-not-allowed';
594
+ if (NacChat._voiceAlwaysOn && !fatal) return;
595
+ botSpeak('Mic error: ' + e.error, { skipBubble: true });
596
+ _setMicState('idle');
597
+ };
598
+ NacChat._recognizer = r;
599
+ return r;
600
+ }
601
+ function _setMicState(state) {
602
+ if (!NacChat._micBtn) return;
603
+ NacChat._micBtn.setAttribute('data-nac-state', state);
604
+ NacChat._micBtn.setAttribute('aria-pressed', state === 'active' ? 'true' : 'false');
605
+ }
606
+
607
+ function _toggleMic() {
608
+ var r = _ensureRecognizer();
609
+ if (!r) { botSpeak('Tu navegador no soporta speech recognition.'); return; }
610
+ if (NacChat._micBtn && NacChat._micBtn.getAttribute('data-nac-state') === 'active') {
611
+ try { r.stop(); } catch (_) {}
612
+ _setMicState('idle');
613
+ } else {
614
+ try {
615
+ r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
616
+ r.continuous = !!NacChat._voiceAlwaysOn;
617
+ r.start();
618
+ _setMicState('active');
619
+ } catch (e) {
620
+ console.warn('[nac-chat-stt] start failed:', e);
621
+ }
622
+ }
623
+ }
624
+ function _toggleHandsFree() {
625
+ NacChat._voiceAlwaysOn = !NacChat._voiceAlwaysOn;
626
+ if (NacChat._handsFreeBtn) {
627
+ NacChat._handsFreeBtn.setAttribute('aria-pressed', NacChat._voiceAlwaysOn ? 'true' : 'false');
628
+ NacChat._handsFreeBtn.setAttribute('data-nac-state', NacChat._voiceAlwaysOn ? 'active' : 'idle');
629
+ }
630
+ if (NacChat._voiceAlwaysOn) {
631
+ _ensureRecognizer();
632
+ try { NacChat._recognizer.continuous = true; NacChat._recognizer.start(); } catch (_) {}
633
+ _setMicState('active');
634
+ botSpeak('Manos libres activado.');
635
+ } else {
636
+ try { NacChat._recognizer && NacChat._recognizer.stop(); } catch (_) {}
637
+ _setMicState('idle');
638
+ botSpeak('Manos libres desactivado.');
639
+ }
640
+ }
641
+ function _toggleTts() {
642
+ NacChat._ttsEnabled = !NacChat._ttsEnabled;
643
+ if (NacChat._ttsBtn) {
644
+ NacChat._ttsBtn.setAttribute('aria-pressed', NacChat._ttsEnabled ? 'true' : 'false');
645
+ }
646
+ if (!NacChat._ttsEnabled) {
647
+ try { window.speechSynthesis.cancel(); } catch (_) {}
648
+ }
649
+ }
650
+
651
+ NacChat.setLang = function (code) {
652
+ if (!code || !TTS_BCP47[code]) return;
653
+ NacChat._lang = code;
654
+ document.documentElement.setAttribute('lang', code);
655
+ if (NacChat._langSelect && NacChat._langSelect.value !== code) {
656
+ NacChat._langSelect.value = code;
657
+ }
658
+ if (NacChat._recognizer) {
659
+ try { NacChat._recognizer.lang = TTS_BCP47[code] || 'en-US'; } catch (_) {}
660
+ }
661
+ };
662
+ NacChat.onAction = function (kind, fn) {
663
+ NacChat._customHandlers[kind] = fn;
664
+ };
665
+
666
+ /* ---------- init ---------- */
667
+ NacChat.init = function (opts) {
668
+ opts = opts || {};
669
+ if (opts.endpoint) NacChat._endpoint = opts.endpoint;
670
+ if (opts.sessionId) NacChat._sessionId = opts.sessionId;
671
+ if (opts.lang) NacChat._lang = opts.lang;
672
+ if (opts.chatLog) NacChat._chatLog = opts.chatLog;
673
+ if (opts.input) NacChat._input = opts.input;
674
+ if (opts.langSelect) NacChat._langSelect = opts.langSelect;
675
+ NacChat._micBtn = opts.micBtn || null;
676
+ NacChat._handsFreeBtn = opts.handsFreeBtn || null;
677
+ NacChat._ttsBtn = opts.ttsBtn || null;
678
+ if (NacChat._input) {
679
+ NacChat._input.addEventListener('keydown', function (e) {
680
+ if (e.key === 'Enter') {
681
+ var v = NacChat._input.value.trim();
682
+ if (v) { NacChat._input.value = ''; NacChat.send(v); }
683
+ }
684
+ });
685
+ }
686
+ if (opts.sendBtn) {
687
+ opts.sendBtn.addEventListener('click', function () {
688
+ var v = NacChat._input && NacChat._input.value.trim();
689
+ if (v) { NacChat._input.value = ''; NacChat.send(v); }
690
+ });
691
+ }
692
+ if (NacChat._micBtn) NacChat._micBtn.addEventListener('click', _toggleMic);
693
+ if (NacChat._handsFreeBtn) NacChat._handsFreeBtn.addEventListener('click', _toggleHandsFree);
694
+ if (NacChat._ttsBtn) NacChat._ttsBtn.addEventListener('click', _toggleTts);
695
+ if (NacChat._langSelect) {
696
+ NacChat._langSelect.addEventListener('change', function () {
697
+ NacChat.setLang(NacChat._langSelect.value);
698
+ });
699
+ }
700
+ };
701
+
702
+ global.NacChat = NacChat;
703
+ })(typeof window !== 'undefined' ? window : globalThis);
704
+
705
+ export default _g.NAC || _g.NACv2 || _g.NacChat || _g[Object.keys(_g).find(k => /^NA[Cc]/.test(k))];
706
+ export const NAC = _g.NAC;
707
+ export const NACv2 = _g.NACv2;
708
+ export const NacChat = _g.NacChat;