@nac3/runtime 2.3.1 → 2.5.0-alpha.1

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