@nac3/runtime 2.3.1 → 2.4.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.
- package/CHANGELOG.md +318 -68
- package/LICENSE +201 -201
- package/README.md +9 -9
- package/SPEC.md +471 -82
- package/dist/cli.js +3 -3
- package/dist/nac-chat-client.browser.js +705 -705
- package/dist/nac-chat-client.cjs +705 -705
- package/dist/nac-chat-client.mjs +705 -705
- package/dist/nac-v2-extensions.browser.js +2102 -2291
- package/dist/nac-v2-extensions.cjs +2102 -2291
- package/dist/nac-v2-extensions.mjs +2102 -2291
- package/dist/nac.browser.js +6019 -6125
- package/dist/nac.cjs +6019 -6125
- package/dist/nac.mjs +6019 -6125
- package/package.json +88 -81
package/dist/nac-chat-client.mjs
CHANGED
|
@@ -1,710 +1,710 @@
|
|
|
1
1
|
// Generated by build.mjs -- do not edit. Source: yujin.app/nac-spec/js/nac-chat-client.js
|
|
2
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
|
-
/* v2.2.1: guard browser-only listener so this bundle is importable in
|
|
218
|
-
Node / SSR / test contexts without crashing. */
|
|
219
|
-
if (typeof document !== 'undefined') {
|
|
220
|
-
document.addEventListener('nac:confirm:requested', function (e) {
|
|
221
|
-
try {
|
|
222
|
-
var prompt = (e && e.detail && e.detail.prompt) || '';
|
|
223
|
-
if (!prompt) return;
|
|
224
|
-
var hints = {
|
|
225
|
-
es: 'Decime si o no.', en: 'Say yes or no.', pt: 'Diga sim ou nao.',
|
|
226
|
-
fr: 'Dites oui ou non.', it: 'Dimmi si o no.', de: 'Sag ja oder nein.',
|
|
227
|
-
ja: 'はい か いいえ で答えて。', zh: '请说 是 或 否。',
|
|
228
|
-
hi: 'haan ya nahin.', ar: 'قل نعم او لا.'
|
|
229
|
-
};
|
|
230
|
-
botSpeak(prompt + ' ' + (hints[NacChat._lang] || hints.es), { skipBubble: true });
|
|
231
|
-
} catch (_) {}
|
|
232
|
-
}, true);
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/* ---------- Locale switch (fix C7-bis) ---------- */
|
|
236
|
-
function _maybeChangeLocaleLocally(text) {
|
|
237
|
-
var code = _detectLangSwitch(text);
|
|
238
|
-
if (!code) return false;
|
|
239
|
-
/* Caller paints the user bubble BEFORE invoking us so the
|
|
240
|
-
visual order is "user said X" -> "bot replies Y". The
|
|
241
|
-
previous version painted the bot bubble inside this
|
|
242
|
-
function and the user bubble after it, producing the
|
|
243
|
-
ack-before-prompt visual bug Pablo reported on
|
|
244
|
-
2026-05-09. */
|
|
245
|
-
if (code === NacChat._lang) {
|
|
246
|
-
botSpeak('Ya estoy en ese idioma.');
|
|
247
|
-
return true;
|
|
248
|
-
}
|
|
249
|
-
NacChat.setLang(code);
|
|
250
|
-
var ack = {
|
|
251
|
-
es: 'Cambie a espanol.', en: 'Switched to English.',
|
|
252
|
-
pt: 'Mudei para portugues.', fr: 'Bascule en francais.',
|
|
253
|
-
it: 'Sono passato all italiano.', de: 'Auf Deutsch umgestellt.',
|
|
254
|
-
ja: '日本語に切り替えました。', zh: '已切换到中文。',
|
|
255
|
-
hi: 'Hindi mein switch kar diya.', ar: 'تم التغيير الى العربية.'
|
|
256
|
-
};
|
|
257
|
-
botSpeak(ack[code] || ('Switched to ' + code + '.'));
|
|
258
|
-
return true;
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
/* ---------- Snapshot ---------- */
|
|
262
|
-
NacChat.snapshotTree = function () {
|
|
263
|
-
if (!global.NAC || typeof global.NAC.describe !== 'function') return null;
|
|
264
|
-
try {
|
|
265
|
-
var snap = global.NAC.describe();
|
|
266
|
-
var plugins = (snap.plugins || []).map(function (p) {
|
|
267
|
-
var m = null;
|
|
268
|
-
try {
|
|
269
|
-
if (typeof global.NAC.manifest === 'function' && p && p.plugin) {
|
|
270
|
-
m = global.NAC.manifest(p.plugin);
|
|
271
|
-
}
|
|
272
|
-
} catch (_) {}
|
|
273
|
-
return {
|
|
274
|
-
plugin: p.plugin || '',
|
|
275
|
-
state: p.state || '',
|
|
276
|
-
elements: p.elements || [],
|
|
277
|
-
manifest: m || null
|
|
278
|
-
};
|
|
279
|
-
});
|
|
280
|
-
var out = { active: snap.active || null, plugins: plugins };
|
|
281
|
-
try {
|
|
282
|
-
if (typeof global.NAC.describe_v2 === 'function') {
|
|
283
|
-
var v2 = global.NAC.describe_v2();
|
|
284
|
-
if (v2) {
|
|
285
|
-
out.v2_scope_entries = v2.v2_scope_entries || [];
|
|
286
|
-
out.sitemap = v2.sitemap || null;
|
|
287
|
-
out.tenant_prefix = v2.tenant_prefix || null;
|
|
288
|
-
out.nac_version_v2 = v2.nac_version || null;
|
|
289
|
-
out.data_tables = v2.data_tables || [];
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
} catch (_) {}
|
|
293
|
-
console.log('[nac-chat] snapshot plugins (' + plugins.length + '):',
|
|
294
|
-
plugins.map(function (p) { return p.plugin; }).join(', '));
|
|
295
|
-
if (out.data_tables && out.data_tables.length) {
|
|
296
|
-
console.log('[nac-chat] data_tables:',
|
|
297
|
-
out.data_tables.map(function (t) {
|
|
298
|
-
return t.table_id + ' (' + t.subkind + ')';
|
|
299
|
-
}).join(', '));
|
|
300
|
-
}
|
|
301
|
-
return out;
|
|
302
|
-
} catch (e) {
|
|
303
|
-
console.warn('[nac-chat] snapshot failed:', e && e.message);
|
|
304
|
-
return null;
|
|
305
|
-
}
|
|
306
|
-
};
|
|
307
|
-
|
|
308
|
-
/* ---------- Direct DOM dispatch helpers ---------- */
|
|
309
|
-
/* These bypass NAC.click() / NAC.fill() polling for
|
|
310
|
-
nac:action:succeeded so demos and brownfield adopters that
|
|
311
|
-
have not wired the ack event on every handler still work
|
|
312
|
-
end-to-end. The host is still responsible for the side
|
|
313
|
-
effect; we just don't wait for the conformance ack. */
|
|
314
|
-
function _directClick(nacId) {
|
|
315
|
-
if (!nacId) throw new Error('click: nac_id required');
|
|
316
|
-
var el = document.querySelector('[data-nac-id="' + nacId + '"]');
|
|
317
|
-
if (!el) throw new Error('click: element not found ' + nacId);
|
|
318
|
-
try { el.click(); return { ok: true, dispatched: 'direct' }; }
|
|
319
|
-
catch (e) { throw new Error('click threw: ' + (e && e.message)); }
|
|
320
|
-
}
|
|
321
|
-
function _directClickByVerb(plugin, verb) {
|
|
322
|
-
if (!verb) throw new Error('click_by_verb: verb required');
|
|
323
|
-
/* Resolve verb -> nac_id by walking the v1 manifest cache.
|
|
324
|
-
NAC.manifest(plugin) returns {actions:[{verb, nac_id}]}. */
|
|
325
|
-
var manifest = null;
|
|
326
|
-
try { if (typeof global.NAC.manifest === 'function') manifest = global.NAC.manifest(plugin); }
|
|
327
|
-
catch (_) {}
|
|
328
|
-
var actions = manifest && manifest.actions || [];
|
|
329
|
-
var match = actions.filter(function (a) { return a && a.verb === verb; })[0];
|
|
330
|
-
var nacId = match && (match.nac_id || match.id);
|
|
331
|
-
if (!nacId) {
|
|
332
|
-
/* Fallback: walk the DOM looking for an element under this
|
|
333
|
-
plugin whose data-nac-action matches the verb. */
|
|
334
|
-
var root = plugin
|
|
335
|
-
? document.querySelector('[data-nac-plugin="' + plugin + '"]')
|
|
336
|
-
: document;
|
|
337
|
-
var hit = root && root.querySelector('[data-nac-action="' + verb + '"][data-nac-id]');
|
|
338
|
-
if (!hit) throw new Error('click_by_verb: no nac_id for verb=' + verb + ' plugin=' + plugin);
|
|
339
|
-
try { hit.click(); return { ok: true, dispatched: 'direct_dom_walk' }; }
|
|
340
|
-
catch (e) { throw new Error('click_by_verb threw: ' + e.message); }
|
|
341
|
-
}
|
|
342
|
-
return _directClick(nacId);
|
|
343
|
-
}
|
|
344
|
-
function _directFill(nacId, value) {
|
|
345
|
-
if (!nacId) throw new Error('fill: nac_id required');
|
|
346
|
-
var el = document.querySelector('[data-nac-id="' + nacId + '"]');
|
|
347
|
-
if (!el) throw new Error('fill: element not found ' + nacId);
|
|
348
|
-
try {
|
|
349
|
-
el.focus();
|
|
350
|
-
el.value = value == null ? '' : String(value);
|
|
351
|
-
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
352
|
-
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
353
|
-
return { ok: true };
|
|
354
|
-
} catch (e) { throw new Error('fill threw: ' + e.message); }
|
|
355
|
-
}
|
|
356
|
-
function _directSelect(nacId, value) {
|
|
357
|
-
if (!nacId) throw new Error('select: nac_id required');
|
|
358
|
-
var el = document.querySelector('[data-nac-id="' + nacId + '"]');
|
|
359
|
-
if (!el) throw new Error('select: element not found ' + nacId);
|
|
360
|
-
try {
|
|
361
|
-
if (el.tagName === 'SELECT') {
|
|
362
|
-
el.value = value;
|
|
363
|
-
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
364
|
-
} else {
|
|
365
|
-
/* radio/checkbox: find the option with matching value */
|
|
366
|
-
var opt = el.querySelector('[value="' + value + '"]');
|
|
367
|
-
if (opt) {
|
|
368
|
-
opt.checked = true;
|
|
369
|
-
opt.dispatchEvent(new Event('change', { bubbles: true }));
|
|
370
|
-
} else {
|
|
371
|
-
el.value = value;
|
|
372
|
-
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
return { ok: true };
|
|
376
|
-
} catch (e) { throw new Error('select threw: ' + e.message); }
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
/* ---------- Backend dispatch ---------- */
|
|
380
|
-
async function _backendCall(text) {
|
|
381
|
-
var snap = NacChat.snapshotTree();
|
|
382
|
-
var body = {
|
|
383
|
-
session_id: NacChat._sessionId,
|
|
384
|
-
prompt: text,
|
|
385
|
-
lang: NacChat._lang,
|
|
386
|
-
history: NacChat._history.slice(-8),
|
|
387
|
-
nac_tree: snap
|
|
388
|
-
};
|
|
389
|
-
try {
|
|
390
|
-
var resp = await fetch(NacChat._endpoint, {
|
|
391
|
-
method: 'POST',
|
|
392
|
-
headers: { 'Content-Type': 'application/json' },
|
|
393
|
-
body: JSON.stringify(body)
|
|
394
|
-
});
|
|
395
|
-
if (!resp.ok) {
|
|
396
|
-
return { ok: false, error: 'http_' + resp.status };
|
|
397
|
-
}
|
|
398
|
-
var json = await resp.json();
|
|
399
|
-
return json && json.ok !== false ? { ok: true, data: json } : { ok: false, error: (json && json.error) || 'backend_error' };
|
|
400
|
-
} catch (e) {
|
|
401
|
-
return { ok: false, error: 'fetch_' + (e && e.message || 'unknown') };
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/* ---------- Action dispatcher ---------- */
|
|
406
|
-
async function _dispatchAction(a) {
|
|
407
|
-
if (NacChat._customHandlers[a.kind]) {
|
|
408
|
-
return await NacChat._customHandlers[a.kind](a);
|
|
409
|
-
}
|
|
410
|
-
if (!global.NAC) throw new Error('NAC runtime missing');
|
|
411
|
-
switch (a.kind) {
|
|
412
|
-
case 'click':
|
|
413
|
-
/* 2026-05-09 fix: NAC.click() polls for nac:action:
|
|
414
|
-
succeeded with a 5s timeout. Many demos / adopters
|
|
415
|
-
do not wire that ack event on every handler, so the
|
|
416
|
-
click visually executes (modal opens, button fires)
|
|
417
|
-
but the promise rejects on timeout and the chat
|
|
418
|
-
reports 'action failed'. We dispatch the DOM click
|
|
419
|
-
directly here -- the side effect happens; ack is
|
|
420
|
-
best-effort. Spec sec 18 requires the ack only at
|
|
421
|
-
NAC-3 conformance level. */
|
|
422
|
-
return _directClick(a.nac_id);
|
|
423
|
-
case 'click_by_verb':
|
|
424
|
-
/* Same reasoning. We resolve verb -> nac_id locally
|
|
425
|
-
then dispatch the DOM click directly. */
|
|
426
|
-
return _directClickByVerb(a.plugin || null, a.verb);
|
|
427
|
-
case 'fill':
|
|
428
|
-
return _directFill(a.nac_id, a.value);
|
|
429
|
-
case 'select':
|
|
430
|
-
return _directSelect(a.nac_id, a.value);
|
|
431
|
-
case 'tab': return await global.NAC.tab(a.plugin, a.tab_key);
|
|
432
|
-
case 'tab_by_label': return await global.NAC.tab_by_label(a.plugin || null, a.label);
|
|
433
|
-
case 'drag_drop': return await global.NAC.drag_drop(a.nac_id, a.target_nac_id,
|
|
434
|
-
typeof a.to_index === 'number' ? { to_index: a.to_index } : undefined);
|
|
435
|
-
case 'go_to_section': return await global.NAC.go_to_section(a.nac_id);
|
|
436
|
-
case 'say': if (a.text) botSpeak(a.text); return { ok: true };
|
|
437
|
-
case 'change_locale':
|
|
438
|
-
if (typeof a.locale === 'string' && a.locale.length === 2) {
|
|
439
|
-
NacChat.setLang(a.locale);
|
|
440
|
-
return { ok: true };
|
|
441
|
-
}
|
|
442
|
-
throw new Error('change_locale: missing locale');
|
|
443
|
-
/* v2.1 sec 18 */
|
|
444
|
-
case 'dt_add_row': {
|
|
445
|
-
if (typeof global.NAC.dt_add_row !== 'function') throw new Error('dt_add_row missing -- runtime older than v2.1');
|
|
446
|
-
var r = global.NAC.dt_add_row(a.table_id, a.values || {});
|
|
447
|
-
if (r && r.ok === false) throw new Error('dt_add_row: ' + r.error + (r.column ? ' (' + r.column + ')' : ''));
|
|
448
|
-
return { ok: true, row_id: r && r.row_id };
|
|
449
|
-
}
|
|
450
|
-
case 'dt_remove_row':
|
|
451
|
-
if (typeof global.NAC.dt_remove_row !== 'function') throw new Error('dt_remove_row missing');
|
|
452
|
-
global.NAC.dt_remove_row(a.table_id, a.row_id); return { ok: true };
|
|
453
|
-
case 'dt_edit_cell': {
|
|
454
|
-
if (typeof global.NAC.dt_edit_cell !== 'function') throw new Error('dt_edit_cell missing');
|
|
455
|
-
var r2 = global.NAC.dt_edit_cell(a.table_id, a.row_id, a.column, a.value);
|
|
456
|
-
if (r2 && r2.ok === false) throw new Error('dt_edit_cell: ' + r2.error);
|
|
457
|
-
return { ok: true };
|
|
458
|
-
}
|
|
459
|
-
case 'dt_set_cell': {
|
|
460
|
-
if (typeof global.NAC.dt_set_cell !== 'function') throw new Error('dt_set_cell missing');
|
|
461
|
-
var r3 = global.NAC.dt_set_cell(a.table_id, a.row, a.col, a.value);
|
|
462
|
-
if (r3 && r3.ok === false) throw new Error('dt_set_cell: ' + r3.error);
|
|
463
|
-
return { ok: true };
|
|
464
|
-
}
|
|
465
|
-
case 'dt_select':
|
|
466
|
-
if (typeof global.NAC.dt_select !== 'function') throw new Error('dt_select missing');
|
|
467
|
-
return global.NAC.dt_select(a.table_id, a.target);
|
|
468
|
-
case 'dt_commit': {
|
|
469
|
-
if (typeof global.NAC.dt_commit !== 'function') throw new Error('dt_commit missing');
|
|
470
|
-
var rc = global.NAC.dt_commit(a.table_id);
|
|
471
|
-
if (rc && rc.ok === false) {
|
|
472
|
-
throw new Error('dt_commit blocked: ' +
|
|
473
|
-
(rc.errors || []).map(function (e) { return e.code; }).join(', '));
|
|
474
|
-
}
|
|
475
|
-
return { ok: true, final_state: rc && rc.final_state };
|
|
476
|
-
}
|
|
477
|
-
case 'dt_discard':
|
|
478
|
-
if (typeof global.NAC.dt_discard !== 'function') throw new Error('dt_discard missing');
|
|
479
|
-
global.NAC.dt_discard(a.table_id); return { ok: true };
|
|
480
|
-
case 'dt_read_aggregate':
|
|
481
|
-
if (typeof global.NAC.dt_read_aggregate !== 'function') throw new Error('dt_read_aggregate missing');
|
|
482
|
-
return { ok: true, value: global.NAC.dt_read_aggregate(a.table_id, a.agg_key, a.column) };
|
|
483
|
-
default:
|
|
484
|
-
throw new Error('unknown action kind: ' + a.kind);
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/* ---------- Send pipeline ---------- */
|
|
489
|
-
NacChat.send = async function (text) {
|
|
490
|
-
text = (text || '').trim();
|
|
491
|
-
if (!text) return;
|
|
492
|
-
/* TTS interrupt: a fresh user turn cancels pending bot speech. */
|
|
493
|
-
if ('speechSynthesis' in window) {
|
|
494
|
-
try { window.speechSynthesis.cancel(); } catch (_) {}
|
|
495
|
-
NacChat._ttsBusyUntil = 0;
|
|
496
|
-
}
|
|
497
|
-
/* Paint the user bubble FIRST so visual order is always
|
|
498
|
-
"user said X" -> "bot replies Y", regardless of whether
|
|
499
|
-
the path is local short-circuit or backend round-trip. */
|
|
500
|
-
_bubble('user', text);
|
|
501
|
-
/* Short-circuits BEFORE the LLM round-trip. */
|
|
502
|
-
if (_maybeAnswerPendingConfirm(text)) { return; }
|
|
503
|
-
if (_maybeChangeLocaleLocally(text)) { return; }
|
|
504
|
-
|
|
505
|
-
NacChat._history.push({ role: 'user', text: text });
|
|
506
|
-
|
|
507
|
-
var resp = await _backendCall(text);
|
|
508
|
-
if (!resp.ok) {
|
|
509
|
-
botSpeak('Falla del backend: ' + resp.error);
|
|
510
|
-
return;
|
|
511
|
-
}
|
|
512
|
-
var d = resp.data;
|
|
513
|
-
/* Prefer the structured shape {message, actions[]} but be
|
|
514
|
-
tolerant to legacy shapes that returned only {reply} or
|
|
515
|
-
a single action. */
|
|
516
|
-
var message = d.message || d.reply || '';
|
|
517
|
-
var actions = Array.isArray(d.actions) ? d.actions : (d.action ? [d.action] : []);
|
|
518
|
-
/* 2026-05-09 diagnostic: log EXACTLY what the backend
|
|
519
|
-
returned so 'chat says X but nothing happens' is
|
|
520
|
-
distinguishable from 'chat dispatched X but it failed
|
|
521
|
-
silently'. If the LLM only emits a {message} with no
|
|
522
|
-
actions, this log makes it obvious. */
|
|
523
|
-
console.log('[nac-chat] backend response: message="' + message
|
|
524
|
-
+ '" actions=' + JSON.stringify(actions));
|
|
525
|
-
if (message) {
|
|
526
|
-
_bubble('bot', message);
|
|
527
|
-
_ttsRememberUtterance(message);
|
|
528
|
-
if (NacChat._ttsEnabled && 'speechSynthesis' in window) {
|
|
529
|
-
try {
|
|
530
|
-
var u = new SpeechSynthesisUtterance(message);
|
|
531
|
-
u.lang = TTS_BCP47[NacChat._lang] || 'en-US'; u.rate = 1.05;
|
|
532
|
-
window.speechSynthesis.speak(u);
|
|
533
|
-
} catch (_) {}
|
|
534
|
-
}
|
|
535
|
-
NacChat._history.push({ role: 'assistant', text: message });
|
|
536
|
-
}
|
|
537
|
-
for (var i = 0; i < actions.length; i++) {
|
|
538
|
-
try {
|
|
539
|
-
await _dispatchAction(actions[i]);
|
|
540
|
-
} catch (e) {
|
|
541
|
-
console.warn('[nac-chat] action failed:', actions[i], e && e.message);
|
|
542
|
-
_bubble('bot', 'No pude ejecutar: ' + (e && e.message || e));
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
};
|
|
546
|
-
|
|
547
|
-
/* ---------- STT ---------- */
|
|
548
|
-
function _ensureRecognizer() {
|
|
549
|
-
if (NacChat._recognizer) return NacChat._recognizer;
|
|
550
|
-
var Cls = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
551
|
-
if (!Cls) return null;
|
|
552
|
-
var r = new Cls();
|
|
553
|
-
r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
|
|
554
|
-
r.continuous = false;
|
|
555
|
-
r.interimResults = true;
|
|
556
|
-
function flushBuffer() {
|
|
557
|
-
var text = (NacChat._sttBuffer || '').trim();
|
|
558
|
-
NacChat._sttBuffer = '';
|
|
559
|
-
if (NacChat._sttFlushTimer) { clearTimeout(NacChat._sttFlushTimer); NacChat._sttFlushTimer = null; }
|
|
560
|
-
if (!text) return;
|
|
561
|
-
if (_isBotEcho(text)) {
|
|
562
|
-
console.log('[nac-chat-stt] dropping bot-echo:', text);
|
|
563
|
-
return;
|
|
564
|
-
}
|
|
565
|
-
if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
|
|
566
|
-
console.log('[nac-chat-stt] dropping during TTS:', text);
|
|
567
|
-
return;
|
|
568
|
-
}
|
|
569
|
-
NacChat.send(text);
|
|
570
|
-
}
|
|
571
|
-
r.onresult = function (e) {
|
|
572
|
-
if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
|
|
573
|
-
return; /* half-duplex */
|
|
574
|
-
}
|
|
575
|
-
for (var i = e.resultIndex; i < e.results.length; i++) {
|
|
576
|
-
var res = e.results[i];
|
|
577
|
-
if (!res.isFinal) continue;
|
|
578
|
-
var txt = (res[0] && res[0].transcript || '').trim();
|
|
579
|
-
if (!txt) continue;
|
|
580
|
-
NacChat._sttBuffer = NacChat._sttBuffer ? (NacChat._sttBuffer + ' ' + txt) : txt;
|
|
581
|
-
if (NacChat._sttFlushTimer) clearTimeout(NacChat._sttFlushTimer);
|
|
582
|
-
NacChat._sttFlushTimer = setTimeout(flushBuffer, NacChat._STT_SILENCE_MS);
|
|
583
|
-
}
|
|
584
|
-
};
|
|
585
|
-
r.onend = function () {
|
|
586
|
-
if (NacChat._voiceAlwaysOn) {
|
|
587
|
-
try {
|
|
588
|
-
r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
|
|
589
|
-
r.continuous = true;
|
|
590
|
-
r.start();
|
|
591
|
-
return;
|
|
592
|
-
} catch (_) {}
|
|
593
|
-
}
|
|
594
|
-
_setMicState('idle');
|
|
595
|
-
};
|
|
596
|
-
r.onerror = function (e) {
|
|
597
|
-
var fatal = e.error === 'not-allowed' || e.error === 'service-not-allowed';
|
|
598
|
-
if (NacChat._voiceAlwaysOn && !fatal) return;
|
|
599
|
-
botSpeak('Mic error: ' + e.error, { skipBubble: true });
|
|
600
|
-
_setMicState('idle');
|
|
601
|
-
};
|
|
602
|
-
NacChat._recognizer = r;
|
|
603
|
-
return r;
|
|
604
|
-
}
|
|
605
|
-
function _setMicState(state) {
|
|
606
|
-
if (!NacChat._micBtn) return;
|
|
607
|
-
NacChat._micBtn.setAttribute('data-nac-state', state);
|
|
608
|
-
NacChat._micBtn.setAttribute('aria-pressed', state === 'active' ? 'true' : 'false');
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
function _toggleMic() {
|
|
612
|
-
var r = _ensureRecognizer();
|
|
613
|
-
if (!r) { botSpeak('Tu navegador no soporta speech recognition.'); return; }
|
|
614
|
-
if (NacChat._micBtn && NacChat._micBtn.getAttribute('data-nac-state') === 'active') {
|
|
615
|
-
try { r.stop(); } catch (_) {}
|
|
616
|
-
_setMicState('idle');
|
|
617
|
-
} else {
|
|
618
|
-
try {
|
|
619
|
-
r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
|
|
620
|
-
r.continuous = !!NacChat._voiceAlwaysOn;
|
|
621
|
-
r.start();
|
|
622
|
-
_setMicState('active');
|
|
623
|
-
} catch (e) {
|
|
624
|
-
console.warn('[nac-chat-stt] start failed:', e);
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
function _toggleHandsFree() {
|
|
629
|
-
NacChat._voiceAlwaysOn = !NacChat._voiceAlwaysOn;
|
|
630
|
-
if (NacChat._handsFreeBtn) {
|
|
631
|
-
NacChat._handsFreeBtn.setAttribute('aria-pressed', NacChat._voiceAlwaysOn ? 'true' : 'false');
|
|
632
|
-
NacChat._handsFreeBtn.setAttribute('data-nac-state', NacChat._voiceAlwaysOn ? 'active' : 'idle');
|
|
633
|
-
}
|
|
634
|
-
if (NacChat._voiceAlwaysOn) {
|
|
635
|
-
_ensureRecognizer();
|
|
636
|
-
try { NacChat._recognizer.continuous = true; NacChat._recognizer.start(); } catch (_) {}
|
|
637
|
-
_setMicState('active');
|
|
638
|
-
botSpeak('Manos libres activado.');
|
|
639
|
-
} else {
|
|
640
|
-
try { NacChat._recognizer && NacChat._recognizer.stop(); } catch (_) {}
|
|
641
|
-
_setMicState('idle');
|
|
642
|
-
botSpeak('Manos libres desactivado.');
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
function _toggleTts() {
|
|
646
|
-
NacChat._ttsEnabled = !NacChat._ttsEnabled;
|
|
647
|
-
if (NacChat._ttsBtn) {
|
|
648
|
-
NacChat._ttsBtn.setAttribute('aria-pressed', NacChat._ttsEnabled ? 'true' : 'false');
|
|
649
|
-
}
|
|
650
|
-
if (!NacChat._ttsEnabled) {
|
|
651
|
-
try { window.speechSynthesis.cancel(); } catch (_) {}
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
NacChat.setLang = function (code) {
|
|
656
|
-
if (!code || !TTS_BCP47[code]) return;
|
|
657
|
-
NacChat._lang = code;
|
|
658
|
-
document.documentElement.setAttribute('lang', code);
|
|
659
|
-
if (NacChat._langSelect && NacChat._langSelect.value !== code) {
|
|
660
|
-
NacChat._langSelect.value = code;
|
|
661
|
-
}
|
|
662
|
-
if (NacChat._recognizer) {
|
|
663
|
-
try { NacChat._recognizer.lang = TTS_BCP47[code] || 'en-US'; } catch (_) {}
|
|
664
|
-
}
|
|
665
|
-
};
|
|
666
|
-
NacChat.onAction = function (kind, fn) {
|
|
667
|
-
NacChat._customHandlers[kind] = fn;
|
|
668
|
-
};
|
|
669
|
-
|
|
670
|
-
/* ---------- init ---------- */
|
|
671
|
-
NacChat.init = function (opts) {
|
|
672
|
-
opts = opts || {};
|
|
673
|
-
if (opts.endpoint) NacChat._endpoint = opts.endpoint;
|
|
674
|
-
if (opts.sessionId) NacChat._sessionId = opts.sessionId;
|
|
675
|
-
if (opts.lang) NacChat._lang = opts.lang;
|
|
676
|
-
if (opts.chatLog) NacChat._chatLog = opts.chatLog;
|
|
677
|
-
if (opts.input) NacChat._input = opts.input;
|
|
678
|
-
if (opts.langSelect) NacChat._langSelect = opts.langSelect;
|
|
679
|
-
NacChat._micBtn = opts.micBtn || null;
|
|
680
|
-
NacChat._handsFreeBtn = opts.handsFreeBtn || null;
|
|
681
|
-
NacChat._ttsBtn = opts.ttsBtn || null;
|
|
682
|
-
if (NacChat._input) {
|
|
683
|
-
NacChat._input.addEventListener('keydown', function (e) {
|
|
684
|
-
if (e.key === 'Enter') {
|
|
685
|
-
var v = NacChat._input.value.trim();
|
|
686
|
-
if (v) { NacChat._input.value = ''; NacChat.send(v); }
|
|
687
|
-
}
|
|
688
|
-
});
|
|
689
|
-
}
|
|
690
|
-
if (opts.sendBtn) {
|
|
691
|
-
opts.sendBtn.addEventListener('click', function () {
|
|
692
|
-
var v = NacChat._input && NacChat._input.value.trim();
|
|
693
|
-
if (v) { NacChat._input.value = ''; NacChat.send(v); }
|
|
694
|
-
});
|
|
695
|
-
}
|
|
696
|
-
if (NacChat._micBtn) NacChat._micBtn.addEventListener('click', _toggleMic);
|
|
697
|
-
if (NacChat._handsFreeBtn) NacChat._handsFreeBtn.addEventListener('click', _toggleHandsFree);
|
|
698
|
-
if (NacChat._ttsBtn) NacChat._ttsBtn.addEventListener('click', _toggleTts);
|
|
699
|
-
if (NacChat._langSelect) {
|
|
700
|
-
NacChat._langSelect.addEventListener('change', function () {
|
|
701
|
-
NacChat.setLang(NacChat._langSelect.value);
|
|
702
|
-
});
|
|
703
|
-
}
|
|
704
|
-
};
|
|
705
|
-
|
|
706
|
-
global.NacChat = NacChat;
|
|
707
|
-
})(typeof window !== 'undefined' ? window : globalThis);
|
|
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
|
+
/* v2.2.1: guard browser-only listener so this bundle is importable in
|
|
218
|
+
Node / SSR / test contexts without crashing. */
|
|
219
|
+
if (typeof document !== 'undefined') {
|
|
220
|
+
document.addEventListener('nac:confirm:requested', function (e) {
|
|
221
|
+
try {
|
|
222
|
+
var prompt = (e && e.detail && e.detail.prompt) || '';
|
|
223
|
+
if (!prompt) return;
|
|
224
|
+
var hints = {
|
|
225
|
+
es: 'Decime si o no.', en: 'Say yes or no.', pt: 'Diga sim ou nao.',
|
|
226
|
+
fr: 'Dites oui ou non.', it: 'Dimmi si o no.', de: 'Sag ja oder nein.',
|
|
227
|
+
ja: 'はい か いいえ で答えて。', zh: '请说 是 或 否。',
|
|
228
|
+
hi: 'haan ya nahin.', ar: 'قل نعم او لا.'
|
|
229
|
+
};
|
|
230
|
+
botSpeak(prompt + ' ' + (hints[NacChat._lang] || hints.es), { skipBubble: true });
|
|
231
|
+
} catch (_) {}
|
|
232
|
+
}, true);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/* ---------- Locale switch (fix C7-bis) ---------- */
|
|
236
|
+
function _maybeChangeLocaleLocally(text) {
|
|
237
|
+
var code = _detectLangSwitch(text);
|
|
238
|
+
if (!code) return false;
|
|
239
|
+
/* Caller paints the user bubble BEFORE invoking us so the
|
|
240
|
+
visual order is "user said X" -> "bot replies Y". The
|
|
241
|
+
previous version painted the bot bubble inside this
|
|
242
|
+
function and the user bubble after it, producing the
|
|
243
|
+
ack-before-prompt visual bug Pablo reported on
|
|
244
|
+
2026-05-09. */
|
|
245
|
+
if (code === NacChat._lang) {
|
|
246
|
+
botSpeak('Ya estoy en ese idioma.');
|
|
247
|
+
return true;
|
|
248
|
+
}
|
|
249
|
+
NacChat.setLang(code);
|
|
250
|
+
var ack = {
|
|
251
|
+
es: 'Cambie a espanol.', en: 'Switched to English.',
|
|
252
|
+
pt: 'Mudei para portugues.', fr: 'Bascule en francais.',
|
|
253
|
+
it: 'Sono passato all italiano.', de: 'Auf Deutsch umgestellt.',
|
|
254
|
+
ja: '日本語に切り替えました。', zh: '已切换到中文。',
|
|
255
|
+
hi: 'Hindi mein switch kar diya.', ar: 'تم التغيير الى العربية.'
|
|
256
|
+
};
|
|
257
|
+
botSpeak(ack[code] || ('Switched to ' + code + '.'));
|
|
258
|
+
return true;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/* ---------- Snapshot ---------- */
|
|
262
|
+
NacChat.snapshotTree = function () {
|
|
263
|
+
if (!global.NAC || typeof global.NAC.describe !== 'function') return null;
|
|
264
|
+
try {
|
|
265
|
+
var snap = global.NAC.describe();
|
|
266
|
+
var plugins = (snap.plugins || []).map(function (p) {
|
|
267
|
+
var m = null;
|
|
268
|
+
try {
|
|
269
|
+
if (typeof global.NAC.manifest === 'function' && p && p.plugin) {
|
|
270
|
+
m = global.NAC.manifest(p.plugin);
|
|
271
|
+
}
|
|
272
|
+
} catch (_) {}
|
|
273
|
+
return {
|
|
274
|
+
plugin: p.plugin || '',
|
|
275
|
+
state: p.state || '',
|
|
276
|
+
elements: p.elements || [],
|
|
277
|
+
manifest: m || null
|
|
278
|
+
};
|
|
279
|
+
});
|
|
280
|
+
var out = { active: snap.active || null, plugins: plugins };
|
|
281
|
+
try {
|
|
282
|
+
if (typeof global.NAC.describe_v2 === 'function') {
|
|
283
|
+
var v2 = global.NAC.describe_v2();
|
|
284
|
+
if (v2) {
|
|
285
|
+
out.v2_scope_entries = v2.v2_scope_entries || [];
|
|
286
|
+
out.sitemap = v2.sitemap || null;
|
|
287
|
+
out.tenant_prefix = v2.tenant_prefix || null;
|
|
288
|
+
out.nac_version_v2 = v2.nac_version || null;
|
|
289
|
+
out.data_tables = v2.data_tables || [];
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
} catch (_) {}
|
|
293
|
+
console.log('[nac-chat] snapshot plugins (' + plugins.length + '):',
|
|
294
|
+
plugins.map(function (p) { return p.plugin; }).join(', '));
|
|
295
|
+
if (out.data_tables && out.data_tables.length) {
|
|
296
|
+
console.log('[nac-chat] data_tables:',
|
|
297
|
+
out.data_tables.map(function (t) {
|
|
298
|
+
return t.table_id + ' (' + t.subkind + ')';
|
|
299
|
+
}).join(', '));
|
|
300
|
+
}
|
|
301
|
+
return out;
|
|
302
|
+
} catch (e) {
|
|
303
|
+
console.warn('[nac-chat] snapshot failed:', e && e.message);
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
/* ---------- Direct DOM dispatch helpers ---------- */
|
|
309
|
+
/* These bypass NAC.click() / NAC.fill() polling for
|
|
310
|
+
nac:action:succeeded so demos and brownfield adopters that
|
|
311
|
+
have not wired the ack event on every handler still work
|
|
312
|
+
end-to-end. The host is still responsible for the side
|
|
313
|
+
effect; we just don't wait for the conformance ack. */
|
|
314
|
+
function _directClick(nacId) {
|
|
315
|
+
if (!nacId) throw new Error('click: nac_id required');
|
|
316
|
+
var el = document.querySelector('[data-nac-id="' + nacId + '"]');
|
|
317
|
+
if (!el) throw new Error('click: element not found ' + nacId);
|
|
318
|
+
try { el.click(); return { ok: true, dispatched: 'direct' }; }
|
|
319
|
+
catch (e) { throw new Error('click threw: ' + (e && e.message)); }
|
|
320
|
+
}
|
|
321
|
+
function _directClickByVerb(plugin, verb) {
|
|
322
|
+
if (!verb) throw new Error('click_by_verb: verb required');
|
|
323
|
+
/* Resolve verb -> nac_id by walking the v1 manifest cache.
|
|
324
|
+
NAC.manifest(plugin) returns {actions:[{verb, nac_id}]}. */
|
|
325
|
+
var manifest = null;
|
|
326
|
+
try { if (typeof global.NAC.manifest === 'function') manifest = global.NAC.manifest(plugin); }
|
|
327
|
+
catch (_) {}
|
|
328
|
+
var actions = manifest && manifest.actions || [];
|
|
329
|
+
var match = actions.filter(function (a) { return a && a.verb === verb; })[0];
|
|
330
|
+
var nacId = match && (match.nac_id || match.id);
|
|
331
|
+
if (!nacId) {
|
|
332
|
+
/* Fallback: walk the DOM looking for an element under this
|
|
333
|
+
plugin whose data-nac-action matches the verb. */
|
|
334
|
+
var root = plugin
|
|
335
|
+
? document.querySelector('[data-nac-plugin="' + plugin + '"]')
|
|
336
|
+
: document;
|
|
337
|
+
var hit = root && root.querySelector('[data-nac-action="' + verb + '"][data-nac-id]');
|
|
338
|
+
if (!hit) throw new Error('click_by_verb: no nac_id for verb=' + verb + ' plugin=' + plugin);
|
|
339
|
+
try { hit.click(); return { ok: true, dispatched: 'direct_dom_walk' }; }
|
|
340
|
+
catch (e) { throw new Error('click_by_verb threw: ' + e.message); }
|
|
341
|
+
}
|
|
342
|
+
return _directClick(nacId);
|
|
343
|
+
}
|
|
344
|
+
function _directFill(nacId, value) {
|
|
345
|
+
if (!nacId) throw new Error('fill: nac_id required');
|
|
346
|
+
var el = document.querySelector('[data-nac-id="' + nacId + '"]');
|
|
347
|
+
if (!el) throw new Error('fill: element not found ' + nacId);
|
|
348
|
+
try {
|
|
349
|
+
el.focus();
|
|
350
|
+
el.value = value == null ? '' : String(value);
|
|
351
|
+
el.dispatchEvent(new Event('input', { bubbles: true }));
|
|
352
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
353
|
+
return { ok: true };
|
|
354
|
+
} catch (e) { throw new Error('fill threw: ' + e.message); }
|
|
355
|
+
}
|
|
356
|
+
function _directSelect(nacId, value) {
|
|
357
|
+
if (!nacId) throw new Error('select: nac_id required');
|
|
358
|
+
var el = document.querySelector('[data-nac-id="' + nacId + '"]');
|
|
359
|
+
if (!el) throw new Error('select: element not found ' + nacId);
|
|
360
|
+
try {
|
|
361
|
+
if (el.tagName === 'SELECT') {
|
|
362
|
+
el.value = value;
|
|
363
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
364
|
+
} else {
|
|
365
|
+
/* radio/checkbox: find the option with matching value */
|
|
366
|
+
var opt = el.querySelector('[value="' + value + '"]');
|
|
367
|
+
if (opt) {
|
|
368
|
+
opt.checked = true;
|
|
369
|
+
opt.dispatchEvent(new Event('change', { bubbles: true }));
|
|
370
|
+
} else {
|
|
371
|
+
el.value = value;
|
|
372
|
+
el.dispatchEvent(new Event('change', { bubbles: true }));
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return { ok: true };
|
|
376
|
+
} catch (e) { throw new Error('select threw: ' + e.message); }
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/* ---------- Backend dispatch ---------- */
|
|
380
|
+
async function _backendCall(text) {
|
|
381
|
+
var snap = NacChat.snapshotTree();
|
|
382
|
+
var body = {
|
|
383
|
+
session_id: NacChat._sessionId,
|
|
384
|
+
prompt: text,
|
|
385
|
+
lang: NacChat._lang,
|
|
386
|
+
history: NacChat._history.slice(-8),
|
|
387
|
+
nac_tree: snap
|
|
388
|
+
};
|
|
389
|
+
try {
|
|
390
|
+
var resp = await fetch(NacChat._endpoint, {
|
|
391
|
+
method: 'POST',
|
|
392
|
+
headers: { 'Content-Type': 'application/json' },
|
|
393
|
+
body: JSON.stringify(body)
|
|
394
|
+
});
|
|
395
|
+
if (!resp.ok) {
|
|
396
|
+
return { ok: false, error: 'http_' + resp.status };
|
|
397
|
+
}
|
|
398
|
+
var json = await resp.json();
|
|
399
|
+
return json && json.ok !== false ? { ok: true, data: json } : { ok: false, error: (json && json.error) || 'backend_error' };
|
|
400
|
+
} catch (e) {
|
|
401
|
+
return { ok: false, error: 'fetch_' + (e && e.message || 'unknown') };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/* ---------- Action dispatcher ---------- */
|
|
406
|
+
async function _dispatchAction(a) {
|
|
407
|
+
if (NacChat._customHandlers[a.kind]) {
|
|
408
|
+
return await NacChat._customHandlers[a.kind](a);
|
|
409
|
+
}
|
|
410
|
+
if (!global.NAC) throw new Error('NAC runtime missing');
|
|
411
|
+
switch (a.kind) {
|
|
412
|
+
case 'click':
|
|
413
|
+
/* 2026-05-09 fix: NAC.click() polls for nac:action:
|
|
414
|
+
succeeded with a 5s timeout. Many demos / adopters
|
|
415
|
+
do not wire that ack event on every handler, so the
|
|
416
|
+
click visually executes (modal opens, button fires)
|
|
417
|
+
but the promise rejects on timeout and the chat
|
|
418
|
+
reports 'action failed'. We dispatch the DOM click
|
|
419
|
+
directly here -- the side effect happens; ack is
|
|
420
|
+
best-effort. Spec sec 18 requires the ack only at
|
|
421
|
+
NAC-3 conformance level. */
|
|
422
|
+
return _directClick(a.nac_id);
|
|
423
|
+
case 'click_by_verb':
|
|
424
|
+
/* Same reasoning. We resolve verb -> nac_id locally
|
|
425
|
+
then dispatch the DOM click directly. */
|
|
426
|
+
return _directClickByVerb(a.plugin || null, a.verb);
|
|
427
|
+
case 'fill':
|
|
428
|
+
return _directFill(a.nac_id, a.value);
|
|
429
|
+
case 'select':
|
|
430
|
+
return _directSelect(a.nac_id, a.value);
|
|
431
|
+
case 'tab': return await global.NAC.tab(a.plugin, a.tab_key);
|
|
432
|
+
case 'tab_by_label': return await global.NAC.tab_by_label(a.plugin || null, a.label);
|
|
433
|
+
case 'drag_drop': return await global.NAC.drag_drop(a.nac_id, a.target_nac_id,
|
|
434
|
+
typeof a.to_index === 'number' ? { to_index: a.to_index } : undefined);
|
|
435
|
+
case 'go_to_section': return await global.NAC.go_to_section(a.nac_id);
|
|
436
|
+
case 'say': if (a.text) botSpeak(a.text); return { ok: true };
|
|
437
|
+
case 'change_locale':
|
|
438
|
+
if (typeof a.locale === 'string' && a.locale.length === 2) {
|
|
439
|
+
NacChat.setLang(a.locale);
|
|
440
|
+
return { ok: true };
|
|
441
|
+
}
|
|
442
|
+
throw new Error('change_locale: missing locale');
|
|
443
|
+
/* v2.1 sec 18 */
|
|
444
|
+
case 'dt_add_row': {
|
|
445
|
+
if (typeof global.NAC.dt_add_row !== 'function') throw new Error('dt_add_row missing -- runtime older than v2.1');
|
|
446
|
+
var r = global.NAC.dt_add_row(a.table_id, a.values || {});
|
|
447
|
+
if (r && r.ok === false) throw new Error('dt_add_row: ' + r.error + (r.column ? ' (' + r.column + ')' : ''));
|
|
448
|
+
return { ok: true, row_id: r && r.row_id };
|
|
449
|
+
}
|
|
450
|
+
case 'dt_remove_row':
|
|
451
|
+
if (typeof global.NAC.dt_remove_row !== 'function') throw new Error('dt_remove_row missing');
|
|
452
|
+
global.NAC.dt_remove_row(a.table_id, a.row_id); return { ok: true };
|
|
453
|
+
case 'dt_edit_cell': {
|
|
454
|
+
if (typeof global.NAC.dt_edit_cell !== 'function') throw new Error('dt_edit_cell missing');
|
|
455
|
+
var r2 = global.NAC.dt_edit_cell(a.table_id, a.row_id, a.column, a.value);
|
|
456
|
+
if (r2 && r2.ok === false) throw new Error('dt_edit_cell: ' + r2.error);
|
|
457
|
+
return { ok: true };
|
|
458
|
+
}
|
|
459
|
+
case 'dt_set_cell': {
|
|
460
|
+
if (typeof global.NAC.dt_set_cell !== 'function') throw new Error('dt_set_cell missing');
|
|
461
|
+
var r3 = global.NAC.dt_set_cell(a.table_id, a.row, a.col, a.value);
|
|
462
|
+
if (r3 && r3.ok === false) throw new Error('dt_set_cell: ' + r3.error);
|
|
463
|
+
return { ok: true };
|
|
464
|
+
}
|
|
465
|
+
case 'dt_select':
|
|
466
|
+
if (typeof global.NAC.dt_select !== 'function') throw new Error('dt_select missing');
|
|
467
|
+
return global.NAC.dt_select(a.table_id, a.target);
|
|
468
|
+
case 'dt_commit': {
|
|
469
|
+
if (typeof global.NAC.dt_commit !== 'function') throw new Error('dt_commit missing');
|
|
470
|
+
var rc = global.NAC.dt_commit(a.table_id);
|
|
471
|
+
if (rc && rc.ok === false) {
|
|
472
|
+
throw new Error('dt_commit blocked: ' +
|
|
473
|
+
(rc.errors || []).map(function (e) { return e.code; }).join(', '));
|
|
474
|
+
}
|
|
475
|
+
return { ok: true, final_state: rc && rc.final_state };
|
|
476
|
+
}
|
|
477
|
+
case 'dt_discard':
|
|
478
|
+
if (typeof global.NAC.dt_discard !== 'function') throw new Error('dt_discard missing');
|
|
479
|
+
global.NAC.dt_discard(a.table_id); return { ok: true };
|
|
480
|
+
case 'dt_read_aggregate':
|
|
481
|
+
if (typeof global.NAC.dt_read_aggregate !== 'function') throw new Error('dt_read_aggregate missing');
|
|
482
|
+
return { ok: true, value: global.NAC.dt_read_aggregate(a.table_id, a.agg_key, a.column) };
|
|
483
|
+
default:
|
|
484
|
+
throw new Error('unknown action kind: ' + a.kind);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/* ---------- Send pipeline ---------- */
|
|
489
|
+
NacChat.send = async function (text) {
|
|
490
|
+
text = (text || '').trim();
|
|
491
|
+
if (!text) return;
|
|
492
|
+
/* TTS interrupt: a fresh user turn cancels pending bot speech. */
|
|
493
|
+
if ('speechSynthesis' in window) {
|
|
494
|
+
try { window.speechSynthesis.cancel(); } catch (_) {}
|
|
495
|
+
NacChat._ttsBusyUntil = 0;
|
|
496
|
+
}
|
|
497
|
+
/* Paint the user bubble FIRST so visual order is always
|
|
498
|
+
"user said X" -> "bot replies Y", regardless of whether
|
|
499
|
+
the path is local short-circuit or backend round-trip. */
|
|
500
|
+
_bubble('user', text);
|
|
501
|
+
/* Short-circuits BEFORE the LLM round-trip. */
|
|
502
|
+
if (_maybeAnswerPendingConfirm(text)) { return; }
|
|
503
|
+
if (_maybeChangeLocaleLocally(text)) { return; }
|
|
504
|
+
|
|
505
|
+
NacChat._history.push({ role: 'user', text: text });
|
|
506
|
+
|
|
507
|
+
var resp = await _backendCall(text);
|
|
508
|
+
if (!resp.ok) {
|
|
509
|
+
botSpeak('Falla del backend: ' + resp.error);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
var d = resp.data;
|
|
513
|
+
/* Prefer the structured shape {message, actions[]} but be
|
|
514
|
+
tolerant to legacy shapes that returned only {reply} or
|
|
515
|
+
a single action. */
|
|
516
|
+
var message = d.message || d.reply || '';
|
|
517
|
+
var actions = Array.isArray(d.actions) ? d.actions : (d.action ? [d.action] : []);
|
|
518
|
+
/* 2026-05-09 diagnostic: log EXACTLY what the backend
|
|
519
|
+
returned so 'chat says X but nothing happens' is
|
|
520
|
+
distinguishable from 'chat dispatched X but it failed
|
|
521
|
+
silently'. If the LLM only emits a {message} with no
|
|
522
|
+
actions, this log makes it obvious. */
|
|
523
|
+
console.log('[nac-chat] backend response: message="' + message
|
|
524
|
+
+ '" actions=' + JSON.stringify(actions));
|
|
525
|
+
if (message) {
|
|
526
|
+
_bubble('bot', message);
|
|
527
|
+
_ttsRememberUtterance(message);
|
|
528
|
+
if (NacChat._ttsEnabled && 'speechSynthesis' in window) {
|
|
529
|
+
try {
|
|
530
|
+
var u = new SpeechSynthesisUtterance(message);
|
|
531
|
+
u.lang = TTS_BCP47[NacChat._lang] || 'en-US'; u.rate = 1.05;
|
|
532
|
+
window.speechSynthesis.speak(u);
|
|
533
|
+
} catch (_) {}
|
|
534
|
+
}
|
|
535
|
+
NacChat._history.push({ role: 'assistant', text: message });
|
|
536
|
+
}
|
|
537
|
+
for (var i = 0; i < actions.length; i++) {
|
|
538
|
+
try {
|
|
539
|
+
await _dispatchAction(actions[i]);
|
|
540
|
+
} catch (e) {
|
|
541
|
+
console.warn('[nac-chat] action failed:', actions[i], e && e.message);
|
|
542
|
+
_bubble('bot', 'No pude ejecutar: ' + (e && e.message || e));
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
/* ---------- STT ---------- */
|
|
548
|
+
function _ensureRecognizer() {
|
|
549
|
+
if (NacChat._recognizer) return NacChat._recognizer;
|
|
550
|
+
var Cls = window.SpeechRecognition || window.webkitSpeechRecognition;
|
|
551
|
+
if (!Cls) return null;
|
|
552
|
+
var r = new Cls();
|
|
553
|
+
r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
|
|
554
|
+
r.continuous = false;
|
|
555
|
+
r.interimResults = true;
|
|
556
|
+
function flushBuffer() {
|
|
557
|
+
var text = (NacChat._sttBuffer || '').trim();
|
|
558
|
+
NacChat._sttBuffer = '';
|
|
559
|
+
if (NacChat._sttFlushTimer) { clearTimeout(NacChat._sttFlushTimer); NacChat._sttFlushTimer = null; }
|
|
560
|
+
if (!text) return;
|
|
561
|
+
if (_isBotEcho(text)) {
|
|
562
|
+
console.log('[nac-chat-stt] dropping bot-echo:', text);
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
|
|
566
|
+
console.log('[nac-chat-stt] dropping during TTS:', text);
|
|
567
|
+
return;
|
|
568
|
+
}
|
|
569
|
+
NacChat.send(text);
|
|
570
|
+
}
|
|
571
|
+
r.onresult = function (e) {
|
|
572
|
+
if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
|
|
573
|
+
return; /* half-duplex */
|
|
574
|
+
}
|
|
575
|
+
for (var i = e.resultIndex; i < e.results.length; i++) {
|
|
576
|
+
var res = e.results[i];
|
|
577
|
+
if (!res.isFinal) continue;
|
|
578
|
+
var txt = (res[0] && res[0].transcript || '').trim();
|
|
579
|
+
if (!txt) continue;
|
|
580
|
+
NacChat._sttBuffer = NacChat._sttBuffer ? (NacChat._sttBuffer + ' ' + txt) : txt;
|
|
581
|
+
if (NacChat._sttFlushTimer) clearTimeout(NacChat._sttFlushTimer);
|
|
582
|
+
NacChat._sttFlushTimer = setTimeout(flushBuffer, NacChat._STT_SILENCE_MS);
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
r.onend = function () {
|
|
586
|
+
if (NacChat._voiceAlwaysOn) {
|
|
587
|
+
try {
|
|
588
|
+
r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
|
|
589
|
+
r.continuous = true;
|
|
590
|
+
r.start();
|
|
591
|
+
return;
|
|
592
|
+
} catch (_) {}
|
|
593
|
+
}
|
|
594
|
+
_setMicState('idle');
|
|
595
|
+
};
|
|
596
|
+
r.onerror = function (e) {
|
|
597
|
+
var fatal = e.error === 'not-allowed' || e.error === 'service-not-allowed';
|
|
598
|
+
if (NacChat._voiceAlwaysOn && !fatal) return;
|
|
599
|
+
botSpeak('Mic error: ' + e.error, { skipBubble: true });
|
|
600
|
+
_setMicState('idle');
|
|
601
|
+
};
|
|
602
|
+
NacChat._recognizer = r;
|
|
603
|
+
return r;
|
|
604
|
+
}
|
|
605
|
+
function _setMicState(state) {
|
|
606
|
+
if (!NacChat._micBtn) return;
|
|
607
|
+
NacChat._micBtn.setAttribute('data-nac-state', state);
|
|
608
|
+
NacChat._micBtn.setAttribute('aria-pressed', state === 'active' ? 'true' : 'false');
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function _toggleMic() {
|
|
612
|
+
var r = _ensureRecognizer();
|
|
613
|
+
if (!r) { botSpeak('Tu navegador no soporta speech recognition.'); return; }
|
|
614
|
+
if (NacChat._micBtn && NacChat._micBtn.getAttribute('data-nac-state') === 'active') {
|
|
615
|
+
try { r.stop(); } catch (_) {}
|
|
616
|
+
_setMicState('idle');
|
|
617
|
+
} else {
|
|
618
|
+
try {
|
|
619
|
+
r.lang = TTS_BCP47[NacChat._lang] || 'en-US';
|
|
620
|
+
r.continuous = !!NacChat._voiceAlwaysOn;
|
|
621
|
+
r.start();
|
|
622
|
+
_setMicState('active');
|
|
623
|
+
} catch (e) {
|
|
624
|
+
console.warn('[nac-chat-stt] start failed:', e);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
function _toggleHandsFree() {
|
|
629
|
+
NacChat._voiceAlwaysOn = !NacChat._voiceAlwaysOn;
|
|
630
|
+
if (NacChat._handsFreeBtn) {
|
|
631
|
+
NacChat._handsFreeBtn.setAttribute('aria-pressed', NacChat._voiceAlwaysOn ? 'true' : 'false');
|
|
632
|
+
NacChat._handsFreeBtn.setAttribute('data-nac-state', NacChat._voiceAlwaysOn ? 'active' : 'idle');
|
|
633
|
+
}
|
|
634
|
+
if (NacChat._voiceAlwaysOn) {
|
|
635
|
+
_ensureRecognizer();
|
|
636
|
+
try { NacChat._recognizer.continuous = true; NacChat._recognizer.start(); } catch (_) {}
|
|
637
|
+
_setMicState('active');
|
|
638
|
+
botSpeak('Manos libres activado.');
|
|
639
|
+
} else {
|
|
640
|
+
try { NacChat._recognizer && NacChat._recognizer.stop(); } catch (_) {}
|
|
641
|
+
_setMicState('idle');
|
|
642
|
+
botSpeak('Manos libres desactivado.');
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
function _toggleTts() {
|
|
646
|
+
NacChat._ttsEnabled = !NacChat._ttsEnabled;
|
|
647
|
+
if (NacChat._ttsBtn) {
|
|
648
|
+
NacChat._ttsBtn.setAttribute('aria-pressed', NacChat._ttsEnabled ? 'true' : 'false');
|
|
649
|
+
}
|
|
650
|
+
if (!NacChat._ttsEnabled) {
|
|
651
|
+
try { window.speechSynthesis.cancel(); } catch (_) {}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
NacChat.setLang = function (code) {
|
|
656
|
+
if (!code || !TTS_BCP47[code]) return;
|
|
657
|
+
NacChat._lang = code;
|
|
658
|
+
document.documentElement.setAttribute('lang', code);
|
|
659
|
+
if (NacChat._langSelect && NacChat._langSelect.value !== code) {
|
|
660
|
+
NacChat._langSelect.value = code;
|
|
661
|
+
}
|
|
662
|
+
if (NacChat._recognizer) {
|
|
663
|
+
try { NacChat._recognizer.lang = TTS_BCP47[code] || 'en-US'; } catch (_) {}
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
NacChat.onAction = function (kind, fn) {
|
|
667
|
+
NacChat._customHandlers[kind] = fn;
|
|
668
|
+
};
|
|
669
|
+
|
|
670
|
+
/* ---------- init ---------- */
|
|
671
|
+
NacChat.init = function (opts) {
|
|
672
|
+
opts = opts || {};
|
|
673
|
+
if (opts.endpoint) NacChat._endpoint = opts.endpoint;
|
|
674
|
+
if (opts.sessionId) NacChat._sessionId = opts.sessionId;
|
|
675
|
+
if (opts.lang) NacChat._lang = opts.lang;
|
|
676
|
+
if (opts.chatLog) NacChat._chatLog = opts.chatLog;
|
|
677
|
+
if (opts.input) NacChat._input = opts.input;
|
|
678
|
+
if (opts.langSelect) NacChat._langSelect = opts.langSelect;
|
|
679
|
+
NacChat._micBtn = opts.micBtn || null;
|
|
680
|
+
NacChat._handsFreeBtn = opts.handsFreeBtn || null;
|
|
681
|
+
NacChat._ttsBtn = opts.ttsBtn || null;
|
|
682
|
+
if (NacChat._input) {
|
|
683
|
+
NacChat._input.addEventListener('keydown', function (e) {
|
|
684
|
+
if (e.key === 'Enter') {
|
|
685
|
+
var v = NacChat._input.value.trim();
|
|
686
|
+
if (v) { NacChat._input.value = ''; NacChat.send(v); }
|
|
687
|
+
}
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
if (opts.sendBtn) {
|
|
691
|
+
opts.sendBtn.addEventListener('click', function () {
|
|
692
|
+
var v = NacChat._input && NacChat._input.value.trim();
|
|
693
|
+
if (v) { NacChat._input.value = ''; NacChat.send(v); }
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
if (NacChat._micBtn) NacChat._micBtn.addEventListener('click', _toggleMic);
|
|
697
|
+
if (NacChat._handsFreeBtn) NacChat._handsFreeBtn.addEventListener('click', _toggleHandsFree);
|
|
698
|
+
if (NacChat._ttsBtn) NacChat._ttsBtn.addEventListener('click', _toggleTts);
|
|
699
|
+
if (NacChat._langSelect) {
|
|
700
|
+
NacChat._langSelect.addEventListener('change', function () {
|
|
701
|
+
NacChat.setLang(NacChat._langSelect.value);
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
|
|
706
|
+
global.NacChat = NacChat;
|
|
707
|
+
})(typeof window !== 'undefined' ? window : globalThis);
|
|
708
708
|
|
|
709
709
|
export default _g.NAC || _g.NACv2 || _g.NacChat || _g[Object.keys(_g).find(k => /^NA[Cc]/.test(k))];
|
|
710
710
|
export const NAC = _g.NAC;
|