domma-cms 1.57.1 → 1.59.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 +9 -0
- package/admin/js/app.js +2 -2
- package/admin/js/lib/admin-assistant.js +2 -2
- package/admin/js/lib/chat-toast.js +2 -0
- package/admin/js/lib/notifications-arrange.js +1 -1
- package/admin/js/templates/docs/usage-chat.html +11 -4
- package/admin/js/views/launchers.js +26 -25
- package/admin/js/views/notifications.js +10 -4
- package/docs/DommaFeatures.md +2 -1
- package/docs/admin-assistant.md +1 -1
- package/docs/plugin-development.md +1 -0
- package/package.json +1 -1
- package/server/routes/api/contacts.js +67 -12
- package/server/routes/api/launchers.js +3 -2
- package/server/services/adminAssistant.js +3 -1
- package/server/services/aiAssist.js +44 -0
- package/server/services/chat/ai.js +21 -9
- package/server/services/chat/conversation.js +40 -2
- package/server/services/permissionRegistry.js +11 -0
- package/server/services/plugins.js +4 -0
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
* That asymmetry is preserved rather than tidied - changing who can see a group
|
|
12
12
|
* is a behaviour change, and this was a relocation. A test pins it so the next
|
|
13
13
|
* reader finds it stated rather than inferred.
|
|
14
|
+
* The one exception is a `contacts-restricted` person (RESTRICTED below), who
|
|
15
|
+
* sees and uses only the groups they created.
|
|
14
16
|
*
|
|
15
17
|
* Because a group is shared, renaming or deleting one rewrites every user's
|
|
16
18
|
* contacts. So only the group's creator (`meta.createdBy`, recorded on new
|
|
@@ -33,7 +35,7 @@ import {registerToolTrash, trashToolEntry} from '../../services/tool-trash.js';
|
|
|
33
35
|
import {authenticate as defaultAuthenticate, requirePermission as defaultRequirePermission} from '../../middleware/auth.js';
|
|
34
36
|
import {createEntry, deleteEntry, getEntry, listEntries, updateEntry} from '../../services/collections.js';
|
|
35
37
|
import {hooks} from '../../services/hooks.js';
|
|
36
|
-
import {getPermissionsFor} from '../../services/roles.js';
|
|
38
|
+
import {getPermissionsFor, getPermissionsForRole, getRoleLevel} from '../../services/roles.js';
|
|
37
39
|
import {getEffectiveRoles} from '../../services/userRoles.js';
|
|
38
40
|
import {ago, clip, plural} from '../../services/sidebarBadges.js';
|
|
39
41
|
|
|
@@ -59,6 +61,44 @@ function defaultHoldsManageGroups(request) {
|
|
|
59
61
|
return getEffectiveRoles(request.user).some(r => allowed.includes(r));
|
|
60
62
|
}
|
|
61
63
|
|
|
64
|
+
/**
|
|
65
|
+
* `contacts-restricted`: Contacts for a person's own address book and nothing
|
|
66
|
+
* more - for outside accounts such as a Job Board candidate or hiring company.
|
|
67
|
+
* Groups are shared on the site, so a restricted person sees, uses and counts
|
|
68
|
+
* only the groups they created themselves, and can put a contact only in one
|
|
69
|
+
* of those. Someone else's group is "not found" to them. Contacts Pro reads
|
|
70
|
+
* the same permission for its own surfaces (people list, sharing, fields).
|
|
71
|
+
*/
|
|
72
|
+
export const RESTRICTED = 'contacts-restricted';
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The rule, pure (the lookups are passed in) - the same as Docs' docs-restricted:
|
|
76
|
+
* restricted when a role held carries the mark and no role held opens Contacts
|
|
77
|
+
* without it. A level-0 role is never restricted.
|
|
78
|
+
*
|
|
79
|
+
* @param {string[]} roles - every role the person holds
|
|
80
|
+
* @param {{isRoot: Function, marked: Function, givesContacts: Function}} look
|
|
81
|
+
* @returns {boolean}
|
|
82
|
+
*/
|
|
83
|
+
export function contactsRestricted(roles, {isRoot, marked, givesContacts}) {
|
|
84
|
+
const list = (Array.isArray(roles) ? roles : []).filter(r => typeof r === 'string' && r);
|
|
85
|
+
if (!list.length || list.some(isRoot)) return false;
|
|
86
|
+
if (!list.some(marked)) return false;
|
|
87
|
+
return !list.some(r => givesContacts(r) && !marked(r));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Is the caller restricted? A lookup that throws restricts (fail closed). */
|
|
91
|
+
function defaultIsRestricted(request) {
|
|
92
|
+
if (!request.user) return false;
|
|
93
|
+
try {
|
|
94
|
+
return contactsRestricted(getEffectiveRoles(request.user), {
|
|
95
|
+
isRoot: (r) => getRoleLevel(r) === 0,
|
|
96
|
+
marked: (r) => getPermissionsForRole(r).some(p => p === RESTRICTED || String(p).startsWith(`${RESTRICTED}.`)),
|
|
97
|
+
givesContacts: (r) => getPermissionsFor('contacts', 'read').includes(r)
|
|
98
|
+
});
|
|
99
|
+
} catch { return true; }
|
|
100
|
+
}
|
|
101
|
+
|
|
62
102
|
const CONTACTS_SLUG = 'contacts-contacts';
|
|
63
103
|
const GROUPS_SLUG = 'contacts-groups';
|
|
64
104
|
|
|
@@ -114,6 +154,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
114
154
|
const authenticate = opts.authenticate || defaultAuthenticate;
|
|
115
155
|
const requirePermission = opts.requirePermission || defaultRequirePermission;
|
|
116
156
|
const holdsManageGroups = opts.holdsManageGroups || defaultHoldsManageGroups;
|
|
157
|
+
const isRestricted = opts.isRestricted || defaultIsRestricted;
|
|
117
158
|
|
|
118
159
|
registerToolTrash(fastify, {slug: CONTACTS_SLUG, resource: 'contacts', itemPath: '/contacts', authenticate, requirePermission, project: toContact, onPurge: entry => hooks.emit('contact:deleted', {id: entry.id, userId: entry.data.userId})});
|
|
119
160
|
|
|
@@ -133,6 +174,21 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
133
174
|
return entries.map(e => ({id: e.id, name: toGroupName(e), createdBy: e.meta?.createdBy ?? null}));
|
|
134
175
|
}
|
|
135
176
|
|
|
177
|
+
/** The groups this caller sees: every group, or a restricted person's own. */
|
|
178
|
+
async function visibleGroups(request) {
|
|
179
|
+
const groups = await loadGroups();
|
|
180
|
+
if (!isRestricted(request)) return groups;
|
|
181
|
+
const uid = userId(request);
|
|
182
|
+
return groups.filter(g => uid && g.createdBy === uid);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A contact's `groups` as this caller may set them: a restricted person's own groups only. */
|
|
186
|
+
async function allowedGroups(request, contact) {
|
|
187
|
+
if (!Array.isArray(contact.groups) || !contact.groups.length || !isRestricted(request)) return contact;
|
|
188
|
+
const mine = new Set((await visibleGroups(request)).map(g => g.name));
|
|
189
|
+
return {...contact, groups: contact.groups.filter(g => mine.has(g))};
|
|
190
|
+
}
|
|
191
|
+
|
|
136
192
|
/**
|
|
137
193
|
* May this caller rename or delete this group? Its creator may; so may
|
|
138
194
|
* anyone holding contacts.manageGroups. A group from before creators were
|
|
@@ -141,7 +197,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
141
197
|
function canManageGroup(request, group) {
|
|
142
198
|
const uid = userId(request);
|
|
143
199
|
if (uid && group.createdBy && group.createdBy === uid) return true;
|
|
144
|
-
return holdsManageGroups(request) === true;
|
|
200
|
+
return !isRestricted(request) && holdsManageGroups(request) === true;
|
|
145
201
|
}
|
|
146
202
|
|
|
147
203
|
const NOT_YOURS = 'Only the person who created this group, or someone allowed to manage every group, can rename or delete it.';
|
|
@@ -152,7 +208,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
152
208
|
|
|
153
209
|
/** GET /api/contacts/count - the sidebar badge (contactsBadge). */
|
|
154
210
|
fastify.get('/count', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request) => {
|
|
155
|
-
const [contacts, groups] = await Promise.all([loadContacts(userId(request)),
|
|
211
|
+
const [contacts, groups] = await Promise.all([loadContacts(userId(request)), visibleGroups(request)]);
|
|
156
212
|
return contactsBadge(contacts, groups.length);
|
|
157
213
|
});
|
|
158
214
|
|
|
@@ -191,7 +247,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
191
247
|
return reply.code(400).send({ error: 'name is required' });
|
|
192
248
|
}
|
|
193
249
|
|
|
194
|
-
const entry = await createEntry(CONTACTS_SLUG, buildContact(body, uid),
|
|
250
|
+
const entry = await createEntry(CONTACTS_SLUG, await allowedGroups(request, buildContact(body, uid)),
|
|
195
251
|
{createdBy: uid, source: 'admin'});
|
|
196
252
|
|
|
197
253
|
return reply.code(201).send(toContact(entry));
|
|
@@ -210,7 +266,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
210
266
|
// Coerced exactly as create (buildContact) does: the editor sends
|
|
211
267
|
// payment terms as the input's string and a PUT used to store "30"
|
|
212
268
|
// where a POST stores 30 - and a bare `favourite: "false"` was truthy.
|
|
213
|
-
const shaped = buildContact({...entry.data, ...updates}, entry.data.userId ?? null);
|
|
269
|
+
const shaped = await allowedGroups(request, buildContact({...entry.data, ...updates}, entry.data.userId ?? null));
|
|
214
270
|
const merged = {...entry.data};
|
|
215
271
|
for (const key of TEXT_FIELDS) {
|
|
216
272
|
if (key in updates) merged[key] = shaped[key];
|
|
@@ -280,7 +336,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
280
336
|
|
|
281
337
|
/** GET /api/contacts/groups */
|
|
282
338
|
fastify.get('/groups', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request, reply) => {
|
|
283
|
-
const groups = await
|
|
339
|
+
const groups = await visibleGroups(request);
|
|
284
340
|
return reply.send(groups.map(g => g.name));
|
|
285
341
|
});
|
|
286
342
|
|
|
@@ -291,8 +347,8 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
291
347
|
*/
|
|
292
348
|
fastify.get('/groups/access', {preHandler: [authenticate, requirePermission('contacts', 'read')]}, async (request, reply) => {
|
|
293
349
|
const uid = userId(request);
|
|
294
|
-
const manageAll = holdsManageGroups(request) === true;
|
|
295
|
-
const groups = await
|
|
350
|
+
const manageAll = !isRestricted(request) && holdsManageGroups(request) === true;
|
|
351
|
+
const groups = await visibleGroups(request);
|
|
296
352
|
return reply.send({
|
|
297
353
|
manageAll,
|
|
298
354
|
groups: groups.map(g => {
|
|
@@ -331,7 +387,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
331
387
|
}
|
|
332
388
|
|
|
333
389
|
const groups = await loadGroups();
|
|
334
|
-
const grpEntry =
|
|
390
|
+
const grpEntry = (await visibleGroups(request)).find(g => g.name === oldName);
|
|
335
391
|
if (!grpEntry) return reply.code(404).send({error: 'Group not found'});
|
|
336
392
|
if (!canManageGroup(request, grpEntry)) return reply.code(403).send({error: NOT_YOURS});
|
|
337
393
|
|
|
@@ -362,8 +418,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
362
418
|
fastify.delete('/groups/:name', {preHandler: [authenticate, requirePermission('contacts', 'delete')]}, async (request, reply) => {
|
|
363
419
|
const name = decodeURIComponent(request.params.name);
|
|
364
420
|
|
|
365
|
-
const
|
|
366
|
-
const grpEntry = groups.find(g => g.name === name);
|
|
421
|
+
const grpEntry = (await visibleGroups(request)).find(g => g.name === name);
|
|
367
422
|
if (!grpEntry) return reply.code(404).send({error: 'Group not found'});
|
|
368
423
|
if (!canManageGroup(request, grpEntry)) return reply.code(403).send({error: NOT_YOURS});
|
|
369
424
|
|
|
@@ -410,7 +465,7 @@ export async function contactsRoutes(fastify, opts = {}) {
|
|
|
410
465
|
let imported = 0;
|
|
411
466
|
for (const raw of incoming) {
|
|
412
467
|
if (!raw || typeof raw.name !== 'string') continue;
|
|
413
|
-
await createEntry(CONTACTS_SLUG, buildContact(raw, uid), {source: 'import'});
|
|
468
|
+
await createEntry(CONTACTS_SLUG, await allowedGroups(request, buildContact(raw, uid)), {source: 'import'});
|
|
414
469
|
imported++;
|
|
415
470
|
}
|
|
416
471
|
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* /api/launchers behind the Tool's switch (toolGate), so it answers 404 while
|
|
4
4
|
* Launchers is switched off.
|
|
5
5
|
*
|
|
6
|
-
* GET /api/launchers/items - every launcher, in order (settings.read)
|
|
6
|
+
* GET /api/launchers/items - every launcher, in order, and whether AI Assist is on (settings.read)
|
|
7
7
|
* PUT /api/launchers/items - {launchers: [...]}: the whole list - edits, order, on/off (settings.update)
|
|
8
8
|
* PATCH /api/launchers/items/:id - a patch over one launcher, e.g. {enabled: false} (settings.update)
|
|
9
9
|
* GET /api/launchers/_count - the sidebar badge (settings.read)
|
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
import {
|
|
20
20
|
LAUNCHERS_ASSET_V, getLaunchers, launchersBadge, launchersForAdmin, saveLaunchers, updateLauncher
|
|
21
21
|
} from '../../services/launchers.js';
|
|
22
|
+
import {isAiAssist} from '../../services/aiAssist.js';
|
|
22
23
|
|
|
23
24
|
/** Far more than any site will want, and small enough that a runaway client cannot write megabytes into every page. */
|
|
24
25
|
const MAX_LAUNCHERS = 100;
|
|
@@ -33,7 +34,7 @@ export async function launchersRoutes(fastify, opts = {}) {
|
|
|
33
34
|
const canRead = {preHandler: [authenticate, requirePermission('settings', 'read')]};
|
|
34
35
|
const canUpdate = {preHandler: [authenticate, requirePermission('settings', 'update')]};
|
|
35
36
|
|
|
36
|
-
fastify.get('/items', canRead, async () => ({launchers: getLaunchers()}));
|
|
37
|
+
fastify.get('/items', canRead, async () => ({launchers: getLaunchers(), aiAssist: isAiAssist()}));
|
|
37
38
|
|
|
38
39
|
fastify.put('/items', canUpdate, async (request, reply) => {
|
|
39
40
|
const list = request.body?.launchers;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import {getConfig} from '../config.js';
|
|
3
3
|
import {adminAccessFor} from './adminAccess.js';
|
|
4
4
|
import {covers} from './pluginScope.js';
|
|
5
|
+
import {isAiAssist} from './aiAssist.js';
|
|
5
6
|
import {characterId, normaliseCharacterSettings} from '../../public/js/characters.mjs';
|
|
6
7
|
|
|
7
8
|
const providers = new Map();
|
|
@@ -58,10 +59,11 @@ export function adminAssistantConfig() {
|
|
|
58
59
|
const settings = normaliseAdminAssistant(site.adminAssistant);
|
|
59
60
|
const characters = normaliseCharacterSettings(site.characters);
|
|
60
61
|
return {...settings, character: characters.enabled ? settings.character : '', charactersEnabled: characters.enabled, animated: characters.animated,
|
|
61
|
-
available: Boolean(globalThis[Symbol.for('domma.launcher-chat')] || process.env.MANAGER_URL && process.env.FLEET_TOKEN)};
|
|
62
|
+
available: isAiAssist() && Boolean(globalThis[Symbol.for('domma.launcher-chat')] || process.env.MANAGER_URL && process.env.FLEET_TOKEN)};
|
|
62
63
|
}
|
|
63
64
|
|
|
64
65
|
export async function requestAdminAnswer(input, {env = process.env, fetchFn = fetch} = {}) {
|
|
66
|
+
if (!isAiAssist()) return {status: 403, body: {error: 'AI answers come with AI Assist, in the Pro plan.'}};
|
|
65
67
|
const local = globalThis[Symbol.for('domma.launcher-chat')];
|
|
66
68
|
if (local) return local.answer(input);
|
|
67
69
|
if (!env.MANAGER_URL || !env.FLEET_TOKEN) return {status: 503, body: {error: 'AI answers are not configured on this site.'}};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Assist - the switch for AI chat answers on this site.
|
|
3
|
+
*
|
|
4
|
+
* Della's (and any character's) AI answers in chat launchers, admin launchers
|
|
5
|
+
* and the admin assistant come with AI Assist, a paid Tool in the Pro plan. The
|
|
6
|
+
* Tool calls `hooks.enableAiAssist()` at boot (plugins.js binds it to the
|
|
7
|
+
* plugin's name, tier and closedSource, as for Dashboard Pro): only a paid,
|
|
8
|
+
* closed-source plugin - one that loads only under a licence - may switch it on.
|
|
9
|
+
* Disabling the Tool switches it off at once (plugins.js runLifecycleHook).
|
|
10
|
+
*
|
|
11
|
+
* The Manager still checks the site's AI Assist licence on every answer; this
|
|
12
|
+
* switch only means the site does not offer or ask for answers it cannot have.
|
|
13
|
+
*
|
|
14
|
+
* @module services/aiAssist
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const owners = new Set();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {{owner: string, tier: string, closedSource: boolean}} who
|
|
21
|
+
* @returns {boolean} whether it is now on
|
|
22
|
+
*/
|
|
23
|
+
export function enableAiAssist({owner, tier, closedSource} = {}) {
|
|
24
|
+
if (typeof owner !== 'string' || !owner.trim()) return false;
|
|
25
|
+
if (tier !== 'paid' || closedSource !== true) return false;
|
|
26
|
+
owners.add(owner.trim());
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The Tool that kept it on was disabled; the last one gone switches it off. */
|
|
31
|
+
export function disableAiAssist(owner) {
|
|
32
|
+
owners.delete(String(owner || '').trim());
|
|
33
|
+
return owners.size > 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Whether this site has AI Assist right now. */
|
|
37
|
+
export function isAiAssist() {
|
|
38
|
+
return owners.size > 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Tests only: forget every owner. */
|
|
42
|
+
export function _resetAiAssistForTests() {
|
|
43
|
+
owners.clear();
|
|
44
|
+
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Della's AI answers - what the chat bot says when the Knowledge has no answer.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
4
|
+
* Comes with AI Assist (a Tool in the Pro plan, services/aiAssist.js) on hosted sites, so a site holds no Claude key: the question goes to the Manager
|
|
5
5
|
* that runs the site (MANAGER_URL + FLEET_TOKEN, POST /api/fleet/launcher-chat), which checks the licence and
|
|
6
6
|
* the month's allowance and asks Claude from a short-lived job that alone reads the key. On dcm, which is the
|
|
7
7
|
* Manager, the same code is reached in this process (globalThis[Symbol.for('domma.launcher-chat')]). A site
|
|
8
|
-
* with
|
|
8
|
+
* without AI Assist, or with no Manager to ask, has no AI answers, and the bot answers from the Knowledge alone.
|
|
9
9
|
*
|
|
10
10
|
* What Claude is given: the site's name, Site Settings > AI assistant and the launcher's own context and rules
|
|
11
11
|
* (services/assistant.js), the enabled Knowledge, the last few messages of this chat and the question. It
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import {assistantBrief} from '../assistant.js';
|
|
18
18
|
import {knowledgeIndex, messagesAfter} from './store.js';
|
|
19
|
+
import {isAiAssist} from '../aiAssist.js';
|
|
19
20
|
|
|
20
21
|
const REGISTRY = Symbol.for('domma.launcher-chat');
|
|
21
22
|
/** What a visitor will wait for an answer. */
|
|
@@ -29,9 +30,9 @@ const BACKOFF_MS = {403: 10 * 60_000, 429: 30 * 60_000, other: 60_000};
|
|
|
29
30
|
let restUntil = 0;
|
|
30
31
|
export function _resetAi() { restUntil = 0; }
|
|
31
32
|
|
|
32
|
-
/** Whether this site has someone to ask. */
|
|
33
|
+
/** Whether this site has AI Assist and someone to ask. */
|
|
33
34
|
export function aiAvailable(env = process.env, at = Date.now()) {
|
|
34
|
-
if (at < restUntil) return false;
|
|
35
|
+
if (at < restUntil || !isAiAssist()) return false;
|
|
35
36
|
return Boolean(globalThis[REGISTRY] || (env.MANAGER_URL && env.FLEET_TOKEN));
|
|
36
37
|
}
|
|
37
38
|
|
|
@@ -81,8 +82,19 @@ async function ask(payload, {env, fetchFn}) {
|
|
|
81
82
|
* @param {{botName: string, aiContext?: string, aiRules?: string, useKnowledge?: boolean}} chat - the launcher's chat block
|
|
82
83
|
* @returns {Promise<string>} the answer, or '' (no answer: carry on without)
|
|
83
84
|
*/
|
|
84
|
-
export async function aiAnswer(id, question, chat,
|
|
85
|
-
|
|
85
|
+
export async function aiAnswer(id, question, chat, opts = {}) {
|
|
86
|
+
return (await aiReply(id, question, chat, opts)).text;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* As aiAnswer, and whether the AI turned the question down (off-topic, or the rules forbid it): its polite
|
|
91
|
+
* reply, if any, is still the text. The site tells its admins (conversation.js).
|
|
92
|
+
*
|
|
93
|
+
* @returns {Promise<{text: string, declined: boolean}>}
|
|
94
|
+
*/
|
|
95
|
+
export async function aiReply(id, question, chat, {env = process.env, fetchFn = fetch, log = console} = {}) {
|
|
96
|
+
const none = {text: '', declined: false};
|
|
97
|
+
if (!aiAvailable(env)) return none;
|
|
86
98
|
try {
|
|
87
99
|
const brief = assistantBrief(chat);
|
|
88
100
|
const {byId} = chat.useKnowledge === false ? {byId: new Map()} : await knowledgeIndex();
|
|
@@ -97,13 +109,13 @@ export async function aiAnswer(id, question, chat, {env = process.env, fetchFn =
|
|
|
97
109
|
question
|
|
98
110
|
};
|
|
99
111
|
const {status, body} = await ask(payload, {env, fetchFn});
|
|
100
|
-
if (status === 200) return typeof body?.answer === 'string' ? body.answer.trim() : '';
|
|
112
|
+
if (status === 200) return {text: typeof body?.answer === 'string' ? body.answer.trim() : '', declined: body?.declined === true};
|
|
101
113
|
restUntil = Date.now() + (BACKOFF_MS[status] || BACKOFF_MS.other);
|
|
102
114
|
if (status !== 429) log.warn?.(`[chat] AI answers unavailable (${status}): ${String(body?.error || '').slice(0, 120)}`);
|
|
103
|
-
return
|
|
115
|
+
return none;
|
|
104
116
|
} catch (err) {
|
|
105
117
|
restUntil = Date.now() + BACKOFF_MS.other;
|
|
106
118
|
log.warn?.(`[chat] AI answer failed: ${err.message}`);
|
|
107
|
-
return
|
|
119
|
+
return none;
|
|
108
120
|
}
|
|
109
121
|
}
|
|
@@ -27,9 +27,13 @@ import {
|
|
|
27
27
|
patchSession, removeSession, removeSessionsAndOrphans, renderAnswer, staffAvailable, withChat
|
|
28
28
|
} from './store.js';
|
|
29
29
|
import {readChatSettings, staffDisplayName} from './settings.js';
|
|
30
|
-
import {
|
|
30
|
+
import {aiReply} from './ai.js';
|
|
31
31
|
|
|
32
32
|
export const SOURCE = 'core:chat';
|
|
33
|
+
/** A visitor started a chat (their first message). */
|
|
34
|
+
export const STARTED_SOURCE = 'core:chat-started';
|
|
35
|
+
/** The AI turned a visitor's question down (off-topic, or the launcher's rules forbid it). */
|
|
36
|
+
export const DECLINED_SOURCE = 'core:chat-declined';
|
|
33
37
|
const int = (v) => (Number.isFinite(Number(v)) ? Math.trunc(Number(v)) : 0);
|
|
34
38
|
const ACTIVE = ['waiting', 'open', 'message'];
|
|
35
39
|
|
|
@@ -60,6 +64,16 @@ export function registerChatSource() {
|
|
|
60
64
|
description: 'A visitor asked to talk to a person, or left a message for the team because nobody was available.',
|
|
61
65
|
severity: 'info', audience: 'admins'
|
|
62
66
|
});
|
|
67
|
+
registerNotificationSource({
|
|
68
|
+
id: STARTED_SOURCE, owner: 'core', label: 'Visitor chat started',
|
|
69
|
+
description: 'A visitor started a chat, whether the bot or a person answers it.',
|
|
70
|
+
severity: 'info', audience: 'admins'
|
|
71
|
+
});
|
|
72
|
+
registerNotificationSource({
|
|
73
|
+
id: DECLINED_SOURCE, owner: 'core', label: 'Chat question turned down',
|
|
74
|
+
description: 'The AI turned down a visitor\'s question in chat: off-topic, or something the launcher\'s rules forbid.',
|
|
75
|
+
severity: 'info', audience: 'admins'
|
|
76
|
+
});
|
|
63
77
|
}
|
|
64
78
|
|
|
65
79
|
const noticeKey = (id) => `chat:${id}`;
|
|
@@ -77,6 +91,27 @@ function raise(session, kind) {
|
|
|
77
91
|
|
|
78
92
|
const settle = (id) => resolveNotification(noticeKey(id), SOURCE).catch(() => 0);
|
|
79
93
|
|
|
94
|
+
/** What the admins are told about the chat: the visitor's words (as the Chats screen shows them) and the page. */
|
|
95
|
+
const quoted = (text) => `"${cleanText(text, 200).replace(/\n/g, ' ')}"`;
|
|
96
|
+
|
|
97
|
+
/** A visitor's first message: the chat has started. */
|
|
98
|
+
function raiseStarted(session, text, chat) {
|
|
99
|
+
const d = session.data;
|
|
100
|
+
const where = d.page ? `\nPage: ${d.page}` : '';
|
|
101
|
+
const who = chat.bot ? `${chat.botName || 'The bot'} is answering.` : 'It is waiting for a person.';
|
|
102
|
+
return notify({severity: 'info', title: `${d.visitorName || 'A visitor'} started a chat`, body: `${quoted(text)}\n\n${who}${where}`,
|
|
103
|
+
source: STARTED_SOURCE, dedupeKey: `chat-started:${session.id}`, link: '#/launchers/chats'}).catch(() => null);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The AI turned a question down. One notice per chat, said again in place for the next. */
|
|
107
|
+
function raiseDeclined(session, text, chat) {
|
|
108
|
+
const d = session.data;
|
|
109
|
+
const where = d.page ? `\nPage: ${d.page}` : '';
|
|
110
|
+
return notify({severity: 'info', title: `${chat.botName || 'The bot'} turned down a question in chat`,
|
|
111
|
+
body: `${d.visitorName || 'A visitor'} asked: ${quoted(text)}\n\nIt is off-topic or against the launcher's rules, so it was not answered.${where}`,
|
|
112
|
+
source: DECLINED_SOURCE, dedupeKey: `chat-declined:${session.id}`, link: '#/launchers/chats'}).catch(() => null);
|
|
113
|
+
}
|
|
114
|
+
|
|
80
115
|
// ---------------------------------------------------------------------------
|
|
81
116
|
// What visitors and staff see
|
|
82
117
|
// ---------------------------------------------------------------------------
|
|
@@ -168,7 +203,8 @@ async function aiTurn(id, text, chat, session) {
|
|
|
168
203
|
if (!chat.ai) return null;
|
|
169
204
|
const used = int(session?.data.aiCount);
|
|
170
205
|
if (used >= int(chat.aiMaxPerChat ?? 20)) return null;
|
|
171
|
-
const said = await
|
|
206
|
+
const {text: said, declined} = await aiReply(id, text, chat);
|
|
207
|
+
if (declined && session) raiseDeclined(session, text, chat);
|
|
172
208
|
return said ? addMessage(id, {from: 'bot', text: said, ai: true}, {misses: 0, aiCount: used + 1}) : null;
|
|
173
209
|
}
|
|
174
210
|
|
|
@@ -251,6 +287,8 @@ export function visitorSays(id, text, chat) {
|
|
|
251
287
|
if (full(session)) return {error: SAY.full, code: 409};
|
|
252
288
|
const staffSide = ACTIVE.includes(session.data.status);
|
|
253
289
|
const wrote = await addMessage(id, {from: 'visitor', text: clean}, staffSide ? {unread: int(session.data.unread) + 1} : {});
|
|
290
|
+
// The first thing the visitor says starts the chat (the summary is set from it).
|
|
291
|
+
if (!session.data.summary && wrote?.session) raiseStarted(wrote.session, clean, chat);
|
|
254
292
|
if (!staffSide) {
|
|
255
293
|
if (chat.bot) await botReply(id, clean, chat, readChatSettings());
|
|
256
294
|
else await handoverNow(id, chat);
|
|
@@ -216,6 +216,17 @@ export const REGISTRY = [
|
|
|
216
216
|
{key: 'manageGroups', label: 'Manage groups', description: 'Rename or delete any group, not only the ones they created - groups are shared, so this changes everyone\'s contacts'}
|
|
217
217
|
]
|
|
218
218
|
},
|
|
219
|
+
{
|
|
220
|
+
// routes/api/contacts.js RESTRICTED; Contacts Pro reads it too. For outside accounts (a Job Board's).
|
|
221
|
+
key: 'contacts-restricted',
|
|
222
|
+
label: 'Contacts: own address book only',
|
|
223
|
+
description: 'A role with this uses Contacts for its own address book and nothing more: only the groups it made, no list of people, no sharing, no shared fields. It changes nothing for a person who also holds a role that gives Contacts without it, and nothing for the top (level-0) role.',
|
|
224
|
+
icon: 'lock',
|
|
225
|
+
group: 'Tools',
|
|
226
|
+
actions: [
|
|
227
|
+
{key: 'on', label: 'Restricted', description: 'Own contacts and own groups only'}
|
|
228
|
+
]
|
|
229
|
+
},
|
|
219
230
|
{
|
|
220
231
|
// Instant calls (services/instantCalls.js). Only in use while a Pro Tool with calls
|
|
221
232
|
// (Booking Pro, Contacts Pro, Calendar) is running; admins are granted it then, once.
|
|
@@ -43,6 +43,7 @@ import {disableInstantCalls, enableInstantCalls, grantInstantCallsOnce} from './
|
|
|
43
43
|
import {claimHosts} from './hostClaims.js';
|
|
44
44
|
import {pluginSafeFetch} from './outbound.js';
|
|
45
45
|
import {disableDashboardPro, enableDashboardPro, registerWidget, unregisterWidgetsFrom} from './widgets.js';
|
|
46
|
+
import {disableAiAssist, enableAiAssist} from './aiAssist.js';
|
|
46
47
|
import {createCollection, getCollection, updateCollection} from './collections.js';
|
|
47
48
|
import * as defaultRolesService from './roles.js';
|
|
48
49
|
import {getAdminScope, normaliseAdminScope} from './roles.js';
|
|
@@ -580,6 +581,8 @@ export async function registerPlugins(fastify) {
|
|
|
580
581
|
enableInstantCalls: () => enableInstantCalls({owner: manifest.name, tier: manifest.tier || 'free', closedSource: manifest.closedSource === true}),
|
|
581
582
|
// Dashboard Pro (services/widgets.js) - the widget board; the same contract as instant calls.
|
|
582
583
|
enableDashboardPro: () => enableDashboardPro({owner: manifest.name, tier: manifest.tier || 'free', closedSource: manifest.closedSource === true}),
|
|
584
|
+
// AI Assist (services/aiAssist.js) - AI chat answers in launchers and the admin assistant; the same contract.
|
|
585
|
+
enableAiAssist: () => enableAiAssist({owner: manifest.name, tier: manifest.tier || 'free', closedSource: manifest.closedSource === true}),
|
|
583
586
|
// A widget from code (anything richer than a manifest's admin.widgets entry), owned by this plugin.
|
|
584
587
|
registerWidget: (def) => registerWidget({...def, owner: manifest.name, source: manifest.displayName || manifest.name}),
|
|
585
588
|
// Who may read a contact that is not their own (Contacts Pro's sharing) - hooks.js 7b.
|
|
@@ -1168,6 +1171,7 @@ export async function runLifecycleHook(name, hook, fastify) {
|
|
|
1168
1171
|
if (hook === 'onDisable') {
|
|
1169
1172
|
disableInstantCalls(name);
|
|
1170
1173
|
disableDashboardPro(name);
|
|
1174
|
+
disableAiAssist(name);
|
|
1171
1175
|
unregisterWidgetsFrom(name);
|
|
1172
1176
|
unregisterContactAccess(name);
|
|
1173
1177
|
unregisterDirectMessenger(name);
|