@boldare/askdare 0.3.0 → 0.5.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 +63 -0
- package/README.md +14 -4
- package/dist/cli.js +111 -26
- package/dist/define-tool.js +1006 -8
- package/dist/embed.d.ts +19 -0
- package/dist/embed.js +250 -0
- package/dist/{store.d.ts → events.d.ts} +163 -54
- package/dist/index.d.ts +28 -2
- package/dist/index.js +74 -158
- package/dist/next.d.ts +70 -9
- package/dist/next.js +767 -169
- package/dist/react-marked.js +648 -624
- package/dist/react.d.ts +63 -77
- package/dist/react.js +148 -1854
- package/dist/root.js +2254 -0
- package/dist/tool-results.d.ts +140 -0
- package/dist/ui/askdare.css +21 -1
- package/dist/ui/avatar.tsx +1 -1
- package/dist/ui/chat.tsx +1 -1
- package/dist/ui/confirm.tsx +1 -1
- package/dist/ui/context.ts +1 -1
- package/dist/ui/feedback.tsx +1 -1
- package/dist/ui/footer.tsx +3 -15
- package/dist/ui/header.tsx +1 -1
- package/dist/ui/icons.tsx +1 -1
- package/dist/ui/index.ts +1 -1
- package/dist/ui/message.tsx +6 -4
- package/dist/ui/panel.tsx +17 -6
- package/dist/ui/welcome.tsx +1 -1
- package/docs/accessibility.md +83 -0
- package/docs/cli.md +5 -3
- package/docs/compliance.md +160 -0
- package/docs/configuration.md +58 -2
- package/docs/costs.md +8 -1
- package/docs/custom-store.md +2 -0
- package/docs/embedding.md +104 -0
- package/docs/events.md +1 -1
- package/docs/feedback.md +1 -1
- package/docs/going-public.md +15 -3
- package/docs/guardrails.md +128 -0
- package/docs/migrating-from-openai-assistant.md +1 -1
- package/docs/privacy.md +27 -3
- package/docs/protocol.md +15 -1
- package/docs/react.md +57 -3
- package/docs/styling.md +4 -3
- package/docs/support.md +3 -3
- package/docs/texts.md +127 -98
- package/docs/tools.md +20 -0
- package/docs/troubleshooting.md +30 -3
- package/llms.txt +14 -11
- package/package.json +10 -6
- package/skills/askdare/SKILL.md +12 -2
package/dist/define-tool.js
CHANGED
|
@@ -1,4 +1,473 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
// src/base-path.ts
|
|
3
|
+
/**
|
|
4
|
+
* Whether a chat route's `basePath` is a path on the app itself, like `/api/chat`: never another
|
|
5
|
+
* origin, a relative path or anything that needs escaping (ADR-0011). The server, the React entry
|
|
6
|
+
* and the CLI each bundle their own copy.
|
|
7
|
+
*/
|
|
8
|
+
function isBasePath(value) {
|
|
9
|
+
return /^(\/[a-zA-Z0-9._~-]+)+$/.test(value);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Whether a bot's `embedPath` is a page of the same app, like `/askdare/support` (ADR-0018): a
|
|
13
|
+
* path as `isBasePath` accepts it, without `.` or `..` segments, so a redirect to it can't leave
|
|
14
|
+
* the app or climb out of where it points.
|
|
15
|
+
*/
|
|
16
|
+
function isEmbedPath(value) {
|
|
17
|
+
return isBasePath(value) && !value.split("/").some((segment) => /^\.{1,2}$/.test(segment));
|
|
18
|
+
}
|
|
19
|
+
/** Whether `path` is `basePath` itself or inside it. */
|
|
20
|
+
function isInside(path, basePath) {
|
|
21
|
+
return path === basePath || path.startsWith(`${basePath}/`);
|
|
22
|
+
}
|
|
23
|
+
// src/i18n/locales/cs.ts
|
|
24
|
+
/**
|
|
25
|
+
* Czech. Formal "vy", as Czech interfaces usually address users; plurals use `one`, `few`,
|
|
26
|
+
* `many` (fractions) and `other`. Override any text with `widget.texts`.
|
|
27
|
+
*/
|
|
28
|
+
const CS = {
|
|
29
|
+
"header.title": "Asistent",
|
|
30
|
+
"header.newConversation": "Začít novou konverzaci",
|
|
31
|
+
"header.close": "Zavřít chat",
|
|
32
|
+
"confirm.newConversation": "Začít novou konverzaci? Současná bude smazána.",
|
|
33
|
+
"confirm.cancel": "Zrušit",
|
|
34
|
+
"confirm.accept": "Začít znovu",
|
|
35
|
+
"welcome.label": "Vítejte",
|
|
36
|
+
"welcome.greeting": "Dobrý den! Jak vám mohu pomoci?",
|
|
37
|
+
"welcome.online": "Online",
|
|
38
|
+
"welcome.suggestions": "Navrhované otázky",
|
|
39
|
+
"composer.placeholder": "Napište zprávu…",
|
|
40
|
+
"composer.send": "Odeslat",
|
|
41
|
+
"composer.attach": "Přiložit soubory",
|
|
42
|
+
"composer.dictate": "Nadiktovat zprávu",
|
|
43
|
+
"status.loading": "Načítám konverzaci…",
|
|
44
|
+
"status.thinking": "Přemýšlím…",
|
|
45
|
+
"status.searching": "Prohledávám dokumenty…",
|
|
46
|
+
"status.tool": "Používám {name}…",
|
|
47
|
+
"status.typing": "Asistent píše",
|
|
48
|
+
"message.sources": "Zdroje",
|
|
49
|
+
"message.replies": "Navrhované odpovědi",
|
|
50
|
+
"feedback.label": "Ohodnoťte tuto odpověď",
|
|
51
|
+
"feedback.up": "Užitečná",
|
|
52
|
+
"feedback.down": "Neužitečná",
|
|
53
|
+
"feedback.comment": "Co bylo špatně?",
|
|
54
|
+
"feedback.send": "Odeslat hodnocení",
|
|
55
|
+
"feedback.skip": "Přeskočit",
|
|
56
|
+
"message.attachments.one": "{count} příloha",
|
|
57
|
+
"message.attachments.few": "{count} přílohy",
|
|
58
|
+
"message.attachments.many": "{count} přílohy",
|
|
59
|
+
"message.attachments.other": "{count} příloh",
|
|
60
|
+
"attachment.list": "Přílohy",
|
|
61
|
+
"attachment.uploading": "Nahrávám…",
|
|
62
|
+
"attachment.remove": "Odebrat {name}",
|
|
63
|
+
"attachment.unsupported": "Tento typ souboru není podporován.",
|
|
64
|
+
"attachment.tooLarge": "Příliš velký (max. {size}).",
|
|
65
|
+
"attachment.tooMany": "K jedné zprávě můžete přiložit nejvýše {count} souborů.",
|
|
66
|
+
"dictation.listening": "Poslouchám…",
|
|
67
|
+
"dictation.transcribing": "Přepisuji…",
|
|
68
|
+
"dictation.cancel": "Zrušit diktování",
|
|
69
|
+
"dictation.done": "Hotovo",
|
|
70
|
+
"dictation.empty": "Nic se nenahrálo. Zkuste to znovu.",
|
|
71
|
+
"microphone.blocked": "Přístup k mikrofonu je zablokovaný. Povolte ho v prohlížeči, abyste mohli diktovat.",
|
|
72
|
+
"microphone.missing": "Nebyl nalezen žádný mikrofon.",
|
|
73
|
+
"microphone.failed": "Mikrofon se nepodařilo spustit.",
|
|
74
|
+
"disclosure.text": "Píšete si s asistentem s umělou inteligencí. Může dělat chyby.",
|
|
75
|
+
"disclosure.privacy": "Zásady ochrany osobních údajů",
|
|
76
|
+
"launcher.label": "Zeptejte se nás",
|
|
77
|
+
"launcher.open": "Otevřít chat",
|
|
78
|
+
"launcher.close": "Zavřít chat",
|
|
79
|
+
"launcher.unavailable": "Chat se nepodařilo načíst. Zkuste to prosím později.",
|
|
80
|
+
"humanCheck.label": "Ověřujeme, že jste člověk",
|
|
81
|
+
"error.humanCheck": "Nepodařilo se ověřit, že jste člověk. Zkuste to prosím znovu.",
|
|
82
|
+
"error.connection": "Problém s připojením. Zkuste to znovu.",
|
|
83
|
+
"error.history": "Předchozí konverzaci se nepodařilo načíst.",
|
|
84
|
+
"error.updated": "Asistent byl aktualizován. Načtěte stránku znovu.",
|
|
85
|
+
"error.stalled": "Připojení se zastavilo. Zkuste to znovu.",
|
|
86
|
+
"error.uploadFailed": "Soubor se nepodařilo nahrát.",
|
|
87
|
+
"error.transcriptionFailed": "Nahrávku se nepodařilo přepsat.",
|
|
88
|
+
"error.invalid_input": "Požadavek je neplatný.",
|
|
89
|
+
"error.unauthorized": "Je vyžadováno přihlášení.",
|
|
90
|
+
"error.session_expired": "Platnost relace vypršela. Zkuste to znovu.",
|
|
91
|
+
"error.not_found": "Nenalezeno.",
|
|
92
|
+
"error.content_blocked": "Tuto zprávu nelze zpracovat.",
|
|
93
|
+
"error.rate_limited": "Příliš mnoho zpráv. Chvíli počkejte.",
|
|
94
|
+
"error.budget_exceeded": "Asistent je do konce dne nedostupný.",
|
|
95
|
+
"error.internal_error": "Něco se pokazilo. Zkuste to znovu.",
|
|
96
|
+
"error.upstream_error": "Asistent je dočasně nedostupný. Zkuste to znovu.",
|
|
97
|
+
"error.bot_unavailable": "Asistent je momentálně nedostupný.",
|
|
98
|
+
"error.timeout": "Odpověď trvala příliš dlouho. Zkuste to znovu.",
|
|
99
|
+
"error.conversationTooLong": "Tato konverzace je příliš dlouhá. Začněte novou.",
|
|
100
|
+
"error.conversationGone": "Tato konverzace už není k dispozici.",
|
|
101
|
+
"error.messageLength": "Zpráva může mít nejvýše {max} znaků.",
|
|
102
|
+
"error.attachmentExpired": "Platnost přílohy vypršela nebo je neplatná. Přiložte ji znovu.",
|
|
103
|
+
"error.filesNotAccepted": "Tento asistent nepřijímá soubory.",
|
|
104
|
+
"error.tooManyFiles": "K jedné zprávě přiložte nejvýše {count} souborů.",
|
|
105
|
+
"error.fileType.images": "Podporovány jsou jen obrázky (PNG, JPEG, WebP, GIF).",
|
|
106
|
+
"error.fileType.pdf": "Podporovány jsou jen soubory PDF.",
|
|
107
|
+
"error.fileType.both": "Podporovány jsou jen obrázky (PNG, JPEG, WebP, GIF) a soubory PDF.",
|
|
108
|
+
"error.fileTooLarge": "Soubor může mít nejvýše {size}.",
|
|
109
|
+
"error.pdfPages": "PDF může mít nejvýše {max} stran.",
|
|
110
|
+
"error.voiceNotAccepted": "Tento asistent nepřijímá hlasový vstup.",
|
|
111
|
+
"error.recordingFormat": "Tento formát nahrávky není podporován.",
|
|
112
|
+
"error.recordingTooLong": "Tato nahrávka je příliš dlouhá.",
|
|
113
|
+
"error.dictationBusy": "Jiné diktování se ještě přepisuje. Zkuste to za chvíli.",
|
|
114
|
+
"error.dictationBudget": "Diktování je do konce dne nedostupné. Psát můžete i nadále."
|
|
115
|
+
};
|
|
116
|
+
// src/i18n/locales/de.ts
|
|
117
|
+
/** German. Informal "du", as most chat interfaces use; override any text with `widget.texts`. */
|
|
118
|
+
const DE = {
|
|
119
|
+
"header.title": "Assistent",
|
|
120
|
+
"header.newConversation": "Neues Gespräch beginnen",
|
|
121
|
+
"header.close": "Chat schließen",
|
|
122
|
+
"confirm.newConversation": "Neues Gespräch beginnen? Das aktuelle wird gelöscht.",
|
|
123
|
+
"confirm.cancel": "Abbrechen",
|
|
124
|
+
"confirm.accept": "Neu beginnen",
|
|
125
|
+
"welcome.label": "Willkommen",
|
|
126
|
+
"welcome.greeting": "Hallo! Wie kann ich helfen?",
|
|
127
|
+
"welcome.online": "Online",
|
|
128
|
+
"welcome.suggestions": "Vorgeschlagene Fragen",
|
|
129
|
+
"composer.placeholder": "Nachricht eingeben…",
|
|
130
|
+
"composer.send": "Senden",
|
|
131
|
+
"composer.attach": "Dateien anhängen",
|
|
132
|
+
"composer.dictate": "Nachricht diktieren",
|
|
133
|
+
"status.loading": "Gespräch wird geladen…",
|
|
134
|
+
"status.thinking": "Denke nach…",
|
|
135
|
+
"status.searching": "Durchsuche Dokumente…",
|
|
136
|
+
"status.tool": "Verwende {name}…",
|
|
137
|
+
"status.typing": "Der Assistent schreibt",
|
|
138
|
+
"message.sources": "Quellen",
|
|
139
|
+
"message.replies": "Vorgeschlagene Antworten",
|
|
140
|
+
"feedback.label": "Diese Antwort bewerten",
|
|
141
|
+
"feedback.up": "Hilfreich",
|
|
142
|
+
"feedback.down": "Nicht hilfreich",
|
|
143
|
+
"feedback.comment": "Was war nicht in Ordnung?",
|
|
144
|
+
"feedback.send": "Feedback senden",
|
|
145
|
+
"feedback.skip": "Überspringen",
|
|
146
|
+
"message.attachments.one": "{count} Anhang",
|
|
147
|
+
"message.attachments.other": "{count} Anhänge",
|
|
148
|
+
"attachment.list": "Anhänge",
|
|
149
|
+
"attachment.uploading": "Wird hochgeladen…",
|
|
150
|
+
"attachment.remove": "{name} entfernen",
|
|
151
|
+
"attachment.unsupported": "Dieser Dateityp wird nicht unterstützt.",
|
|
152
|
+
"attachment.tooLarge": "Zu groß (max. {size}).",
|
|
153
|
+
"attachment.tooMany": "Du kannst bis zu {count} Dateien pro Nachricht anhängen.",
|
|
154
|
+
"dictation.listening": "Ich höre zu…",
|
|
155
|
+
"dictation.transcribing": "Wird transkribiert…",
|
|
156
|
+
"dictation.cancel": "Diktat abbrechen",
|
|
157
|
+
"dictation.done": "Fertig",
|
|
158
|
+
"dictation.empty": "Es wurde nichts aufgenommen. Bitte versuche es erneut.",
|
|
159
|
+
"microphone.blocked": "Der Zugriff auf das Mikrofon ist blockiert. Erlaube ihn im Browser, um zu diktieren.",
|
|
160
|
+
"microphone.missing": "Kein Mikrofon gefunden.",
|
|
161
|
+
"microphone.failed": "Das Mikrofon konnte nicht gestartet werden.",
|
|
162
|
+
"disclosure.text": "Du chattest mit einem KI-Assistenten. Er kann Fehler machen.",
|
|
163
|
+
"disclosure.privacy": "Datenschutzerklärung",
|
|
164
|
+
"launcher.label": "Frag uns",
|
|
165
|
+
"launcher.open": "Chat öffnen",
|
|
166
|
+
"launcher.close": "Chat schließen",
|
|
167
|
+
"launcher.unavailable": "Der Chat konnte nicht geladen werden. Bitte versuche es später erneut.",
|
|
168
|
+
"humanCheck.label": "Wir prüfen, ob du ein Mensch bist",
|
|
169
|
+
"error.humanCheck": "Wir konnten nicht bestätigen, dass du ein Mensch bist. Bitte versuche es erneut.",
|
|
170
|
+
"error.connection": "Verbindungsproblem. Bitte versuche es erneut.",
|
|
171
|
+
"error.history": "Das vorherige Gespräch konnte nicht geladen werden.",
|
|
172
|
+
"error.updated": "Der Assistent wurde aktualisiert. Bitte lade die Seite neu.",
|
|
173
|
+
"error.stalled": "Die Verbindung ist ins Stocken geraten. Bitte versuche es erneut.",
|
|
174
|
+
"error.uploadFailed": "Die Datei konnte nicht hochgeladen werden.",
|
|
175
|
+
"error.transcriptionFailed": "Die Aufnahme konnte nicht transkribiert werden.",
|
|
176
|
+
"error.invalid_input": "Die Anfrage war ungültig.",
|
|
177
|
+
"error.unauthorized": "Eine Anmeldung ist erforderlich.",
|
|
178
|
+
"error.session_expired": "Deine Sitzung ist abgelaufen. Bitte versuche es erneut.",
|
|
179
|
+
"error.not_found": "Nicht gefunden.",
|
|
180
|
+
"error.content_blocked": "Diese Nachricht kann nicht verarbeitet werden.",
|
|
181
|
+
"error.rate_limited": "Zu viele Nachrichten. Bitte warte einen Moment.",
|
|
182
|
+
"error.budget_exceeded": "Der Assistent ist für den Rest des Tages nicht verfügbar.",
|
|
183
|
+
"error.internal_error": "Etwas ist schiefgelaufen. Bitte versuche es erneut.",
|
|
184
|
+
"error.upstream_error": "Der Assistent ist vorübergehend nicht verfügbar. Bitte versuche es erneut.",
|
|
185
|
+
"error.bot_unavailable": "Der Assistent ist derzeit nicht verfügbar.",
|
|
186
|
+
"error.timeout": "Der Assistent hat zu lange gebraucht. Bitte versuche es erneut.",
|
|
187
|
+
"error.conversationTooLong": "Dieses Gespräch ist zu lang. Bitte beginne ein neues.",
|
|
188
|
+
"error.conversationGone": "Dieses Gespräch ist nicht mehr verfügbar.",
|
|
189
|
+
"error.messageLength": "Nachrichten dürfen höchstens {max} Zeichen lang sein.",
|
|
190
|
+
"error.attachmentExpired": "Ein Anhang ist abgelaufen oder ungültig. Bitte hänge ihn erneut an.",
|
|
191
|
+
"error.filesNotAccepted": "Dieser Assistent nimmt keine Dateien an.",
|
|
192
|
+
"error.tooManyFiles": "Hänge bis zu {count} Dateien pro Nachricht an.",
|
|
193
|
+
"error.fileType.images": "Nur Bilder (PNG, JPEG, WebP, GIF) werden unterstützt.",
|
|
194
|
+
"error.fileType.pdf": "Nur PDF-Dateien werden unterstützt.",
|
|
195
|
+
"error.fileType.both": "Nur Bilder (PNG, JPEG, WebP, GIF) und PDF-Dateien werden unterstützt.",
|
|
196
|
+
"error.fileTooLarge": "Dateien dürfen höchstens {size} groß sein.",
|
|
197
|
+
"error.pdfPages": "PDFs dürfen höchstens {max} Seiten haben.",
|
|
198
|
+
"error.voiceNotAccepted": "Dieser Assistent nimmt keine Spracheingabe an.",
|
|
199
|
+
"error.recordingFormat": "Dieses Aufnahmeformat wird nicht unterstützt.",
|
|
200
|
+
"error.recordingTooLong": "Diese Aufnahme ist zu lang.",
|
|
201
|
+
"error.dictationBusy": "Ein anderes Diktat wird noch transkribiert. Bitte versuche es gleich noch einmal.",
|
|
202
|
+
"error.dictationBudget": "Diktieren ist für den Rest des Tages nicht verfügbar. Du kannst weiterhin tippen."
|
|
203
|
+
};
|
|
204
|
+
// src/i18n/locales/es.ts
|
|
205
|
+
/** Spanish. Informal "tú", neutral across regions; override any text with `widget.texts`. */
|
|
206
|
+
const ES = {
|
|
207
|
+
"header.title": "Asistente",
|
|
208
|
+
"header.newConversation": "Empezar una conversación nueva",
|
|
209
|
+
"header.close": "Cerrar el chat",
|
|
210
|
+
"confirm.newConversation": "¿Empezar una conversación nueva? La actual se eliminará.",
|
|
211
|
+
"confirm.cancel": "Cancelar",
|
|
212
|
+
"confirm.accept": "Empezar de nuevo",
|
|
213
|
+
"welcome.label": "Bienvenida",
|
|
214
|
+
"welcome.greeting": "¡Hola! ¿En qué puedo ayudarte?",
|
|
215
|
+
"welcome.online": "En línea",
|
|
216
|
+
"welcome.suggestions": "Preguntas sugeridas",
|
|
217
|
+
"composer.placeholder": "Escribe tu mensaje…",
|
|
218
|
+
"composer.send": "Enviar",
|
|
219
|
+
"composer.attach": "Adjuntar archivos",
|
|
220
|
+
"composer.dictate": "Dictar un mensaje",
|
|
221
|
+
"status.loading": "Cargando la conversación…",
|
|
222
|
+
"status.thinking": "Pensando…",
|
|
223
|
+
"status.searching": "Buscando en los documentos…",
|
|
224
|
+
"status.tool": "Usando {name}…",
|
|
225
|
+
"status.typing": "El asistente está escribiendo",
|
|
226
|
+
"message.sources": "Fuentes",
|
|
227
|
+
"message.replies": "Respuestas sugeridas",
|
|
228
|
+
"feedback.label": "Valora esta respuesta",
|
|
229
|
+
"feedback.up": "Útil",
|
|
230
|
+
"feedback.down": "No es útil",
|
|
231
|
+
"feedback.comment": "¿Qué salió mal?",
|
|
232
|
+
"feedback.send": "Enviar comentario",
|
|
233
|
+
"feedback.skip": "Omitir",
|
|
234
|
+
"message.attachments.one": "{count} archivo adjunto",
|
|
235
|
+
"message.attachments.other": "{count} archivos adjuntos",
|
|
236
|
+
"attachment.list": "Archivos adjuntos",
|
|
237
|
+
"attachment.uploading": "Subiendo…",
|
|
238
|
+
"attachment.remove": "Quitar {name}",
|
|
239
|
+
"attachment.unsupported": "Este tipo de archivo no es compatible.",
|
|
240
|
+
"attachment.tooLarge": "Demasiado grande (máx. {size}).",
|
|
241
|
+
"attachment.tooMany": "Puedes adjuntar hasta {count} archivos por mensaje.",
|
|
242
|
+
"dictation.listening": "Escuchando…",
|
|
243
|
+
"dictation.transcribing": "Transcribiendo…",
|
|
244
|
+
"dictation.cancel": "Cancelar el dictado",
|
|
245
|
+
"dictation.done": "Listo",
|
|
246
|
+
"dictation.empty": "No se grabó nada. Inténtalo de nuevo.",
|
|
247
|
+
"microphone.blocked": "El acceso al micrófono está bloqueado. Permítelo en tu navegador para dictar.",
|
|
248
|
+
"microphone.missing": "No se encontró ningún micrófono.",
|
|
249
|
+
"microphone.failed": "No se pudo iniciar el micrófono.",
|
|
250
|
+
"disclosure.text": "Estás hablando con un asistente de IA. Puede cometer errores.",
|
|
251
|
+
"disclosure.privacy": "Política de privacidad",
|
|
252
|
+
"launcher.label": "Pregúntanos",
|
|
253
|
+
"launcher.open": "Abrir el chat",
|
|
254
|
+
"launcher.close": "Cerrar el chat",
|
|
255
|
+
"launcher.unavailable": "No se pudo cargar el chat. Inténtalo de nuevo más tarde.",
|
|
256
|
+
"humanCheck.label": "Comprobando que eres una persona",
|
|
257
|
+
"error.humanCheck": "No pudimos confirmar que eres una persona. Inténtalo de nuevo.",
|
|
258
|
+
"error.connection": "Problema de conexión. Inténtalo de nuevo.",
|
|
259
|
+
"error.history": "No se pudo cargar la conversación anterior.",
|
|
260
|
+
"error.updated": "El asistente se ha actualizado. Recarga la página.",
|
|
261
|
+
"error.stalled": "La conexión se detuvo. Inténtalo de nuevo.",
|
|
262
|
+
"error.uploadFailed": "No se pudo subir el archivo.",
|
|
263
|
+
"error.transcriptionFailed": "No se pudo transcribir la grabación.",
|
|
264
|
+
"error.invalid_input": "La solicitud no es válida.",
|
|
265
|
+
"error.unauthorized": "Es necesario autenticarse.",
|
|
266
|
+
"error.session_expired": "Tu sesión ha caducado. Inténtalo de nuevo.",
|
|
267
|
+
"error.not_found": "No encontrado.",
|
|
268
|
+
"error.content_blocked": "Este mensaje no se puede procesar.",
|
|
269
|
+
"error.rate_limited": "Demasiados mensajes. Espera un momento.",
|
|
270
|
+
"error.budget_exceeded": "El asistente no está disponible durante el resto del día.",
|
|
271
|
+
"error.internal_error": "Algo salió mal. Inténtalo de nuevo.",
|
|
272
|
+
"error.upstream_error": "El asistente no está disponible temporalmente. Inténtalo de nuevo.",
|
|
273
|
+
"error.bot_unavailable": "El asistente no está disponible en este momento.",
|
|
274
|
+
"error.timeout": "El asistente tardó demasiado en responder. Inténtalo de nuevo.",
|
|
275
|
+
"error.conversationTooLong": "Esta conversación es demasiado larga. Empieza una nueva.",
|
|
276
|
+
"error.conversationGone": "Esta conversación ya no está disponible.",
|
|
277
|
+
"error.messageLength": "Los mensajes pueden tener hasta {max} caracteres.",
|
|
278
|
+
"error.attachmentExpired": "Un archivo adjunto caducó o no es válido. Vuelve a adjuntarlo.",
|
|
279
|
+
"error.filesNotAccepted": "Este asistente no acepta archivos.",
|
|
280
|
+
"error.tooManyFiles": "Adjunta hasta {count} archivos por mensaje.",
|
|
281
|
+
"error.fileType.images": "Solo se admiten imágenes (PNG, JPEG, WebP, GIF).",
|
|
282
|
+
"error.fileType.pdf": "Solo se admiten archivos PDF.",
|
|
283
|
+
"error.fileType.both": "Solo se admiten imágenes (PNG, JPEG, WebP, GIF) y archivos PDF.",
|
|
284
|
+
"error.fileTooLarge": "Los archivos pueden ocupar hasta {size}.",
|
|
285
|
+
"error.pdfPages": "Los PDF pueden tener hasta {max} páginas.",
|
|
286
|
+
"error.voiceNotAccepted": "Este asistente no acepta entrada de voz.",
|
|
287
|
+
"error.recordingFormat": "Este formato de grabación no es compatible.",
|
|
288
|
+
"error.recordingTooLong": "Esta grabación es demasiado larga.",
|
|
289
|
+
"error.dictationBusy": "Todavía se está transcribiendo otro dictado. Inténtalo en un momento.",
|
|
290
|
+
"error.dictationBudget": "El dictado no está disponible durante el resto del día. Puedes seguir escribiendo."
|
|
291
|
+
};
|
|
292
|
+
// src/i18n/locales/fr.ts
|
|
293
|
+
/**
|
|
294
|
+
* French. "Vous", and a narrow no-break space (U+202F) before `?`, `!`, `:` and `;` as French
|
|
295
|
+
* typography asks; override any text with `widget.texts`.
|
|
296
|
+
*/
|
|
297
|
+
const FR = {
|
|
298
|
+
"header.title": "Assistant",
|
|
299
|
+
"header.newConversation": "Nouvelle conversation",
|
|
300
|
+
"header.close": "Fermer le chat",
|
|
301
|
+
"confirm.newConversation": "Commencer une nouvelle conversation ? La conversation actuelle sera supprimée.",
|
|
302
|
+
"confirm.cancel": "Annuler",
|
|
303
|
+
"confirm.accept": "Recommencer",
|
|
304
|
+
"welcome.label": "Bienvenue",
|
|
305
|
+
"welcome.greeting": "Bonjour ! Comment puis-je vous aider ?",
|
|
306
|
+
"welcome.online": "En ligne",
|
|
307
|
+
"welcome.suggestions": "Questions suggérées",
|
|
308
|
+
"composer.placeholder": "Écrivez votre message…",
|
|
309
|
+
"composer.send": "Envoyer",
|
|
310
|
+
"composer.attach": "Joindre des fichiers",
|
|
311
|
+
"composer.dictate": "Dicter un message",
|
|
312
|
+
"status.loading": "Chargement de la conversation…",
|
|
313
|
+
"status.thinking": "Réflexion…",
|
|
314
|
+
"status.searching": "Recherche dans les documents…",
|
|
315
|
+
"status.tool": "Utilisation de {name}…",
|
|
316
|
+
"status.typing": "L’assistant écrit",
|
|
317
|
+
"message.sources": "Sources",
|
|
318
|
+
"message.replies": "Réponses suggérées",
|
|
319
|
+
"feedback.label": "Évaluer cette réponse",
|
|
320
|
+
"feedback.up": "Utile",
|
|
321
|
+
"feedback.down": "Pas utile",
|
|
322
|
+
"feedback.comment": "Qu’est-ce qui n’allait pas ?",
|
|
323
|
+
"feedback.send": "Envoyer l’avis",
|
|
324
|
+
"feedback.skip": "Passer",
|
|
325
|
+
"message.attachments.one": "{count} pièce jointe",
|
|
326
|
+
"message.attachments.other": "{count} pièces jointes",
|
|
327
|
+
"attachment.list": "Pièces jointes",
|
|
328
|
+
"attachment.uploading": "Envoi…",
|
|
329
|
+
"attachment.remove": "Retirer {name}",
|
|
330
|
+
"attachment.unsupported": "Ce type de fichier n’est pas pris en charge.",
|
|
331
|
+
"attachment.tooLarge": "Trop volumineux (max. {size}).",
|
|
332
|
+
"attachment.tooMany": "Vous pouvez joindre jusqu’à {count} fichiers par message.",
|
|
333
|
+
"dictation.listening": "Écoute…",
|
|
334
|
+
"dictation.transcribing": "Transcription…",
|
|
335
|
+
"dictation.cancel": "Annuler la dictée",
|
|
336
|
+
"dictation.done": "Terminé",
|
|
337
|
+
"dictation.empty": "Rien n’a été enregistré. Veuillez réessayer.",
|
|
338
|
+
"microphone.blocked": "L’accès au micro est bloqué. Autorisez-le dans votre navigateur pour dicter.",
|
|
339
|
+
"microphone.missing": "Aucun micro trouvé.",
|
|
340
|
+
"microphone.failed": "Le micro n’a pas pu démarrer.",
|
|
341
|
+
"disclosure.text": "Vous discutez avec un assistant IA. Il peut faire des erreurs.",
|
|
342
|
+
"disclosure.privacy": "Politique de confidentialité",
|
|
343
|
+
"launcher.label": "Une question ?",
|
|
344
|
+
"launcher.open": "Ouvrir le chat",
|
|
345
|
+
"launcher.close": "Fermer le chat",
|
|
346
|
+
"launcher.unavailable": "Le chat n’a pas pu se charger. Veuillez réessayer plus tard.",
|
|
347
|
+
"humanCheck.label": "Vérification que vous êtes humain",
|
|
348
|
+
"error.humanCheck": "Nous n’avons pas pu confirmer que vous êtes humain. Veuillez réessayer.",
|
|
349
|
+
"error.connection": "Problème de connexion. Veuillez réessayer.",
|
|
350
|
+
"error.history": "Impossible de charger la conversation précédente.",
|
|
351
|
+
"error.updated": "L’assistant a été mis à jour. Veuillez recharger la page.",
|
|
352
|
+
"error.stalled": "La connexion s’est interrompue. Veuillez réessayer.",
|
|
353
|
+
"error.uploadFailed": "Le fichier n’a pas pu être envoyé.",
|
|
354
|
+
"error.transcriptionFailed": "L’enregistrement n’a pas pu être transcrit.",
|
|
355
|
+
"error.invalid_input": "La requête n’est pas valide.",
|
|
356
|
+
"error.unauthorized": "Une authentification est requise.",
|
|
357
|
+
"error.session_expired": "Votre session a expiré. Veuillez réessayer.",
|
|
358
|
+
"error.not_found": "Introuvable.",
|
|
359
|
+
"error.content_blocked": "Ce message ne peut pas être traité.",
|
|
360
|
+
"error.rate_limited": "Trop de messages. Veuillez patienter un instant.",
|
|
361
|
+
"error.budget_exceeded": "L’assistant n’est plus disponible pour aujourd’hui.",
|
|
362
|
+
"error.internal_error": "Une erreur s’est produite. Veuillez réessayer.",
|
|
363
|
+
"error.upstream_error": "L’assistant est momentanément indisponible. Veuillez réessayer.",
|
|
364
|
+
"error.bot_unavailable": "L’assistant est actuellement indisponible.",
|
|
365
|
+
"error.timeout": "L’assistant a mis trop de temps à répondre. Veuillez réessayer.",
|
|
366
|
+
"error.conversationTooLong": "Cette conversation est trop longue. Veuillez en commencer une nouvelle.",
|
|
367
|
+
"error.conversationGone": "Cette conversation n’est plus disponible.",
|
|
368
|
+
"error.messageLength": "Les messages peuvent contenir jusqu’à {max} caractères.",
|
|
369
|
+
"error.attachmentExpired": "Une pièce jointe a expiré ou n’est pas valide. Veuillez la joindre à nouveau.",
|
|
370
|
+
"error.filesNotAccepted": "Cet assistant n’accepte pas de fichiers.",
|
|
371
|
+
"error.tooManyFiles": "Joignez jusqu’à {count} fichiers par message.",
|
|
372
|
+
"error.fileType.images": "Seules les images (PNG, JPEG, WebP, GIF) sont prises en charge.",
|
|
373
|
+
"error.fileType.pdf": "Seuls les fichiers PDF sont pris en charge.",
|
|
374
|
+
"error.fileType.both": "Seules les images (PNG, JPEG, WebP, GIF) et les fichiers PDF sont pris en charge.",
|
|
375
|
+
"error.fileTooLarge": "Les fichiers peuvent faire jusqu’à {size}.",
|
|
376
|
+
"error.pdfPages": "Les PDF peuvent compter jusqu’à {max} pages.",
|
|
377
|
+
"error.voiceNotAccepted": "Cet assistant n’accepte pas la saisie vocale.",
|
|
378
|
+
"error.recordingFormat": "Ce format d’enregistrement n’est pas pris en charge.",
|
|
379
|
+
"error.recordingTooLong": "Cet enregistrement est trop long.",
|
|
380
|
+
"error.dictationBusy": "Une autre dictée est en cours de transcription. Réessayez dans un instant.",
|
|
381
|
+
"error.dictationBudget": "La dictée n’est plus disponible pour aujourd’hui. Vous pouvez toujours écrire."
|
|
382
|
+
};
|
|
383
|
+
// src/i18n/locales/it.ts
|
|
384
|
+
/** Italian. Informal "tu"; override any text with `widget.texts`. */
|
|
385
|
+
const IT = {
|
|
386
|
+
"header.title": "Assistente",
|
|
387
|
+
"header.newConversation": "Inizia una nuova conversazione",
|
|
388
|
+
"header.close": "Chiudi la chat",
|
|
389
|
+
"confirm.newConversation": "Iniziare una nuova conversazione? Quella attuale verrà eliminata.",
|
|
390
|
+
"confirm.cancel": "Annulla",
|
|
391
|
+
"confirm.accept": "Ricomincia",
|
|
392
|
+
"welcome.label": "Benvenuto",
|
|
393
|
+
"welcome.greeting": "Ciao! Come posso aiutarti?",
|
|
394
|
+
"welcome.online": "Online",
|
|
395
|
+
"welcome.suggestions": "Domande suggerite",
|
|
396
|
+
"composer.placeholder": "Scrivi un messaggio…",
|
|
397
|
+
"composer.send": "Invia",
|
|
398
|
+
"composer.attach": "Allega file",
|
|
399
|
+
"composer.dictate": "Detta un messaggio",
|
|
400
|
+
"status.loading": "Caricamento della conversazione…",
|
|
401
|
+
"status.thinking": "Sto pensando…",
|
|
402
|
+
"status.searching": "Cerco nei documenti…",
|
|
403
|
+
"status.tool": "Uso {name}…",
|
|
404
|
+
"status.typing": "L’assistente sta scrivendo",
|
|
405
|
+
"message.sources": "Fonti",
|
|
406
|
+
"message.replies": "Risposte suggerite",
|
|
407
|
+
"feedback.label": "Valuta questa risposta",
|
|
408
|
+
"feedback.up": "Utile",
|
|
409
|
+
"feedback.down": "Non utile",
|
|
410
|
+
"feedback.comment": "Cosa non andava?",
|
|
411
|
+
"feedback.send": "Invia feedback",
|
|
412
|
+
"feedback.skip": "Salta",
|
|
413
|
+
"message.attachments.one": "{count} allegato",
|
|
414
|
+
"message.attachments.other": "{count} allegati",
|
|
415
|
+
"attachment.list": "Allegati",
|
|
416
|
+
"attachment.uploading": "Caricamento…",
|
|
417
|
+
"attachment.remove": "Rimuovi {name}",
|
|
418
|
+
"attachment.unsupported": "Questo tipo di file non è supportato.",
|
|
419
|
+
"attachment.tooLarge": "Troppo grande (max {size}).",
|
|
420
|
+
"attachment.tooMany": "Puoi allegare fino a {count} file per messaggio.",
|
|
421
|
+
"dictation.listening": "In ascolto…",
|
|
422
|
+
"dictation.transcribing": "Trascrizione…",
|
|
423
|
+
"dictation.cancel": "Annulla la dettatura",
|
|
424
|
+
"dictation.done": "Fatto",
|
|
425
|
+
"dictation.empty": "Non è stato registrato nulla. Riprova.",
|
|
426
|
+
"microphone.blocked": "L’accesso al microfono è bloccato. Consentilo nel browser per poter dettare.",
|
|
427
|
+
"microphone.missing": "Nessun microfono trovato.",
|
|
428
|
+
"microphone.failed": "Impossibile avviare il microfono.",
|
|
429
|
+
"disclosure.text": "Stai chattando con un assistente IA. Può commettere errori.",
|
|
430
|
+
"disclosure.privacy": "Informativa sulla privacy",
|
|
431
|
+
"launcher.label": "Chiedi a noi",
|
|
432
|
+
"launcher.open": "Apri la chat",
|
|
433
|
+
"launcher.close": "Chiudi la chat",
|
|
434
|
+
"launcher.unavailable": "Impossibile caricare la chat. Riprova più tardi.",
|
|
435
|
+
"humanCheck.label": "Verifichiamo che tu sia una persona",
|
|
436
|
+
"error.humanCheck": "Non è stato possibile verificare che tu sia una persona. Riprova.",
|
|
437
|
+
"error.connection": "Problema di connessione. Riprova.",
|
|
438
|
+
"error.history": "Impossibile caricare la conversazione precedente.",
|
|
439
|
+
"error.updated": "L’assistente è stato aggiornato. Ricarica la pagina.",
|
|
440
|
+
"error.stalled": "La connessione si è interrotta. Riprova.",
|
|
441
|
+
"error.uploadFailed": "Impossibile caricare il file.",
|
|
442
|
+
"error.transcriptionFailed": "Impossibile trascrivere la registrazione.",
|
|
443
|
+
"error.invalid_input": "La richiesta non è valida.",
|
|
444
|
+
"error.unauthorized": "È necessaria l’autenticazione.",
|
|
445
|
+
"error.session_expired": "La sessione è scaduta. Riprova.",
|
|
446
|
+
"error.not_found": "Non trovato.",
|
|
447
|
+
"error.content_blocked": "Questo messaggio non può essere elaborato.",
|
|
448
|
+
"error.rate_limited": "Troppi messaggi. Attendi un momento.",
|
|
449
|
+
"error.budget_exceeded": "L’assistente non è disponibile per il resto della giornata.",
|
|
450
|
+
"error.internal_error": "Qualcosa è andato storto. Riprova.",
|
|
451
|
+
"error.upstream_error": "L’assistente è temporaneamente non disponibile. Riprova.",
|
|
452
|
+
"error.bot_unavailable": "L’assistente al momento non è disponibile.",
|
|
453
|
+
"error.timeout": "L’assistente ha impiegato troppo tempo a rispondere. Riprova.",
|
|
454
|
+
"error.conversationTooLong": "Questa conversazione è troppo lunga. Iniziane una nuova.",
|
|
455
|
+
"error.conversationGone": "Questa conversazione non è più disponibile.",
|
|
456
|
+
"error.messageLength": "I messaggi possono contenere fino a {max} caratteri.",
|
|
457
|
+
"error.attachmentExpired": "Un allegato è scaduto o non è valido. Allegalo di nuovo.",
|
|
458
|
+
"error.filesNotAccepted": "Questo assistente non accetta file.",
|
|
459
|
+
"error.tooManyFiles": "Allega fino a {count} file per messaggio.",
|
|
460
|
+
"error.fileType.images": "Sono supportate solo immagini (PNG, JPEG, WebP, GIF).",
|
|
461
|
+
"error.fileType.pdf": "Sono supportati solo file PDF.",
|
|
462
|
+
"error.fileType.both": "Sono supportati solo immagini (PNG, JPEG, WebP, GIF) e file PDF.",
|
|
463
|
+
"error.fileTooLarge": "I file possono pesare fino a {size}.",
|
|
464
|
+
"error.pdfPages": "I PDF possono avere fino a {max} pagine.",
|
|
465
|
+
"error.voiceNotAccepted": "Questo assistente non accetta input vocali.",
|
|
466
|
+
"error.recordingFormat": "Questo formato di registrazione non è supportato.",
|
|
467
|
+
"error.recordingTooLong": "Questa registrazione è troppo lunga.",
|
|
468
|
+
"error.dictationBusy": "Un’altra dettatura è ancora in trascrizione. Riprova tra un momento.",
|
|
469
|
+
"error.dictationBudget": "La dettatura non è disponibile per il resto della giornata. Puoi comunque scrivere."
|
|
470
|
+
};
|
|
2
471
|
// src/i18n/locale.ts
|
|
3
472
|
/** The canonical form of a BCP 47 tag that Intl accepts (plural rules need it), else undefined. */
|
|
4
473
|
function canonicalLocale(tag) {
|
|
@@ -64,6 +533,8 @@ const EN = {
|
|
|
64
533
|
"launcher.open": "Open chat",
|
|
65
534
|
"launcher.close": "Close chat",
|
|
66
535
|
"launcher.unavailable": "The chat couldn’t load. Please try again later.",
|
|
536
|
+
"humanCheck.label": "Checking that you’re human",
|
|
537
|
+
"error.humanCheck": "We couldn’t confirm you’re human. Please try again.",
|
|
67
538
|
"error.connection": "Connection problem. Please try again.",
|
|
68
539
|
"error.history": "Could not load the previous conversation.",
|
|
69
540
|
"error.updated": "The assistant was updated. Please reload the page.",
|
|
@@ -160,6 +631,8 @@ const PL = {
|
|
|
160
631
|
"launcher.open": "Otwórz czat",
|
|
161
632
|
"launcher.close": "Zamknij czat",
|
|
162
633
|
"launcher.unavailable": "Nie udało się załadować czatu. Spróbuj ponownie później.",
|
|
634
|
+
"humanCheck.label": "Sprawdzamy, czy jesteś człowiekiem",
|
|
635
|
+
"error.humanCheck": "Nie udało się potwierdzić, że jesteś człowiekiem. Spróbuj ponownie.",
|
|
163
636
|
"error.connection": "Problem z połączeniem. Spróbuj ponownie.",
|
|
164
637
|
"error.history": "Nie udało się wczytać poprzedniej rozmowy.",
|
|
165
638
|
"error.updated": "Asystent został zaktualizowany. Odśwież stronę.",
|
|
@@ -195,9 +668,37 @@ const PL = {
|
|
|
195
668
|
"error.dictationBudget": "Dyktowanie jest niedostępne do końca dnia. Wiadomość możesz nadal wpisać."
|
|
196
669
|
};
|
|
197
670
|
/** Languages with a built-in dictionary; any other locale shows English texts. */
|
|
198
|
-
const TEXT_LOCALES = [
|
|
671
|
+
const TEXT_LOCALES = [
|
|
672
|
+
"en",
|
|
673
|
+
"cs",
|
|
674
|
+
"de",
|
|
675
|
+
"es",
|
|
676
|
+
"fr",
|
|
677
|
+
"it",
|
|
678
|
+
"pl"
|
|
679
|
+
];
|
|
199
680
|
const DICTIONARIES = {
|
|
200
681
|
en: EN,
|
|
682
|
+
cs: {
|
|
683
|
+
...EN,
|
|
684
|
+
...CS
|
|
685
|
+
},
|
|
686
|
+
de: {
|
|
687
|
+
...EN,
|
|
688
|
+
...DE
|
|
689
|
+
},
|
|
690
|
+
es: {
|
|
691
|
+
...EN,
|
|
692
|
+
...ES
|
|
693
|
+
},
|
|
694
|
+
fr: {
|
|
695
|
+
...EN,
|
|
696
|
+
...FR
|
|
697
|
+
},
|
|
698
|
+
it: {
|
|
699
|
+
...EN,
|
|
700
|
+
...IT
|
|
701
|
+
},
|
|
201
702
|
pl: {
|
|
202
703
|
...EN,
|
|
203
704
|
...PL
|
|
@@ -212,7 +713,7 @@ function textLocale(locale) {
|
|
|
212
713
|
const TEXT_KEYS = [.../* @__PURE__ */ new Set([...Object.keys(EN), ...PLURAL_BASES.flatMap((base) => PLURAL_FORMS.map((form) => `${base}.${form}`))])];
|
|
213
714
|
/**
|
|
214
715
|
* The full dictionary for a locale with overrides applied. Plural forms beyond `one`/`other`
|
|
215
|
-
* (Polish `few`, `many`) are kept too, so the widget can pick them.
|
|
716
|
+
* (Polish and Czech `few`, `many`) are kept too, so the widget can pick them.
|
|
216
717
|
*/
|
|
217
718
|
function textsFor(locale, overrides = {}) {
|
|
218
719
|
return {
|
|
@@ -700,6 +1201,306 @@ const readSuggestedReplies = (calls) => {
|
|
|
700
1201
|
const call = calls.findLast((stored) => stored.name === "suggest_replies" && stored.output !== void 0);
|
|
701
1202
|
return call && suggestedReplies(call.arguments);
|
|
702
1203
|
};
|
|
1204
|
+
const hook = z.custom((value) => typeof value === "function", "must be a function");
|
|
1205
|
+
/** The guardrail keys of the bot definition schema. */
|
|
1206
|
+
const guardrailShape = {
|
|
1207
|
+
moderation: z.object({
|
|
1208
|
+
model: z.string().trim().min(1, "is required"),
|
|
1209
|
+
check: z.enum([
|
|
1210
|
+
"input",
|
|
1211
|
+
"output",
|
|
1212
|
+
"both"
|
|
1213
|
+
]).optional(),
|
|
1214
|
+
categories: z.array(z.string().trim().min(1).max(64)).min(1).max(30).optional(),
|
|
1215
|
+
message: z.string().trim().min(1).max(300).optional()
|
|
1216
|
+
}).strict().optional(),
|
|
1217
|
+
onInput: hook.optional(),
|
|
1218
|
+
onOutput: hook.optional(),
|
|
1219
|
+
toolResults: z.enum(["trusted", "untrusted"]).optional()
|
|
1220
|
+
};
|
|
1221
|
+
/** Fills in the defaults: everything off. */
|
|
1222
|
+
function resolveGuardrails(options) {
|
|
1223
|
+
const { moderation } = options;
|
|
1224
|
+
const check = moderation?.check ?? "input";
|
|
1225
|
+
return Object.freeze({
|
|
1226
|
+
moderation: moderation ? Object.freeze({
|
|
1227
|
+
model: moderation.model.trim(),
|
|
1228
|
+
input: check !== "output",
|
|
1229
|
+
output: check !== "input",
|
|
1230
|
+
categories: moderation.categories ? Object.freeze(moderation.categories.map((category) => category.trim())) : void 0,
|
|
1231
|
+
message: moderation.message?.trim()
|
|
1232
|
+
}) : void 0,
|
|
1233
|
+
onInput: options.onInput,
|
|
1234
|
+
onOutput: options.onOutput,
|
|
1235
|
+
toolResults: options.toolResults ?? "trusted"
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
/** Whether visitor messages are checked before the model sees them. */
|
|
1239
|
+
const checksInput = (guardrails) => guardrails.onInput !== void 0 || guardrails.moderation?.input === true;
|
|
1240
|
+
/** Whether answers are checked, and so held back until complete. */
|
|
1241
|
+
const checksOutput = (guardrails) => guardrails.onOutput !== void 0 || guardrails.moderation?.output === true;
|
|
1242
|
+
// src/bot/define-bot.ts
|
|
1243
|
+
/** Marks a resolved bot; `Symbol.for`, so a second copy of this module recognises it too. */
|
|
1244
|
+
const BOT = Symbol.for("askdare.bot");
|
|
1245
|
+
const DEFAULT_LIMITS = {
|
|
1246
|
+
maxOutputTokens: 1024,
|
|
1247
|
+
maxInputChars: 4e3,
|
|
1248
|
+
maxSteps: 5,
|
|
1249
|
+
turnTimeoutMs: 12e4,
|
|
1250
|
+
dailyTokens: 2e6,
|
|
1251
|
+
dailyTokensPerIp: 2e5,
|
|
1252
|
+
sessionsPerIpPerHour: 30,
|
|
1253
|
+
conversationsPerIpPerHour: 20,
|
|
1254
|
+
messagesPerVisitorPerMinute: 10,
|
|
1255
|
+
messagesPerIpPerMinute: 30,
|
|
1256
|
+
maxTurns: 50,
|
|
1257
|
+
uploadsPerVisitorPerHour: 20,
|
|
1258
|
+
uploadsPerIpPerHour: 60,
|
|
1259
|
+
uploadsPerDay: 500,
|
|
1260
|
+
transcriptionsPerVisitorPerHour: 30,
|
|
1261
|
+
voiceSecondsPerDay: 3600,
|
|
1262
|
+
voiceSecondsPerIpPerDay: 600
|
|
1263
|
+
};
|
|
1264
|
+
/** An https URL or a path on your app (no protocol-relative URLs). */
|
|
1265
|
+
const LINK$1 = /^(https:\/\/[^\s"'<>\\]{1,500}|\/(?![/\\])[^\s"'<>\\]{0,500})$/;
|
|
1266
|
+
/** A same-origin path (served by your app, allowed by the iframe CSP) or a small raster data URL. */
|
|
1267
|
+
const AVATAR = /^(\/(?!\/)[\w\-./%]{1,200}|data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]{1,90000})$/;
|
|
1268
|
+
const origin = z.string().refine((value) => {
|
|
1269
|
+
try {
|
|
1270
|
+
const url = new URL(value);
|
|
1271
|
+
return (url.protocol === "https:" || url.protocol === "http:" && /^(localhost|127\.0\.0\.1|\[::1\]|.+\.localhost)$/.test(url.hostname)) && url.origin === value && /^[a-z0-9.-]+$|^\[[0-9a-f:]+\]$/i.test(url.hostname);
|
|
1272
|
+
} catch {
|
|
1273
|
+
return false;
|
|
1274
|
+
}
|
|
1275
|
+
}, "must be an https origin like https://www.example.com (no path or wildcard; http only for localhost)");
|
|
1276
|
+
const flatTexts = z.partialRecord(z.enum(TEXT_KEYS), z.string().trim().min(1).max(300));
|
|
1277
|
+
const textsPerLanguage = z.record(z.string(), flatTexts).refine((sets) => Object.keys(sets).every((tag) => canonicalLocale(tag) !== void 0), "must use BCP 47 tags like en or pl-PL as languages").refine((sets) => Object.keys(sets).length <= 20, "has more than 20 languages").refine((sets) => {
|
|
1278
|
+
const tags = Object.keys(sets).map((tag) => canonicalLocale(tag));
|
|
1279
|
+
return new Set(tags).size === tags.length;
|
|
1280
|
+
}, "has the same language twice");
|
|
1281
|
+
/** Per-language when any value is a set of texts; a flat set has only strings. */
|
|
1282
|
+
const isPerLanguage = (value) => typeof value === "object" && value !== null && Object.values(value).some((entry) => typeof entry === "object" && entry !== null);
|
|
1283
|
+
const textsSchema = z.unknown().superRefine((value, context) => {
|
|
1284
|
+
const result = (isPerLanguage(value) ? textsPerLanguage : flatTexts).safeParse(value);
|
|
1285
|
+
for (const issue of result.error?.issues ?? []) context.addIssue({
|
|
1286
|
+
code: "custom",
|
|
1287
|
+
message: issue.message,
|
|
1288
|
+
path: issue.path
|
|
1289
|
+
});
|
|
1290
|
+
});
|
|
1291
|
+
/**
|
|
1292
|
+
* The overrides a visitor in `locale` gets: the set for every language, then the per-language set
|
|
1293
|
+
* for the tag, else its primary subtag, else the `en` set when the language has no built-in
|
|
1294
|
+
* dictionary (so its texts are English anyway).
|
|
1295
|
+
*/
|
|
1296
|
+
function widgetTexts(widget, locale) {
|
|
1297
|
+
const own = languageTexts(widget, locale) ?? (textLocale(locale) === "en" ? widget.textsByLocale["en"] : void 0);
|
|
1298
|
+
return own ? {
|
|
1299
|
+
...widget.texts,
|
|
1300
|
+
...own
|
|
1301
|
+
} : widget.texts;
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* The per-language set written for this language, if any: the one for its tag, else for its
|
|
1305
|
+
* primary subtag, else the first one for another tag of the same language (`pl-PL` for `pl`).
|
|
1306
|
+
*/
|
|
1307
|
+
function languageTexts(widget, locale) {
|
|
1308
|
+
const tag = canonicalLocale(locale) ?? locale;
|
|
1309
|
+
const sets = widget.textsByLocale;
|
|
1310
|
+
const language = primarySubtag(tag);
|
|
1311
|
+
return sets[tag] ?? sets[language] ?? Object.entries(sets).find(([other]) => primarySubtag(other) === language)?.[1];
|
|
1312
|
+
}
|
|
1313
|
+
/** The language part of a BCP 47 tag, lowercase: `pl` for `pl-PL`. */
|
|
1314
|
+
const primarySubtag = (tag) => (tag.split("-")[0] ?? tag).toLowerCase();
|
|
1315
|
+
const definitionSchema = z.object({
|
|
1316
|
+
id: z.string().regex(/^[a-z0-9][a-z0-9-]{0,47}$/, "use 1-48 lowercase letters, digits or dashes"),
|
|
1317
|
+
model: z.string().trim().min(1, "is required"),
|
|
1318
|
+
instructions: z.union([z.string().trim().min(1, "must not be empty"), z.function()]),
|
|
1319
|
+
limits: z.object({
|
|
1320
|
+
maxOutputTokens: z.number().int().min(16).max(128e3).optional(),
|
|
1321
|
+
maxInputChars: z.number().int().min(1).max(1e5).optional(),
|
|
1322
|
+
maxSteps: z.number().int().min(1).max(20).optional(),
|
|
1323
|
+
turnTimeoutMs: z.number().int().min(1e3).max(9e5).optional(),
|
|
1324
|
+
dailyTokens: z.number().int().min(1e3).optional(),
|
|
1325
|
+
dailyTokensPerIp: z.number().int().min(100).optional(),
|
|
1326
|
+
sessionsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
|
|
1327
|
+
conversationsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
|
|
1328
|
+
messagesPerVisitorPerMinute: z.number().int().min(1).max(1e3).optional(),
|
|
1329
|
+
messagesPerIpPerMinute: z.number().int().min(1).max(1e4).optional(),
|
|
1330
|
+
maxTurns: z.number().int().min(1).max(1e3).optional(),
|
|
1331
|
+
uploadsPerVisitorPerHour: z.number().int().min(1).max(1e3).optional(),
|
|
1332
|
+
uploadsPerIpPerHour: z.number().int().min(1).max(1e4).optional(),
|
|
1333
|
+
uploadsPerDay: z.number().int().min(1).max(1e6).optional(),
|
|
1334
|
+
transcriptionsPerVisitorPerHour: z.number().int().min(1).max(1e3).optional(),
|
|
1335
|
+
voiceSecondsPerDay: z.number().int().min(60).optional(),
|
|
1336
|
+
voiceSecondsPerIpPerDay: z.number().int().min(60).optional()
|
|
1337
|
+
}).optional(),
|
|
1338
|
+
tools: z.array(z.custom((value) => typeof value === "object" && value !== null && "execute" in value, "must be created with defineTool()")).max(64).refine((tools) => new Set(tools.map((tool) => tool.name)).size === tools.length, "must have unique names").refine((tools) => tools.every((tool) => tool.name !== "file_search"), "must not use the reserved name file_search").refine((tools) => tools.every((tool) => tool.name !== SUGGEST_REPLIES), `must not use the reserved name ${SUGGEST_REPLIES}`).optional(),
|
|
1339
|
+
pageContext: z.boolean().optional(),
|
|
1340
|
+
knowledge: z.object({
|
|
1341
|
+
vectorStoreId: z.string().regex(/^vs_[A-Za-z0-9_-]+$/, "must be a vector store ID like vs_…"),
|
|
1342
|
+
maxResults: z.number().int().min(1).max(50).optional()
|
|
1343
|
+
}).optional(),
|
|
1344
|
+
attachments: z.object({
|
|
1345
|
+
images: z.boolean().optional(),
|
|
1346
|
+
pdf: z.boolean().optional(),
|
|
1347
|
+
maxBytes: z.number().int().min(1e3).max(2e7).optional(),
|
|
1348
|
+
maxPerMessage: z.number().int().min(1).max(10).optional(),
|
|
1349
|
+
maxPdfPages: z.number().int().min(1).max(500).optional()
|
|
1350
|
+
}).refine((value) => value.images !== false || value.pdf !== false, "must allow images or pdf").optional(),
|
|
1351
|
+
voice: z.object({
|
|
1352
|
+
model: z.string().trim().min(1, "is required"),
|
|
1353
|
+
maxSeconds: z.number().int().min(5).max(300).optional()
|
|
1354
|
+
}).optional(),
|
|
1355
|
+
security: z.object({
|
|
1356
|
+
allowedOrigins: z.array(origin).max(50).optional(),
|
|
1357
|
+
humanVerifier: z.custom((value) => typeof value === "object" && value !== null && typeof value.verify === "function" && value.challenge?.provider === "turnstile" && /^[A-Za-z0-9_-]{1,100}$/.test(String(value.challenge?.siteKey)), "must be created with turnstile() or implement HumanVerifier").optional()
|
|
1358
|
+
}).optional(),
|
|
1359
|
+
embedPath: z.string().refine(isEmbedPath, "must be a path of this app like /askdare/support").optional(),
|
|
1360
|
+
widget: z.object({
|
|
1361
|
+
title: z.string().trim().min(1).max(80).optional(),
|
|
1362
|
+
greeting: z.string().trim().min(1).max(500).optional(),
|
|
1363
|
+
placeholder: z.string().trim().min(1).max(120).optional(),
|
|
1364
|
+
locale: z.string().refine((value) => value === "auto" || canonicalLocale(value) !== void 0, "must be auto or a BCP 47 tag like en or pl-PL").optional(),
|
|
1365
|
+
texts: textsSchema.optional(),
|
|
1366
|
+
disclosure: z.union([z.literal(false), z.object({ privacyUrl: z.string().regex(LINK$1, "must be an https URL or a path like /privacy").optional() }).strict()]).optional(),
|
|
1367
|
+
css: z.string().max(5e4).optional(),
|
|
1368
|
+
subtitle: z.string().trim().min(1).max(120).optional(),
|
|
1369
|
+
starters: z.array(z.string().trim().min(1).max(80)).max(4).optional(),
|
|
1370
|
+
feedback: z.boolean().optional(),
|
|
1371
|
+
replies: z.enum(["suggest", "off"]).optional(),
|
|
1372
|
+
avatar: z.string().regex(AVATAR, "must be a path like /avatar.png or a PNG, JPEG, WebP or GIF data URL").optional(),
|
|
1373
|
+
launcherLabel: z.string().trim().min(1).max(40).optional(),
|
|
1374
|
+
theme: z.union([z.enum(PRESET_NAMES), themeDefinitionSchema]).optional(),
|
|
1375
|
+
colorScheme: z.enum([
|
|
1376
|
+
"auto",
|
|
1377
|
+
"light",
|
|
1378
|
+
"dark"
|
|
1379
|
+
]).optional()
|
|
1380
|
+
}).optional(),
|
|
1381
|
+
...guardrailShape
|
|
1382
|
+
});
|
|
1383
|
+
/**
|
|
1384
|
+
* Declares a chatbot. Validates eagerly so misconfiguration fails at startup, not on the first
|
|
1385
|
+
* visitor's message.
|
|
1386
|
+
*/
|
|
1387
|
+
function defineBot(definition) {
|
|
1388
|
+
return createBot(definition);
|
|
1389
|
+
}
|
|
1390
|
+
/** The resolved bot behind a handle, or a TypeError when it didn't come from `defineBot`. */
|
|
1391
|
+
function botOf(handle) {
|
|
1392
|
+
if (!isBot(handle)) throw new TypeError(`[askdare] Bot "${handle.id}" was not made by defineBot().`);
|
|
1393
|
+
return handle;
|
|
1394
|
+
}
|
|
1395
|
+
function isBot(handle) {
|
|
1396
|
+
return BOT in handle;
|
|
1397
|
+
}
|
|
1398
|
+
/** `defineBot` for code inside the library, typed with the resolved settings. */
|
|
1399
|
+
function createBot(definition) {
|
|
1400
|
+
const parsed = definitionSchema.safeParse(definition);
|
|
1401
|
+
if (!parsed.success) {
|
|
1402
|
+
const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"} ${issue.message}`).join("; ");
|
|
1403
|
+
const hint = parsed.error.issues.some((issue) => issue.path.join(".") === "model") ? " Set the model in the bot definition, usually as model: process.env.ASKDARE_MODEL with ASKDARE_MODEL in .env.local and in every environment that builds or runs the app (on Vercel: Production and Preview)." : "";
|
|
1404
|
+
throw new TypeError(`[askdare] Invalid bot "${String(definition.id)}": ${issues}.${hint}`);
|
|
1405
|
+
}
|
|
1406
|
+
const { instructions } = definition;
|
|
1407
|
+
const widget = definition.widget ?? {};
|
|
1408
|
+
const locale = widget.locale ?? "en";
|
|
1409
|
+
const perLanguage = isPerLanguage(widget.texts);
|
|
1410
|
+
const textsByLocale = Object.freeze(perLanguage ? Object.fromEntries(Object.entries(widget.texts).map(([tag, set]) => [canonicalLocale(tag) ?? tag, Object.freeze({ ...set })])) : {});
|
|
1411
|
+
const overrides = Object.freeze({
|
|
1412
|
+
...perLanguage ? {} : widget.texts,
|
|
1413
|
+
...widget.title ? { "header.title": widget.title } : {},
|
|
1414
|
+
...widget.greeting ? { "welcome.greeting": widget.greeting } : {},
|
|
1415
|
+
...widget.placeholder ? { "composer.placeholder": widget.placeholder } : {},
|
|
1416
|
+
...widget.launcherLabel ? { "launcher.label": widget.launcherLabel } : {}
|
|
1417
|
+
});
|
|
1418
|
+
const ownLocale = locale === "auto" ? "en" : locale;
|
|
1419
|
+
const texts = textsFor(ownLocale, widgetTexts({
|
|
1420
|
+
texts: overrides,
|
|
1421
|
+
textsByLocale
|
|
1422
|
+
}, ownLocale));
|
|
1423
|
+
const theme = resolveTheme(definition.widget?.theme, definition.widget?.colorScheme ?? "auto");
|
|
1424
|
+
if (typeof definition.widget?.theme === "object" && globalThis.process?.env?.["NODE_ENV"] !== "production") for (const warning of themeWarnings(theme)) console.warn(`[askdare] Bot "${definition.id}" theme: ${warning}.`);
|
|
1425
|
+
return Object.freeze({
|
|
1426
|
+
[BOT]: true,
|
|
1427
|
+
id: definition.id,
|
|
1428
|
+
model: definition.model.trim(),
|
|
1429
|
+
instructions: typeof instructions === "string" ? () => instructions : instructions,
|
|
1430
|
+
limits: Object.freeze({
|
|
1431
|
+
...DEFAULT_LIMITS,
|
|
1432
|
+
...definition.limits
|
|
1433
|
+
}),
|
|
1434
|
+
tools: Object.freeze([...definition.tools ?? []]),
|
|
1435
|
+
pageContext: definition.pageContext ?? false,
|
|
1436
|
+
knowledge: definition.knowledge ? Object.freeze({
|
|
1437
|
+
vectorStoreId: definition.knowledge.vectorStoreId,
|
|
1438
|
+
maxResults: definition.knowledge.maxResults ?? 5
|
|
1439
|
+
}) : void 0,
|
|
1440
|
+
attachments: definition.attachments ? Object.freeze({
|
|
1441
|
+
images: definition.attachments.images ?? true,
|
|
1442
|
+
pdf: definition.attachments.pdf ?? true,
|
|
1443
|
+
maxBytes: definition.attachments.maxBytes ?? 4e6,
|
|
1444
|
+
maxPerMessage: definition.attachments.maxPerMessage ?? 3,
|
|
1445
|
+
maxPdfPages: definition.attachments.maxPdfPages ?? 50
|
|
1446
|
+
}) : void 0,
|
|
1447
|
+
voice: definition.voice ? Object.freeze({
|
|
1448
|
+
model: definition.voice.model.trim(),
|
|
1449
|
+
maxSeconds: definition.voice.maxSeconds ?? 60
|
|
1450
|
+
}) : void 0,
|
|
1451
|
+
security: Object.freeze({
|
|
1452
|
+
allowedOrigins: Object.freeze([...new Set(definition.security?.allowedOrigins ?? [])]),
|
|
1453
|
+
humanVerifier: definition.security?.humanVerifier
|
|
1454
|
+
}),
|
|
1455
|
+
embedPath: definition.embedPath,
|
|
1456
|
+
widget: Object.freeze({
|
|
1457
|
+
title: texts["header.title"] ?? "",
|
|
1458
|
+
subtitle: widget.subtitle ?? "",
|
|
1459
|
+
greeting: texts["welcome.greeting"] ?? "",
|
|
1460
|
+
placeholder: texts["composer.placeholder"] ?? "",
|
|
1461
|
+
locale,
|
|
1462
|
+
starters: Object.freeze([...widget.starters ?? []]),
|
|
1463
|
+
feedback: widget.feedback ?? true,
|
|
1464
|
+
replies: widget.replies ?? "off",
|
|
1465
|
+
avatar: widget.avatar,
|
|
1466
|
+
launcherLabel: texts["launcher.label"] ?? "",
|
|
1467
|
+
texts: overrides,
|
|
1468
|
+
textsByLocale,
|
|
1469
|
+
disclosure: widget.disclosure === false ? false : Object.freeze({ privacyUrl: widget.disclosure?.privacyUrl }),
|
|
1470
|
+
css: widget.css ?? "",
|
|
1471
|
+
theme
|
|
1472
|
+
}),
|
|
1473
|
+
guardrails: resolveGuardrails(definition)
|
|
1474
|
+
});
|
|
1475
|
+
}
|
|
1476
|
+
// src/protocol/events.ts
|
|
1477
|
+
/** Stable error codes sent to clients. The accompanying message never contains internals. */
|
|
1478
|
+
const ERROR_CODES = [
|
|
1479
|
+
"invalid_input",
|
|
1480
|
+
"unauthorized",
|
|
1481
|
+
"session_expired",
|
|
1482
|
+
"not_found",
|
|
1483
|
+
"rate_limited",
|
|
1484
|
+
"budget_exceeded",
|
|
1485
|
+
"bot_unavailable",
|
|
1486
|
+
"content_blocked",
|
|
1487
|
+
"timeout",
|
|
1488
|
+
"upstream_error",
|
|
1489
|
+
"internal_error"
|
|
1490
|
+
];
|
|
1491
|
+
const PROTOCOL_EVENT_TYPES = [
|
|
1492
|
+
"conversation.created",
|
|
1493
|
+
"user.ack",
|
|
1494
|
+
"message.start",
|
|
1495
|
+
"reasoning",
|
|
1496
|
+
"text.delta",
|
|
1497
|
+
"citation",
|
|
1498
|
+
"tool.status",
|
|
1499
|
+
"tool.ui",
|
|
1500
|
+
"replies",
|
|
1501
|
+
"message.end",
|
|
1502
|
+
"error"
|
|
1503
|
+
];
|
|
703
1504
|
// src/protocol/version.ts
|
|
704
1505
|
/**
|
|
705
1506
|
* Version of the SSE wire protocol between the askdare server and its clients.
|
|
@@ -708,6 +1509,107 @@ const readSuggestedReplies = (calls) => {
|
|
|
708
1509
|
const PROTOCOL_VERSION = 1;
|
|
709
1510
|
/** Response header carrying {@link PROTOCOL_VERSION} on every streaming response. */
|
|
710
1511
|
const PROTOCOL_HEADER = "x-askdare-protocol";
|
|
1512
|
+
// src/errors.ts
|
|
1513
|
+
const HTTP_STATUS = {
|
|
1514
|
+
invalid_input: 400,
|
|
1515
|
+
unauthorized: 401,
|
|
1516
|
+
session_expired: 401,
|
|
1517
|
+
not_found: 404,
|
|
1518
|
+
content_blocked: 422,
|
|
1519
|
+
rate_limited: 429,
|
|
1520
|
+
budget_exceeded: 429,
|
|
1521
|
+
internal_error: 500,
|
|
1522
|
+
upstream_error: 502,
|
|
1523
|
+
bot_unavailable: 503,
|
|
1524
|
+
timeout: 504
|
|
1525
|
+
};
|
|
1526
|
+
const DEFAULT_MESSAGES = {
|
|
1527
|
+
invalid_input: "The request was invalid.",
|
|
1528
|
+
unauthorized: "Authentication is required.",
|
|
1529
|
+
session_expired: "Your session has expired. Please try again.",
|
|
1530
|
+
not_found: "Not found.",
|
|
1531
|
+
content_blocked: "This message cannot be processed.",
|
|
1532
|
+
rate_limited: "Too many messages. Please wait a moment.",
|
|
1533
|
+
budget_exceeded: "The assistant is unavailable for the rest of the day.",
|
|
1534
|
+
internal_error: "Something went wrong. Please try again.",
|
|
1535
|
+
upstream_error: "The assistant is temporarily unavailable. Please try again.",
|
|
1536
|
+
bot_unavailable: "The assistant is currently unavailable.",
|
|
1537
|
+
timeout: "The assistant took too long to respond. Please try again."
|
|
1538
|
+
};
|
|
1539
|
+
/** An error with a stable, client-safe code. Anything else that escapes becomes `internal_error`. */
|
|
1540
|
+
var AskdareError = class extends Error {
|
|
1541
|
+
name = "AskdareError";
|
|
1542
|
+
code;
|
|
1543
|
+
status;
|
|
1544
|
+
retryAfterMs;
|
|
1545
|
+
key;
|
|
1546
|
+
params;
|
|
1547
|
+
constructor(code, options = {}) {
|
|
1548
|
+
super(options.message ?? DEFAULT_MESSAGES[code], { cause: options.cause });
|
|
1549
|
+
this.code = code;
|
|
1550
|
+
this.status = HTTP_STATUS[code];
|
|
1551
|
+
this.retryAfterMs = options.retryAfterMs;
|
|
1552
|
+
this.key = options.key ?? (options.message === void 0 ? `error.${code}` : void 0);
|
|
1553
|
+
this.params = options.params;
|
|
1554
|
+
}
|
|
1555
|
+
};
|
|
1556
|
+
/** The caller's own signal aborted the work (for example, the visitor closed the chat). Not an error to report. */
|
|
1557
|
+
var TurnAbortedError = class extends Error {
|
|
1558
|
+
name = "TurnAbortedError";
|
|
1559
|
+
};
|
|
1560
|
+
/** Normalizes anything thrown into a {@link AskdareError} without exposing its details. */
|
|
1561
|
+
function toAskdareError(error) {
|
|
1562
|
+
return error instanceof AskdareError ? error : new AskdareError("internal_error", { cause: error });
|
|
1563
|
+
}
|
|
1564
|
+
/** API keys never reach a log line, a report or the chat: `sk-proj-abc…` keeps only its prefix. */
|
|
1565
|
+
function scrub(text) {
|
|
1566
|
+
return text.replace(/\b(sk|rk)-[A-Za-z0-9_-]{6,}/g, (key) => `${key.slice(0, 3)}…`);
|
|
1567
|
+
}
|
|
1568
|
+
/** Longer quoted values in an error message may be the visitor's text, not configuration. */
|
|
1569
|
+
const LONG_QUOTE = /(['"`])[^'"`]{33,}\1/g;
|
|
1570
|
+
const MAX_MESSAGE = 300;
|
|
1571
|
+
/**
|
|
1572
|
+
* An error message fit for a log line: API keys cut down to their prefix (a 401 quotes part of the
|
|
1573
|
+
* key), quoted values longer than 32 characters replaced (a 400 can quote the value it rejected,
|
|
1574
|
+
* which may be what the visitor wrote), and the whole capped. Model names, parameters and IDs stay.
|
|
1575
|
+
*/
|
|
1576
|
+
function loggableMessage(message) {
|
|
1577
|
+
const text = scrub(message).replace(LONG_QUOTE, (_, quote) => `${quote}[…]${quote}`);
|
|
1578
|
+
return text.length > MAX_MESSAGE ? `${text.slice(0, MAX_MESSAGE)}…` : text;
|
|
1579
|
+
}
|
|
1580
|
+
/**
|
|
1581
|
+
* The cause of an error as the server logs it when no `onError` is set (ADR-0004: no content in
|
|
1582
|
+
* logs): an `Error` keeps its name, stack frames and status, code and request ID, with its message
|
|
1583
|
+
* passed through {@link loggableMessage}; a string is cleaned the same way; anything else is
|
|
1584
|
+
* logged as its type only.
|
|
1585
|
+
*/
|
|
1586
|
+
function forLog(cause) {
|
|
1587
|
+
if (cause === void 0) return void 0;
|
|
1588
|
+
if (typeof cause === "string") return loggableMessage(cause);
|
|
1589
|
+
if (!(cause instanceof Error)) return `[${typeof cause}]`;
|
|
1590
|
+
const copy = new Error(loggableMessage(cause.message));
|
|
1591
|
+
copy.name = cause.name;
|
|
1592
|
+
const frames = (cause.stack ?? "").split("\n").filter((line) => /^\s+at /.test(line));
|
|
1593
|
+
copy.stack = [`${copy.name}: ${copy.message}`, ...frames].join("\n");
|
|
1594
|
+
const { status, code, requestId } = cause;
|
|
1595
|
+
return Object.assign(copy, {
|
|
1596
|
+
...status === void 0 ? {} : { status },
|
|
1597
|
+
...code === void 0 ? {} : { code },
|
|
1598
|
+
...requestId === void 0 ? {} : { requestId }
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
// src/security/human-verifier.ts
|
|
1602
|
+
/** Where Cloudflare serves Turnstile's script and frame; the iframe's CSP allows it for such bots. */
|
|
1603
|
+
const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
|
|
1604
|
+
/** Longest token Turnstile issues. */
|
|
1605
|
+
const HUMAN_TOKEN_MAX_LENGTH = 2048;
|
|
1606
|
+
/**
|
|
1607
|
+
* The Turnstile `action` the chat renders for a bot and the server expects back: the bot id, cut
|
|
1608
|
+
* to Turnstile's 32 characters (bot ids use only characters it accepts).
|
|
1609
|
+
*/
|
|
1610
|
+
const turnstileAction = (botId) => botId.slice(0, 32);
|
|
1611
|
+
/** The origins a challenge's script and frame come from, for the iframe's CSP. */
|
|
1612
|
+
const CHALLENGE_ORIGINS = { turnstile: TURNSTILE_ORIGIN };
|
|
711
1613
|
/**
|
|
712
1614
|
* A URL or something a browser or a chat app would turn into a link: a scheme (`https://`,
|
|
713
1615
|
* `mailto:`, `javascript:` …), `www.`, an IP address or a domain name such as `example.com`.
|
|
@@ -741,8 +1643,53 @@ function normalizeReplies(values) {
|
|
|
741
1643
|
}
|
|
742
1644
|
return replies.length > 0 ? replies : void 0;
|
|
743
1645
|
}
|
|
744
|
-
|
|
1646
|
+
/** A tool's name: what `defineTool` accepts and what the protocol carries. */
|
|
745
1647
|
const TOOL_NAME = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
1648
|
+
/** Whether a value is plain JSON: no `undefined`, functions, class instances or `NaN`. */
|
|
1649
|
+
function isPlainJson(value, depth) {
|
|
1650
|
+
switch (typeof value) {
|
|
1651
|
+
case "string":
|
|
1652
|
+
case "boolean": return true;
|
|
1653
|
+
case "number": return Number.isFinite(value);
|
|
1654
|
+
case "object": {
|
|
1655
|
+
if (value === null) return true;
|
|
1656
|
+
if (depth >= 8) return false;
|
|
1657
|
+
if (Array.isArray(value)) {
|
|
1658
|
+
for (let index = 0; index < value.length; index += 1) if (!(index in value) || !isPlainJson(value[index], depth + 1)) return false;
|
|
1659
|
+
return true;
|
|
1660
|
+
}
|
|
1661
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1662
|
+
if (prototype !== Object.prototype && prototype !== null) return false;
|
|
1663
|
+
return Object.values(value).every((item) => isPlainJson(item, depth + 1));
|
|
1664
|
+
}
|
|
1665
|
+
default: return false;
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
/** The payload's JSON, or undefined when it isn't plain JSON within the size and depth limits. */
|
|
1669
|
+
function wireJson(value) {
|
|
1670
|
+
if (value === null || value === void 0 || !isPlainJson(value, 0)) return void 0;
|
|
1671
|
+
const json = JSON.stringify(value);
|
|
1672
|
+
return new TextEncoder().encode(json).length <= 8192 ? json : void 0;
|
|
1673
|
+
}
|
|
1674
|
+
/**
|
|
1675
|
+
* The payload as it goes over the wire: a fresh copy of plain JSON within the limits, or
|
|
1676
|
+
* undefined when it breaks one. A payload is sent whole or not at all, never cut.
|
|
1677
|
+
*/
|
|
1678
|
+
function toToolUiData(value) {
|
|
1679
|
+
const json = wireJson(value);
|
|
1680
|
+
return json === void 0 ? void 0 : JSON.parse(json);
|
|
1681
|
+
}
|
|
1682
|
+
/** One payload as it goes over the wire: a call ID, a tool name and data within the limits. */
|
|
1683
|
+
function isToolUi(value) {
|
|
1684
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
1685
|
+
const { callId, name, data } = value;
|
|
1686
|
+
return typeof callId === "string" && callId.length > 0 && callId.length <= 128 && typeof name === "string" && TOOL_NAME.test(name) && wireJson(data) !== void 0;
|
|
1687
|
+
}
|
|
1688
|
+
/** A list of payloads as it goes over the wire: 1 to 4, each valid, no call twice. */
|
|
1689
|
+
function isToolUiList(value) {
|
|
1690
|
+
return Array.isArray(value) && value.length > 0 && value.length <= 4 && value.every(isToolUi) && new Set(value.map((item) => item.callId)).size === value.length;
|
|
1691
|
+
}
|
|
1692
|
+
// src/tools/define-tool.ts
|
|
746
1693
|
/** Finds fields OpenAI strict mode would reject, so they fail at startup instead of mid-chat. */
|
|
747
1694
|
function strictModeProblems(schema, path) {
|
|
748
1695
|
if (schema instanceof z.ZodOptional || schema instanceof z.ZodDefault) return [`${path || "(root)"} is optional; use .nullable() so the field is always present`];
|
|
@@ -764,6 +1711,7 @@ function defineTool(definition) {
|
|
|
764
1711
|
const timeoutMs = definition.timeoutMs ?? 1e4;
|
|
765
1712
|
if (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 12e4) problems.push("timeoutMs must be an integer between 100 and 120000");
|
|
766
1713
|
if (definition.replies !== void 0 && typeof definition.replies !== "function") problems.push("replies must be a function of the result");
|
|
1714
|
+
if (definition.ui !== void 0 && typeof definition.ui !== "function") problems.push("ui must be a function of the result");
|
|
767
1715
|
if (problems.length > 0) throw new TypeError(`[askdare] Invalid tool "${definition.name}": ${problems.join("; ")}`);
|
|
768
1716
|
return Object.freeze({
|
|
769
1717
|
name: definition.name,
|
|
@@ -771,9 +1719,21 @@ function defineTool(definition) {
|
|
|
771
1719
|
input: definition.input,
|
|
772
1720
|
execute: definition.execute,
|
|
773
1721
|
timeoutMs,
|
|
774
|
-
...definition.replies ? { replies: definition.replies } : {}
|
|
1722
|
+
...definition.replies ? { replies: definition.replies } : {},
|
|
1723
|
+
...definition.ui ? { ui: definition.ui } : {}
|
|
775
1724
|
});
|
|
776
1725
|
}
|
|
1726
|
+
/** The tool's output for a call, if it ran with arguments that fit its schema and succeeded. */
|
|
1727
|
+
function successfulOutput(tool, call) {
|
|
1728
|
+
if (call.output === void 0) return void 0;
|
|
1729
|
+
let args;
|
|
1730
|
+
try {
|
|
1731
|
+
args = JSON.parse(call.arguments);
|
|
1732
|
+
} catch {
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
return tool.input.safeParse(args).success ? JSON.parse(call.output) : void 0;
|
|
1736
|
+
}
|
|
777
1737
|
/**
|
|
778
1738
|
* The options a turn's calls define, oldest call first (ADR-0015): the last call that
|
|
779
1739
|
* defines any wins. The live turn and the history both pick them here, from the stored JSON, so a
|
|
@@ -785,10 +1745,11 @@ function readToolReplies(tools, calls, onError) {
|
|
|
785
1745
|
let replies;
|
|
786
1746
|
for (const call of calls) {
|
|
787
1747
|
const tool = tools.find((candidate) => candidate.name === call.name);
|
|
788
|
-
if (!tool?.replies
|
|
1748
|
+
if (!tool?.replies) continue;
|
|
789
1749
|
try {
|
|
790
|
-
|
|
791
|
-
|
|
1750
|
+
const output = successfulOutput(tool, call);
|
|
1751
|
+
if (output === void 0) continue;
|
|
1752
|
+
const items = tool.replies(output);
|
|
792
1753
|
const offered = Array.isArray(items) ? normalizeReplies(items) : void 0;
|
|
793
1754
|
if (offered) replies = offered;
|
|
794
1755
|
} catch (error) {
|
|
@@ -797,4 +1758,41 @@ function readToolReplies(tools, calls, onError) {
|
|
|
797
1758
|
}
|
|
798
1759
|
return replies;
|
|
799
1760
|
}
|
|
800
|
-
|
|
1761
|
+
/** A `ui` payload broke the limits of ADR-0017; it says so without quoting the payload. */
|
|
1762
|
+
var ToolUiLimitError = class extends Error {
|
|
1763
|
+
constructor() {
|
|
1764
|
+
super("the payload is not plain JSON of at most 8 KB and 8 levels");
|
|
1765
|
+
this.name = "ToolUiLimitError";
|
|
1766
|
+
}
|
|
1767
|
+
};
|
|
1768
|
+
/**
|
|
1769
|
+
* The payloads a turn's calls define for the visitor, in call order (ADR-0017), as the live turn
|
|
1770
|
+
* and the history both send them. A call without an ID, a failed call and a tool without `ui`
|
|
1771
|
+
* define none. A `ui` that throws, or returns a payload over the limits, defines none either;
|
|
1772
|
+
* `onError` hears about it. The caller keeps at most `MAX_TOOL_UI` per answer.
|
|
1773
|
+
*/
|
|
1774
|
+
function readToolUi(tools, calls, onError) {
|
|
1775
|
+
const payloads = [];
|
|
1776
|
+
for (const call of calls) {
|
|
1777
|
+
const tool = tools.find((candidate) => candidate.name === call.name);
|
|
1778
|
+
if (!tool?.ui || call.callId === void 0 || call.output === void 0) continue;
|
|
1779
|
+
try {
|
|
1780
|
+
const output = successfulOutput(tool, call);
|
|
1781
|
+
if (output === void 0) continue;
|
|
1782
|
+
const value = tool.ui(output);
|
|
1783
|
+
if (value === void 0 || value === null) continue;
|
|
1784
|
+
const data = toToolUiData(value);
|
|
1785
|
+
if (data === void 0) throw new ToolUiLimitError();
|
|
1786
|
+
const payload = {
|
|
1787
|
+
callId: call.callId,
|
|
1788
|
+
name: tool.name,
|
|
1789
|
+
data
|
|
1790
|
+
};
|
|
1791
|
+
if (isToolUi(payload)) payloads.push(payload);
|
|
1792
|
+
} catch (error) {
|
|
1793
|
+
onError?.(tool, error);
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
return payloads;
|
|
1797
|
+
}
|
|
1798
|
+
export { SUGGEST_REPLIES_OUTPUT as A, canonicalLocale as B, languageTexts as C, checksOutput as D, checksInput as E, resolveTheme as F, isInside as H, PRESET_NAMES as I, TEXT_LOCALES as L, readSuggestedReplies as M, suggestedReplies as N, SUGGEST_REPLIES as O, defineTheme as P, textLocale as R, defineBot as S, widgetTexts as T, isBasePath as V, PROTOCOL_HEADER as _, isToolUiList as a, PROTOCOL_EVENT_TYPES as b, HUMAN_TOKEN_MAX_LENGTH as c, AskdareError as d, TurnAbortedError as f, toAskdareError as g, scrub as h, readToolUi as i, SUGGEST_REPLIES_PARAMETERS as j, SUGGEST_REPLIES_DESCRIPTION as k, TURNSTILE_ORIGIN as l, loggableMessage as m, defineTool as n, normalizeReplies as o, forLog as p, readToolReplies as r, CHALLENGE_ORIGINS as s, ToolUiLimitError as t, turnstileAction as u, PROTOCOL_VERSION as v, primarySubtag as w, botOf as x, ERROR_CODES as y, textsFor as z };
|