domma-cms 1.70.0 → 1.71.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/admin/js/lib/sidebar-frequent.js +1 -1
- package/admin/js/templates/docs/usage-tools.html +1 -1
- package/docs/DommaFeatures.md +46 -12
- package/package.json +1 -1
- package/plugins/feedback/CHANGELOG.md +5 -0
- package/plugins/feedback/CLAUDE.md +26 -0
- package/plugins/feedback/admin/css/index.css +11 -0
- package/plugins/feedback/admin/lib/ai.js +41 -0
- package/plugins/feedback/admin/lib/kit.js +3 -1
- package/plugins/feedback/admin/views/feedback.js +1 -1
- package/plugins/feedback/admin/views/inbox.js +58 -2
- package/plugins/feedback/docs/guide.md +2 -0
- package/plugins/feedback/lib/ai-text.js +217 -0
- package/plugins/feedback/lib/receiver.js +10 -0
- package/plugins/feedback/lib/themes.js +75 -0
- package/plugins/feedback/plugin.js +39 -2
- package/plugins/feedback/plugin.json +2 -2
- package/plugins/feedback/tests/ai.test.js +248 -0
- package/plugins/free-tier.lock.json +31 -21
- package/plugins/support/CHANGELOG.md +5 -0
- package/plugins/support/CLAUDE.md +33 -0
- package/plugins/support/admin/css/index.css +14 -0
- package/plugins/support/admin/lib/ai.js +68 -0
- package/plugins/support/admin/lib/kit.js +5 -1
- package/plugins/support/admin/views/inbox.js +121 -4
- package/plugins/support/admin/views/support.js +1 -1
- package/plugins/support/docs/guide.md +5 -0
- package/plugins/support/lib/ai-text.js +217 -0
- package/plugins/support/lib/assist.js +74 -0
- package/plugins/support/lib/receiver.js +2 -1
- package/plugins/support/plugin.js +73 -3
- package/plugins/support/plugin.json +2 -2
- package/plugins/support/tests/ai.test.js +245 -0
- package/server/services/sidebarFrequent.js +1 -1
- package/server/services/wpImport/redirects.js +7 -2
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
* Right-click a row (or its ⋮, or Shift+F10) for the quick moves: resolve or
|
|
7
7
|
* reopen, urgent, archive, delete. The archive is Domma's own filing - the site
|
|
8
8
|
* still sees the request - and a customer writing again takes it back out.
|
|
9
|
+
*
|
|
10
|
+
* With AI Assist on the Manager: "Summarise" atop a request's thread, "Suggest
|
|
11
|
+
* a reply" into the reply box (never sent by itself), and "Summarise" on the
|
|
12
|
+
* Waiting on Domma tab, grouping those requests into themes.
|
|
9
13
|
*/
|
|
10
14
|
|
|
11
15
|
import {
|
|
@@ -14,6 +18,7 @@ import {
|
|
|
14
18
|
} from '../lib/kit.js';
|
|
15
19
|
import {DRAFT_KEYS, afterSend, draftQuestion, draftText, draftValues, ticketPrint} from '../lib/drafts.js';
|
|
16
20
|
import {looksLikeAddress, routeMailLinks} from '../lib/email.js';
|
|
21
|
+
import {AI_QUESTION, REPLACE_LATE_QUESTION, REPLACE_QUESTION, summaryCard, themesCard, usageText} from '../lib/ai.js';
|
|
17
22
|
|
|
18
23
|
const ROW = `
|
|
19
24
|
<div class="sp-row" data-id="{{key}}" tabindex="0" role="button" aria-haspopup="menu">
|
|
@@ -32,6 +37,14 @@ const FILTERS = [
|
|
|
32
37
|
{key: 'all', label: 'All'},
|
|
33
38
|
{key: 'archived', label: 'Archived'}
|
|
34
39
|
];
|
|
40
|
+
/** One theme of the waiting requests. Text bindings only: nothing from Claude is parsed as HTML. */
|
|
41
|
+
const THEME = `
|
|
42
|
+
<div class="sp-theme">
|
|
43
|
+
<div class="sp-theme-head"><strong data-bind-text="title"></strong><span class="sp-chip is-muted" data-bind-text="countText"></span></div>
|
|
44
|
+
<p data-bind-hidden="!detail" data-bind-text="detail"></p>
|
|
45
|
+
<p class="sp-theme-quotes" data-bind-hidden="!quotesText" data-bind-text="quotesText"></p>
|
|
46
|
+
</div>`;
|
|
47
|
+
|
|
35
48
|
const inFilter = (t, f) => (f === 'archived' ? Boolean(t.archived) : !t.archived && (f === 'all' || t.status === f));
|
|
36
49
|
|
|
37
50
|
export async function mount(root, ctx) {
|
|
@@ -41,6 +54,16 @@ export async function mount(root, ctx) {
|
|
|
41
54
|
const iconOf = (c) => categories.find(x => x.key === c)?.icon || 'message-square';
|
|
42
55
|
const labelOf = (c) => categories.find(x => x.key === c)?.short || c;
|
|
43
56
|
const inboxLabel = (s) => statuses.find(x => x.key === s)?.inboxLabel || s;
|
|
57
|
+
// AI Assist: each task only when the server says it can be asked for here.
|
|
58
|
+
const aiOn = mode?.ai && typeof mode.ai === 'object' ? mode.ai : {};
|
|
59
|
+
// Asked once per visit, before anything goes to Claude.
|
|
60
|
+
let toldAboutAi = false;
|
|
61
|
+
const aiAsk = async () => {
|
|
62
|
+
if (toldAboutAi) return true;
|
|
63
|
+
if (!await E.confirm(AI_QUESTION)) return false;
|
|
64
|
+
toldAboutAi = true;
|
|
65
|
+
return true;
|
|
66
|
+
};
|
|
44
67
|
|
|
45
68
|
const tickets = M.observable([]);
|
|
46
69
|
const panels = panelSet();
|
|
@@ -80,6 +103,14 @@ export async function mount(root, ctx) {
|
|
|
80
103
|
}));
|
|
81
104
|
}));
|
|
82
105
|
|
|
106
|
+
// The waiting requests' themes (AI Assist): on the Waiting on Domma tab only; the latest is kept.
|
|
107
|
+
const keptThemes = M.observable(null);
|
|
108
|
+
const themesBusy = M.observable(false);
|
|
109
|
+
const themes = M.computed(() => themesCard(keptThemes.value, {busy: themesBusy.value, waiting: counts.value.open || 0}));
|
|
110
|
+
const themeRows = M.computed(() => themes.value.themes);
|
|
111
|
+
const showThemes = M.computed(() => aiOn.themes === true && filter.value === 'open');
|
|
112
|
+
scope(() => { themes.dispose?.(); themeRows.dispose?.(); showThemes.dispose?.(); });
|
|
113
|
+
|
|
83
114
|
const card = mode.contact || {};
|
|
84
115
|
root.innerHTML = '';
|
|
85
116
|
const view = document.createElement('div');
|
|
@@ -93,6 +124,15 @@ export async function mount(root, ctx) {
|
|
|
93
124
|
<input class="form-input sp-search" type="search" placeholder="Search requests" data-model="query.value" aria-label="Search requests">
|
|
94
125
|
<span data-help-title="Support inbox" data-help="Every site's support requests. Click one to read and reply - replying emails the customer a link back to the conversation in their own admin. Right-click a request (or use its ⋮ button, or Shift+F10) to resolve, reopen, mark urgent, archive or delete it. Archiving puts a request away without deleting it; the customer still sees it, and if they write again it comes back here. Urgent requests sort first and turn the sidebar badge red. Internal notes never reach the site."></span>
|
|
95
126
|
</div>
|
|
127
|
+
${aiOn.themes ? `<div class="sp-themes" data-bind-hidden="!showThemes.value">
|
|
128
|
+
<div class="sp-themes-bar">
|
|
129
|
+
<button type="button" class="btn btn-sm btn-outline" data-summarise data-bind-disabled="!themes.value.canSummarise"><span data-icon="sparkles" data-icon-size="13"></span> <span data-bind-text="themes.value.label"></span></button>
|
|
130
|
+
<small class="sp-hint" data-bind-text="themes.value.note"></small>
|
|
131
|
+
<span data-help-title="Summarise" data-help="Groups every request waiting on Domma (archived ones left out, whatever the search) into themes with AI, each with how many requests it covers and a few of the customers' words. Only the subjects and what the customers wrote go to Claude, through AI Assist: no site names, people's names, email addresses, phone numbers or files. The latest summary stays here until you summarise again. Each one counts towards this server's monthly AI Assist allowance."></span>
|
|
132
|
+
</div>
|
|
133
|
+
<p class="sp-themes-summary" data-bind-hidden="!themes.value.summary" data-bind-text="themes.value.summary"></p>
|
|
134
|
+
<div class="sp-theme-list" data-each="themeRows.value key=key"></div>
|
|
135
|
+
</div>` : ''}
|
|
96
136
|
<p class="sp-note sp-small">Customers see: ${esc([card.email, card.phone, card.hours].filter(Boolean).join(' · ') || 'no contact details set')}${mode.notifyEmail ? ` · New requests are emailed to ${esc(mode.notifyEmail)}` : ' · New requests are not emailed (no notifyEmail set)'}.</p>
|
|
97
137
|
<div class="sp-loading dm-loading-slot" data-bind-hidden="!loading.value">Loading...</div>
|
|
98
138
|
<p class="sp-note is-bad" data-bind-hidden="!error.value" data-bind-text="error.value"></p>
|
|
@@ -102,6 +142,8 @@ export async function mount(root, ctx) {
|
|
|
102
142
|
scope(kit.helpPopovers(view, {position: 'bottom'}));
|
|
103
143
|
const listEl = view.querySelector('.sp-list');
|
|
104
144
|
listEl.innerHTML = ROW;
|
|
145
|
+
const themeList = view.querySelector('.sp-theme-list');
|
|
146
|
+
if (themeList) themeList.innerHTML = THEME;
|
|
105
147
|
scope(M.effect(() => { rows.value; Promise.resolve().then(() => { M.flush?.(); I.scan(listEl); }); }));
|
|
106
148
|
|
|
107
149
|
async function load() {
|
|
@@ -109,6 +151,7 @@ export async function mount(root, ctx) {
|
|
|
109
151
|
const res = await kit.whileLoading(view.querySelector('.sp-loading'), api.tickets(), kit.SHAPES.iconRows);
|
|
110
152
|
if (!here()) return;
|
|
111
153
|
tickets.value = listOf(res, 'tickets');
|
|
154
|
+
keptThemes.value = res?.themes && typeof res.themes === 'object' ? res.themes : null;
|
|
112
155
|
error.value = '';
|
|
113
156
|
} catch (err) {
|
|
114
157
|
if (here()) error.value = `Could not load requests: ${err.message || err}`;
|
|
@@ -231,6 +274,13 @@ export async function mount(root, ctx) {
|
|
|
231
274
|
const after = M.observable('answered');
|
|
232
275
|
const notes = M.observable(start.notes);
|
|
233
276
|
const busy = M.observable(false);
|
|
277
|
+
// AI Assist: the kept summary, and which task is on its way ('' none, 'summary', 'reply').
|
|
278
|
+
const aiSum = M.observable(t.aiSummary && typeof t.aiSummary === 'object' ? t.aiSummary : null);
|
|
279
|
+
const aiBusy = M.observable('');
|
|
280
|
+
const sum = M.computed(() => summaryCard(aiSum.value, {busy: aiBusy.value, messages: (cur.value.messages || []).length,
|
|
281
|
+
chars: Number(cur.value.aiChars ?? t.aiChars ?? 0)}));
|
|
282
|
+
const sumPoints = M.computed(() => sum.value.points);
|
|
283
|
+
const showing = () => panels.get('detail')?.key === tid;
|
|
234
284
|
let panel = null;
|
|
235
285
|
let guard = null;
|
|
236
286
|
let savedNotes = saved.notes;
|
|
@@ -249,10 +299,10 @@ export async function mount(root, ctx) {
|
|
|
249
299
|
panel = await openPanel({
|
|
250
300
|
title: t.subject,
|
|
251
301
|
size: 'lg',
|
|
252
|
-
model: {thread, status, statusLabel, tone, urgent, archived, draft, hasDraft, after, notes, busy},
|
|
302
|
+
model: {thread, status, statusLabel, tone, urgent, archived, draft, hasDraft, after, notes, busy, aiBusy, sum, sumPoints},
|
|
253
303
|
cleanup: () => {
|
|
254
304
|
stopScroll(); stopMail(); stopFiles(); shown.dispose(); menu?.destroy?.();
|
|
255
|
-
[cur, thread, status, statusLabel, tone, urgent, archived, hasDraft].forEach(c => c.dispose?.());
|
|
305
|
+
[cur, thread, status, statusLabel, tone, urgent, archived, hasDraft, sum, sumPoints].forEach(c => c.dispose?.());
|
|
256
306
|
panels.release('detail');
|
|
257
307
|
},
|
|
258
308
|
html: `<div class="sp-detail">
|
|
@@ -266,6 +316,15 @@ export async function mount(root, ctx) {
|
|
|
266
316
|
${t.where ? `<div><dt>Where</dt><dd>${esc(t.where)}</dd></div>` : ''}
|
|
267
317
|
${t.cmsVersion ? `<div><dt>CMS</dt><dd>${esc(t.cmsVersion)}</dd></div>` : ''}
|
|
268
318
|
</dl>
|
|
319
|
+
${aiOn.summary ? `<div class="sp-ai">
|
|
320
|
+
<div class="sp-ai-bar">
|
|
321
|
+
<button type="button" class="btn btn-sm btn-outline" data-on-click="summarise" data-bind-disabled="!sum.value.canSummarise"><span data-icon="sparkles" data-icon-size="13"></span> <span data-bind-text="sum.value.label"></span></button>
|
|
322
|
+
<small class="sp-hint" data-bind-text="sum.value.note"></small>
|
|
323
|
+
<span data-help-title="Summarise" data-help="A few lines on what the customer needs and where things stand, and the points still open, by AI. Only the words of the conversation go to Claude, through AI Assist: no site name, people's names, email addresses, phone numbers or files. The summary is kept with the request until you summarise again, and says when the conversation has moved on since. Each one counts towards this server's monthly AI Assist allowance."></span>
|
|
324
|
+
</div>
|
|
325
|
+
<p class="sp-ai-summary" data-bind-hidden="!sum.value.summary" data-bind-text="sum.value.summary"></p>
|
|
326
|
+
<ul class="sp-ai-points" data-each="sumPoints.value key=key"><li data-bind-text="text"></li></ul>
|
|
327
|
+
</div>` : ''}
|
|
269
328
|
<div class="sp-thread-host">${THREAD}</div>
|
|
270
329
|
<div class="sp-reply">
|
|
271
330
|
<label class="form-label" for="sp-answer">Reply <span data-help="The customer sees it in their admin and gets it by email. Right-click a message (or its ⋮, or Shift+F10) to copy or quote it. A reply you leave unsent is kept, and offered back when you open this request again."></span></label>
|
|
@@ -277,6 +336,7 @@ export async function mount(root, ctx) {
|
|
|
277
336
|
<span class="sp-spacer"></span>
|
|
278
337
|
<button type="button" class="btn btn-sm btn-ghost" data-on-click="resolve" data-bind-hidden="status.value === 'closed'" data-bind-disabled="busy.value">Resolve without reply</button>
|
|
279
338
|
<button type="button" class="btn btn-sm btn-ghost" data-on-click="reopen" data-bind-hidden="status.value !== 'closed'" data-bind-disabled="busy.value">Reopen</button>
|
|
339
|
+
${aiOn.reply ? `<button type="button" class="btn btn-sm btn-outline" data-on-click="suggest" data-bind-disabled="sum.value.busy" title="Fills the reply box for you to edit. Nothing is sent until you send it."><span data-icon="sparkles" data-icon-size="13"></span> <span data-bind-text="sum.value.suggestLabel"></span></button>` : ''}
|
|
280
340
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="send" data-bind-disabled="busy.value || !hasDraft.value"><span data-icon="send" data-icon-size="13"></span> Send reply</button>
|
|
281
341
|
</div>
|
|
282
342
|
</div>
|
|
@@ -321,7 +381,42 @@ export async function mount(root, ctx) {
|
|
|
321
381
|
ours(next);
|
|
322
382
|
E.toast('Notes saved.', {type: 'success'});
|
|
323
383
|
}),
|
|
324
|
-
remove: () => run(async () => { await actions.remove(cur.peek()); })
|
|
384
|
+
remove: () => run(async () => { await actions.remove(cur.peek()); }),
|
|
385
|
+
async summarise() {
|
|
386
|
+
if (!sum.peek().canSummarise || !await aiAsk() || !showing()) return;
|
|
387
|
+
aiBusy.value = 'summary';
|
|
388
|
+
try {
|
|
389
|
+
const res = await api.summary(tid);
|
|
390
|
+
aiSum.value = res;
|
|
391
|
+
if (here()) E.toast(usageText(res, 'Summarised.'), {type: 'success'});
|
|
392
|
+
} catch (err) {
|
|
393
|
+
if (here()) E.toast(`No summary: ${err.message || err}`, {type: 'error', duration: 8000});
|
|
394
|
+
} finally {
|
|
395
|
+
aiBusy.value = '';
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
/** A reply to edit. It only fills the box: the person reads it, changes it and sends it, or not. */
|
|
399
|
+
async suggest() {
|
|
400
|
+
if (aiBusy.peek()) return;
|
|
401
|
+
if (draft.peek().trim() && !await E.confirm(REPLACE_QUESTION)) return;
|
|
402
|
+
if (!await aiAsk() || !showing()) return;
|
|
403
|
+
const before = draft.peek();
|
|
404
|
+
aiBusy.value = 'reply';
|
|
405
|
+
try {
|
|
406
|
+
const res = await api.suggest(tid);
|
|
407
|
+
if (!here() || !showing()) return;
|
|
408
|
+
const now = draft.peek();
|
|
409
|
+
if (now !== before && now.trim() && !await E.confirm(REPLACE_LATE_QUESTION)) return;
|
|
410
|
+
if (!showing()) return;
|
|
411
|
+
draft.value = res.text;
|
|
412
|
+
panel.panel.querySelector('#sp-answer')?.focus();
|
|
413
|
+
E.toast(usageText(res, 'Suggested - read it and edit it before you send.'), {type: 'success'});
|
|
414
|
+
} catch (err) {
|
|
415
|
+
if (here()) E.toast(`No suggestion: ${err.message || err}`, {type: 'error', duration: 8000});
|
|
416
|
+
} finally {
|
|
417
|
+
aiBusy.value = '';
|
|
418
|
+
}
|
|
419
|
+
}
|
|
325
420
|
}
|
|
326
421
|
});
|
|
327
422
|
guard = guardPanel(panel, {
|
|
@@ -360,9 +455,31 @@ export async function mount(root, ctx) {
|
|
|
360
455
|
return true;
|
|
361
456
|
}
|
|
362
457
|
|
|
363
|
-
const bindings = M.applyBindings({tickets, loading, error, filter, query, rows, counts, emptyText}, view, {methods: {}});
|
|
458
|
+
const bindings = M.applyBindings({tickets, loading, error, filter, query, rows, counts, emptyText, themes, themeRows, showThemes}, view, {methods: {}});
|
|
364
459
|
scope(() => bindings.dispose());
|
|
365
460
|
|
|
461
|
+
// The waiting requests' themes (AI Assist).
|
|
462
|
+
async function summariseWaiting() {
|
|
463
|
+
if (themesBusy.peek() || !themes.peek().canSummarise || !await aiAsk() || !here()) return;
|
|
464
|
+
themesBusy.value = true;
|
|
465
|
+
try {
|
|
466
|
+
const res = await api.themes();
|
|
467
|
+
if (!here()) return;
|
|
468
|
+
keptThemes.value = res;
|
|
469
|
+
E.toast(usageText(res, 'Summarised.'), {type: 'success'});
|
|
470
|
+
} catch (err) {
|
|
471
|
+
if (here()) E.toast(`No summary: ${err.message || err}`, {type: 'error', duration: 8000});
|
|
472
|
+
} finally {
|
|
473
|
+
themesBusy.value = false;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
const summariseBtn = view.querySelector('[data-summarise]');
|
|
477
|
+
if (summariseBtn) {
|
|
478
|
+
const onSummarise = () => { summariseWaiting(); };
|
|
479
|
+
summariseBtn.addEventListener('click', onSummarise);
|
|
480
|
+
scope(() => summariseBtn.removeEventListener('click', onSummarise));
|
|
481
|
+
}
|
|
482
|
+
|
|
366
483
|
const seg = view.querySelector('.sp-seg');
|
|
367
484
|
const onFilter = (e) => { const b = e.target.closest('[data-filter]'); if (b) { filter.value = b.dataset.filter; store.set('support.filter', filter.value); } };
|
|
368
485
|
seg.addEventListener('click', onFilter);
|
|
@@ -76,6 +76,10 @@ On the Domma server itself (the Manager), the same screen is the **Inbox** of ev
|
|
|
76
76
|
- Filter by **Open**, **Answered**, **Resolved**, **Archived** or **All**, urgent first; search subject, text, person and site.
|
|
77
77
|
- Open a request to read the conversation (with any files the customer attached - one still on its way says so), **Reply** (the site sees it and is notified, and the person is emailed), **Resolve**, change its priority, and keep **Internal notes** (never sent to the site).
|
|
78
78
|
- Right-click a row to archive, resolve or **Delete** it. Archiving is Domma's own filing: the site does not see it, and a request comes out of the archive when the customer writes again.
|
|
79
|
+
- With **AI Assist** on the Domma server, an open request has **Summarise** above the conversation: a few lines on what the customer needs and where it stands, and the points still open. On a very short conversation the button is greyed out until there is more to sum up. The summary stays with the request and says when the conversation has moved on since.
|
|
80
|
+
- **Suggest a reply** (beside **Send reply**) fills the reply box with a reply written by AI, for you to read and edit. Nothing is sent until you click **Send reply** yourself. If the box already has text, you are asked before it is replaced.
|
|
81
|
+
- On the **Waiting on Domma** tab, **Summarise** groups every request waiting on Domma (not archived ones) into themes, with how many requests each covers and a few of the customers' words. The latest summary stays on the screen until you summarise again or delete one of the requests it read.
|
|
82
|
+
- For all three, only the words of the conversation go to Claude: no site names or web addresses, people's names, email addresses, phone numbers or files, and greetings, sign-offs, quoted earlier emails and signatures are left out. You are asked once per visit before anything is sent. Each use counts towards the server's monthly AI Assist allowance.
|
|
79
83
|
- A new request or a customer's reply is emailed to the Domma support address, with the customer as Reply-To and `[URGENT]` in the subject when it is urgent.
|
|
80
84
|
- The **Support settings** cog sets the contact card every site shows (email, phone, opening hours, how fast you answer), the address new requests are emailed to, and how many messages one site may send in a window. Changes apply at once; each site gets the new card with its next sync.
|
|
81
85
|
|
|
@@ -86,3 +90,4 @@ On the Domma server itself (the Manager), the same screen is the **Inbox** of ev
|
|
|
86
90
|
- Subjects are limited to 140 characters and messages to 8,000.
|
|
87
91
|
- The Domma server accepts up to 20 requests and replies from one site in 10 minutes. Any more show as **Waiting to send** and go later.
|
|
88
92
|
- You cannot edit or withdraw a message once sent. Write a follow-up instead.
|
|
93
|
+
- The AI Assist features are only on the Domma server. A summary needs a conversation of a few sentences at least.
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Assist on the Manager - the receiver side only. The Domma team's inbox asks Claude for summaries and
|
|
3
|
+
* suggestions through the Manager's own AI Assist service, reached in this process:
|
|
4
|
+
* globalThis[Symbol.for('domma.ai-text')] = {version: 1, tasks: [...], run(body) -> Promise<{status, body}>}
|
|
5
|
+
* (site-manager/services/aiTextRoutes.js). There is no fleet route here: the receiver IS the Manager, and a
|
|
6
|
+
* customer site never offers these features.
|
|
7
|
+
*
|
|
8
|
+
* What is sent is text only, cleaned by `scrubText()`: no names, email addresses, phone numbers, ids or files.
|
|
9
|
+
* A suggestion is never sent or saved by itself: the person sees it and keeps, edits or drops it.
|
|
10
|
+
*
|
|
11
|
+
* Feedback and Support each carry their own copy of this file (either can be installed alone).
|
|
12
|
+
*
|
|
13
|
+
* @module lib/ai-text
|
|
14
|
+
*/
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
|
|
18
|
+
let aiAssistLookup = null;
|
|
19
|
+
try {
|
|
20
|
+
({isAiAssist: aiAssistLookup} = await import('../../../server/services/aiAssist.js'));
|
|
21
|
+
} catch { /* an engine before AI Assist: no AI features */ }
|
|
22
|
+
|
|
23
|
+
/** Whether this server has AI Assist (the Tool is on and licensed). Tests set their own. */
|
|
24
|
+
export function aiAssistOn() {
|
|
25
|
+
try { return typeof aiAssistLookup === 'function' && aiAssistLookup() === true; } catch { return false; }
|
|
26
|
+
}
|
|
27
|
+
export function useAiAssistLookup(fn) { aiAssistLookup = fn; }
|
|
28
|
+
|
|
29
|
+
const LOCAL = Symbol.for('domma.ai-text');
|
|
30
|
+
const registry = () => {
|
|
31
|
+
const r = globalThis[LOCAL];
|
|
32
|
+
return r && typeof r === 'object' && typeof r.run === 'function' ? r : null;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Whether a task can be asked for here: AI Assist on, and the Manager's service in this process. */
|
|
36
|
+
export function aiTextAvailable(task) {
|
|
37
|
+
if (!aiAssistOn()) return false;
|
|
38
|
+
const r = registry();
|
|
39
|
+
if (!r) return false;
|
|
40
|
+
return !task || !Array.isArray(r.tasks) || r.tasks.includes(task);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Ask the Manager's AI Assist service. Never throws: {status, body} as it answered, or a 403/503 of its own.
|
|
45
|
+
* @param {object} body {task, ...} as aiTextRoutes.js takes it
|
|
46
|
+
*/
|
|
47
|
+
export async function requestAiText(body) {
|
|
48
|
+
if (!aiAssistOn()) return {status: 403, body: {error: 'This comes with AI Assist, in the Pro plan.'}};
|
|
49
|
+
const r = registry();
|
|
50
|
+
if (!r) return {status: 503, body: {error: 'AI Assist is not available on this server.'}};
|
|
51
|
+
try {
|
|
52
|
+
const out = await r.run(body);
|
|
53
|
+
if (!out || !Number.isInteger(out.status)) return {status: 503, body: {error: 'AI Assist did not answer. Try again shortly.'}};
|
|
54
|
+
return {status: out.status, body: out.body && typeof out.body === 'object' ? out.body : {}};
|
|
55
|
+
} catch {
|
|
56
|
+
return {status: 503, body: {error: 'AI Assist is not available just now. Try again shortly.'}};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The answer an admin route gives when the service did not produce a result: its status and error text
|
|
62
|
+
* passed through, a decline as 422. Null when there is a result to use.
|
|
63
|
+
*/
|
|
64
|
+
export function aiFailure({status, body}, declined = 'Claude would not do that one.') {
|
|
65
|
+
if (status === 200 && !body?.declined) return null;
|
|
66
|
+
return {status: status === 200 ? 422 : status,
|
|
67
|
+
body: {error: body?.declined ? declined : body?.error || 'AI Assist did not answer.', used: body?.used, limit: body?.limit}};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
71
|
+
/** Whole words (not inside another word), longest first, any case. */
|
|
72
|
+
const wordsOf = (list) => {
|
|
73
|
+
const alts = [...new Set(list.map(w => w.toLowerCase()))].filter(w => w.length >= 2).sort((a, b) => b.length - a.length).map(escapeRe);
|
|
74
|
+
return alts.length ? new RegExp(`(?<![\\p{L}\\p{N}_])(?:${alts.join('|')})(?![\\p{L}\\p{N}_])`, 'giu') : null;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Names that stand in for a missing one, and words a mailbox is often called: never treated as anyone's name
|
|
79
|
+
* (taking "site", "admin" or "support" out of every message would lose its sense, and protect no one).
|
|
80
|
+
*/
|
|
81
|
+
const NOT_NAMES = new Set(['a', 'an', 'the', 'site', 'admin', 'administrator', 'an admin', 'a site admin', 'domma', 'domma support', 'support',
|
|
82
|
+
'team', 'customer', 'manager', 'user', 'info', 'hello', 'contact', 'sales', 'office', 'mail', 'email', 'enquiries', 'help', 'noreply',
|
|
83
|
+
'no-reply', 'webmaster', 'accounts', 'billing']);
|
|
84
|
+
|
|
85
|
+
/** The parts of the names and of the email addresses' local parts (john.smith@ -> john, smith). */
|
|
86
|
+
export function nameParts({names = [], emails = []} = {}) {
|
|
87
|
+
const out = new Set();
|
|
88
|
+
const add = (w) => { const v = String(w || '').trim().replace(/^[^\p{L}]+|[^\p{L}]+$/gu, ''); if (v.length >= 2 && !NOT_NAMES.has(v.toLowerCase())) out.add(v); };
|
|
89
|
+
for (const n of names || []) {
|
|
90
|
+
const full = String(n || '').trim();
|
|
91
|
+
if (!full || NOT_NAMES.has(full.toLowerCase())) continue;
|
|
92
|
+
add(full);
|
|
93
|
+
for (const w of full.split(/\s+/)) add(w);
|
|
94
|
+
}
|
|
95
|
+
for (const e of emails || []) {
|
|
96
|
+
const local = String(e || '').split('@')[0] || '';
|
|
97
|
+
if (!String(e || '').includes('@')) continue;
|
|
98
|
+
for (const w of local.split(/[._+\-\d]+/)) if (/^\p{L}+$/u.test(w)) add(w);
|
|
99
|
+
}
|
|
100
|
+
return [...out];
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const GREETING_LINE = /^\s*(?:hi|hello|hey|dear|good (?:morning|afternoon|evening)|morning|afternoon)\b(?:[ \t]+[\p{L}'-]+){0,3}[ \t]*[,!.]?[ \t]*$/iu;
|
|
104
|
+
const GREETING_START = /^\s*(?:hi|hello|hey|dear|good (?:morning|afternoon|evening))\b[^,\n]{0,40},[ \t]*/iu;
|
|
105
|
+
const WORDS = "[\\p{L}'.-]+(?:[ \\t]+[\\p{L}'.-]+){0,2}";
|
|
106
|
+
/** "Thanks," / "Kind regards" / "Cheers, Jo" / "Thanks Darryl": a line of its own. Bare "Best" needs its comma or the line to end. */
|
|
107
|
+
const SIGN_OFF = new RegExp(`^\\s*(?:(?:many thanks|thanks(?: again| so much| very much)?|thank you(?: so much| very much| again)?|kind regards|warm regards|best regards|best wishes|all the best|regards)[ \\t]*(?:[,.!][ \\t]*(?:${WORDS})?|[ \\t]+${WORDS})?|(?:best|cheers)[ \\t]*(?:[,.!][ \\t]*(?:${WORDS})?)?)[ \\t]*[,.!]?[ \\t]*$`, 'iu');
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Text fit to send. Taken out: a greeting at the start ("Hi Ann,"), a sign-off and the short lines under it
|
|
111
|
+
* ("Thanks,\nAnn Jones\nAcme Ltd"), earlier messages quoted in an email (lines starting ">", "On ... wrote:" and
|
|
112
|
+
* what follows), a signature after "-- ", email addresses and phone numbers; then the people and sites known to be
|
|
113
|
+
* in it: `names` and the local parts of `emails` (whole names or any part, any case, as whole words) become [name],
|
|
114
|
+
* `sites` (names and domains, any case; a link on a domain too) become [site]. Spaces tidied. `letter: false` (a title
|
|
115
|
+
* or subject) keeps the first line and any "Thanks" as they are.
|
|
116
|
+
*/
|
|
117
|
+
export function scrubText(raw, max = 2000, {names = [], emails = [], sites = [], letter = true} = {}) {
|
|
118
|
+
const people = wordsOf(nameParts({names, emails}));
|
|
119
|
+
const siteList = (sites || []).map(n => String(n || '').trim().toLowerCase()).filter(Boolean);
|
|
120
|
+
const hosts = siteList.filter(s => /^[a-z0-9-]+(?:\.[a-z0-9-]+)+$/.test(s));
|
|
121
|
+
const links = hosts.length
|
|
122
|
+
? new RegExp(`(?:https?://)?(?:[a-z0-9-]+\\.)*(?:${hosts.map(escapeRe).join('|')})(?::\\d+)?(?:[/?#](?:[^\\s<>"']*[^\\s<>"'.,;:!?)\\]])?)?(?![\\w.-]*[a-z0-9])`, 'gi') : null;
|
|
123
|
+
const places = wordsOf(siteList.filter(s => !hosts.includes(s)));
|
|
124
|
+
const lines = String(raw ?? '').replace(/\r\n?/g, '\n').replace(/ /g, ' ').split('\n');
|
|
125
|
+
const kept = [];
|
|
126
|
+
let started = false;
|
|
127
|
+
for (let i = 0; i < lines.length; i++) {
|
|
128
|
+
let line = lines[i];
|
|
129
|
+
if (/^--\s?$/.test(line)) break;
|
|
130
|
+
if (/^\s*On\b.{0,200}\bwrote:\s*$/i.test(line)) break;
|
|
131
|
+
if (/^\s*>/.test(line)) continue;
|
|
132
|
+
if (letter && !started && line.trim()) {
|
|
133
|
+
started = true;
|
|
134
|
+
if (GREETING_LINE.test(line)) continue;
|
|
135
|
+
line = line.replace(GREETING_START, '');
|
|
136
|
+
}
|
|
137
|
+
if (letter && SIGN_OFF.test(line)) {
|
|
138
|
+
// The name, role and company lines under it: short ones only, at most three.
|
|
139
|
+
let j = i + 1;
|
|
140
|
+
while (j < lines.length && j <= i + 3 && lines[j].trim() && lines[j].trim().length <= 40) j++;
|
|
141
|
+
i = j - 1;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
kept.push(line);
|
|
145
|
+
}
|
|
146
|
+
let out = kept.join('\n')
|
|
147
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]+/g, ' ')
|
|
148
|
+
// Bounded parts, so a long run without spaces costs little.
|
|
149
|
+
.replace(/(?:mailto:)?[^\s@<>()"',;:]{1,64}@[^\s@<>()"',;:]{1,253}\.[A-Za-z]{2,24}/g, '[email]')
|
|
150
|
+
// A run of digits, spaces, brackets and hyphens holding 9 to 15 digits is a phone number. Dates and
|
|
151
|
+
// versions (2026-11-16, 1.58.0) have fewer digits, or dots.
|
|
152
|
+
.replace(/(?<![\w.])\+?\(?\d[\d \t()-]{6,24}\d(?!\w|\.\d)/g, (m) => {
|
|
153
|
+
const digits = m.replace(/\D/g, '').length;
|
|
154
|
+
return digits >= 9 && digits <= 15 ? '[phone]' : m;
|
|
155
|
+
});
|
|
156
|
+
if (links) out = out.replace(links, '[site]');
|
|
157
|
+
if (places) out = out.replace(places, '[site]');
|
|
158
|
+
if (people) out = out.replace(people, '[name]');
|
|
159
|
+
return out
|
|
160
|
+
.replace(/[ \t]+/g, ' ')
|
|
161
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
162
|
+
.trim()
|
|
163
|
+
.slice(0, max);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const text = (v, max) => String(v ?? '').slice(0, max);
|
|
167
|
+
const whole = (v) => Math.max(0, Math.floor(Number(v) || 0));
|
|
168
|
+
|
|
169
|
+
/** A kept themes result, cleaned (it is shown again later). */
|
|
170
|
+
export function cleanThemes(raw) {
|
|
171
|
+
const r = raw && typeof raw === 'object' ? raw : {};
|
|
172
|
+
return {
|
|
173
|
+
at: text(r.at, 40),
|
|
174
|
+
filter: text(r.filter, 300),
|
|
175
|
+
answers: whole(r.answers),
|
|
176
|
+
summary: text(r.summary, 1500),
|
|
177
|
+
themes: (Array.isArray(r.themes) ? r.themes : []).slice(0, 8).map(t => ({
|
|
178
|
+
title: text(t?.title, 120), detail: text(t?.detail, 600), count: whole(t?.count),
|
|
179
|
+
quotes: (Array.isArray(t?.quotes) ? t.quotes : []).slice(0, 3).map(q => text(q, 300))
|
|
180
|
+
}))
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** A kept summary of one conversation, cleaned. */
|
|
185
|
+
export function cleanSummary(raw) {
|
|
186
|
+
const r = raw && typeof raw === 'object' ? raw : {};
|
|
187
|
+
return {
|
|
188
|
+
at: text(r.at, 40),
|
|
189
|
+
messages: whole(r.messages),
|
|
190
|
+
summary: text(r.summary, 1500),
|
|
191
|
+
points: (Array.isArray(r.points) ? r.points : []).slice(0, 5).map(p => text(p, 300)).filter(Boolean)
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Results kept on the Manager, one file: {<key>: value}. Read on each use; written whole, through a temporary
|
|
197
|
+
* file, private (0600). Nothing here is sent anywhere.
|
|
198
|
+
*/
|
|
199
|
+
export function createKept(file) {
|
|
200
|
+
const read = () => {
|
|
201
|
+
try {
|
|
202
|
+
const v = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
203
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
204
|
+
} catch { return {}; }
|
|
205
|
+
};
|
|
206
|
+
const write = (all) => {
|
|
207
|
+
fs.mkdirSync(path.dirname(file), {recursive: true, mode: 0o700});
|
|
208
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
209
|
+
fs.writeFileSync(tmp, JSON.stringify(all, null, 2), {mode: 0o600});
|
|
210
|
+
fs.renameSync(tmp, file);
|
|
211
|
+
};
|
|
212
|
+
return {
|
|
213
|
+
get: (key) => read()[key] ?? null,
|
|
214
|
+
set(key, value) { const all = read(); all[key] = value; write(all); return value; },
|
|
215
|
+
remove(key) { const all = read(); if (key in all) { delete all[key]; write(all); } }
|
|
216
|
+
};
|
|
217
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Support inbox - AI Assist on the Manager (the receiver only). PURE: what of a request is sent for each task.
|
|
3
|
+
*
|
|
4
|
+
* summary {kind: 'ticket', title: subject, text: "Customer: ..." / "Domma: ..." lines}
|
|
5
|
+
* reply {title: subject, thread: [{from: customer|us, text}]}
|
|
6
|
+
* themes {kind: 'tickets', survey, question, answers: ["Subject. What the customer wrote"]}
|
|
7
|
+
*
|
|
8
|
+
* Only the words of the conversation go, through scrubText(): no site, no names (the people on the request and its
|
|
9
|
+
* site's name are taken out of the text as well), no email addresses, phone numbers, quoted earlier mail, signatures
|
|
10
|
+
* or files. `sites` is the request's site: its name and domain, as the caller knows them.
|
|
11
|
+
*
|
|
12
|
+
* @module support/lib/assist
|
|
13
|
+
*/
|
|
14
|
+
import {scrubText} from './ai-text.js';
|
|
15
|
+
|
|
16
|
+
/** The Manager's caps (site-manager/services/aiTextRoutes.js LIMITS). */
|
|
17
|
+
export const AI_LIMITS = {post: 8000, thread: 40, page: 60_000, title: 300, answer: 2000, answers: 1000};
|
|
18
|
+
export const THEMES_SURVEY = 'Support requests from Domma sites';
|
|
19
|
+
export const THEMES_QUESTION = 'Requests waiting on Domma';
|
|
20
|
+
/** The Manager summarises nothing shorter (aiTextRoutes.js: "There is too little to summarise"). */
|
|
21
|
+
export const SUMMARY_MIN = 200;
|
|
22
|
+
|
|
23
|
+
/** Everyone named on a request: the customer, and each of the team who replied. */
|
|
24
|
+
export const peopleOf = (data = {}) => [data.userName, ...(data.messages || []).map(m => m.name)].filter(Boolean);
|
|
25
|
+
|
|
26
|
+
/** Who to take out of the words: the people's names, the customer's email (john.smith@ -> john, smith), the site. */
|
|
27
|
+
const scrubFor = (data, sites) => ({names: peopleOf(data), emails: [data.userEmail], sites});
|
|
28
|
+
|
|
29
|
+
const said = (data, sites = []) => {
|
|
30
|
+
const names = scrubFor(data, sites);
|
|
31
|
+
return (Array.isArray(data.messages) ? data.messages : [])
|
|
32
|
+
.map(m => ({from: m.from === 'domma' ? 'domma' : 'customer', text: scrubText(m.body, AI_LIMITS.post, names)}))
|
|
33
|
+
.filter(m => m.text);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** The subject, cleaned the same way. */
|
|
37
|
+
export const subjectOf = (data = {}, {sites = []} = {}) => scrubText(data.subject, AI_LIMITS.title, {...scrubFor(data, sites), letter: false});
|
|
38
|
+
|
|
39
|
+
/** The conversation as "Customer:" and "Domma:" lines, the latest kept when it is long. */
|
|
40
|
+
export function conversationText(data = {}, {sites = []} = {}) {
|
|
41
|
+
const out = [];
|
|
42
|
+
let chars = 0;
|
|
43
|
+
for (const m of said(data, sites).reverse()) {
|
|
44
|
+
const line = `${m.from === 'domma' ? 'Domma' : 'Customer'}: ${m.text}`;
|
|
45
|
+
chars += line.length + 2;
|
|
46
|
+
if (chars > AI_LIMITS.page) break;
|
|
47
|
+
out.unshift(line);
|
|
48
|
+
}
|
|
49
|
+
return out.join('\n\n');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The conversation for a suggested reply: the latest messages, as from customer|us. */
|
|
53
|
+
export function replyThread(data = {}, {sites = []} = {}) {
|
|
54
|
+
return said(data, sites).slice(-AI_LIMITS.thread).map(m => ({from: m.from === 'domma' ? 'us' : 'customer', text: m.text}));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The requests in the "Waiting on Domma" tab: open, not archived. */
|
|
58
|
+
export const waitingOnDomma = (entries = []) => entries.filter(e => e.data?.status === 'open' && !e.data?.archived);
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* What is sent of each waiting request: its subject, then what the customer wrote.
|
|
62
|
+
* @param {Function} sitesOf (slug) => [name, domain] of that request's site
|
|
63
|
+
*/
|
|
64
|
+
export function themesAnswers(entries = [], sitesOf = () => []) {
|
|
65
|
+
return entries
|
|
66
|
+
.map(e => {
|
|
67
|
+
const sites = sitesOf(e.data?.site || '');
|
|
68
|
+
const customer = said(e.data || {}, sites).filter(m => m.from === 'customer').map(m => m.text).join(' ');
|
|
69
|
+
const subject = subjectOf(e.data || {}, {sites});
|
|
70
|
+
return [subject && !/[.!?]$/.test(subject) ? `${subject}.` : subject, customer].filter(Boolean).join(' ').slice(0, AI_LIMITS.answer);
|
|
71
|
+
})
|
|
72
|
+
.filter(Boolean)
|
|
73
|
+
.slice(0, AI_LIMITS.answers);
|
|
74
|
+
}
|
|
@@ -51,7 +51,7 @@ export async function slugFromToken(authorization) {
|
|
|
51
51
|
} catch { return null; }
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
/** slug -> {name, host}, from Site Manager's registry. Empty when there is none. */
|
|
54
|
+
/** slug -> {name, host, hosts}, from Site Manager's registry. Empty when there is none. */
|
|
55
55
|
export function siteDirectory() {
|
|
56
56
|
try {
|
|
57
57
|
const j = JSON.parse(fs.readFileSync(path.join(SITE_MANAGER, 'data', 'sites.json'), 'utf8'));
|
|
@@ -59,6 +59,7 @@ export function siteDirectory() {
|
|
|
59
59
|
return Object.fromEntries(list.filter(s => s?.slug).map(s => [s.slug, {
|
|
60
60
|
name: s.displayName || s.name || s.slug,
|
|
61
61
|
host: s.primaryDomain || s.fallbackDomain || (Array.isArray(s.domains) ? s.domains[0] : '') || '',
|
|
62
|
+
hosts: [...new Set([s.primaryDomain, s.fallbackDomain, ...(Array.isArray(s.domains) ? s.domains : [])].filter(d => typeof d === 'string' && d))],
|
|
62
63
|
cmsVersion: s.cmsVersion || ''
|
|
63
64
|
}]));
|
|
64
65
|
} catch { return {}; }
|