@workover/cli 0.27.0 → 0.29.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/bin/workover.mjs +2244 -4
- package/contacts.mjs +1561 -0
- package/domains.mjs +417 -0
- package/email-studio.mjs +829 -0
- package/feedback-board.mjs +321 -0
- package/journeys.mjs +409 -0
- package/package.json +20 -1
- package/support-agent-tests.mjs +424 -0
- package/support-config.mjs +302 -0
- package/support-email.mjs +458 -0
- package/support-fields.mjs +294 -0
- package/support-freshdesk.mjs +176 -0
- package/support-inbox.mjs +313 -0
- package/support-label-rules.mjs +136 -0
- package/support-labels.mjs +244 -0
- package/support-outcomes.mjs +276 -0
- package/support-outside-bot.mjs +145 -0
- package/support-setup.mjs +660 -0
- package/support-signatures.mjs +156 -0
- package/support-sources.mjs +233 -0
- package/support-walter.mjs +310 -0
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// Support's labels from a terminal: `workover support labels ...` and the MCP server's
|
|
2
|
+
// `workover_support_*label*` tools (WO-1752, S63, Support settings > Labels).
|
|
3
|
+
//
|
|
4
|
+
// THE SAME FILE ships in @workover/cli (apps/cli/support-labels.mjs) and @workover/mcp
|
|
5
|
+
// (apps/mcp/support-labels.mjs), because the two packages are published separately and neither
|
|
6
|
+
// may depend on the other. `apps/mcp/support-labels.test.mjs` fails when the copies differ.
|
|
7
|
+
//
|
|
8
|
+
// Every label with how many conversations carry it, the labels conversations carry that the
|
|
9
|
+
// catalog does not spell, and adding, renaming, recoloring, archiving and merging. Every call goes
|
|
10
|
+
// to a route opened to tokens holding the `support` scope (`workover login --support`); adding is
|
|
11
|
+
// any teammate's, the other changes the workspace owner's or an admin's. Each write is safe to
|
|
12
|
+
// repeat: the same label added again is answered as it is, the same rename, color or archive again
|
|
13
|
+
// changes nothing, and the same merge again answers 0 conversations.
|
|
14
|
+
//
|
|
15
|
+
// `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
|
|
16
|
+
// whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
|
|
17
|
+
// return lines, for a terminal or an MCP text result alike.
|
|
18
|
+
|
|
19
|
+
import { apiError, resolveWorkspace } from './site-setup.mjs';
|
|
20
|
+
|
|
21
|
+
export const LABEL_COLORS = ['gray', 'blue', 'green', 'amber', 'red', 'violet'];
|
|
22
|
+
|
|
23
|
+
/** The Messenger whose labels these are: Support has to exist first. */
|
|
24
|
+
async function messengerOf(call, workspace) {
|
|
25
|
+
const ws = await resolveWorkspace(call, workspace);
|
|
26
|
+
const status = await call(`/messenger/agent-setup?organizationId=${encodeURIComponent(ws.id)}`);
|
|
27
|
+
const id = status?.messenger?.id;
|
|
28
|
+
if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
|
|
29
|
+
return { ws, messengerId: id };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A label named by its id or its full name ("Billing / Refunds"), whatever the case. */
|
|
33
|
+
function findLabel(labels, ref) {
|
|
34
|
+
const raw = String(ref ?? '').trim();
|
|
35
|
+
if (!raw) throw apiError(400, 'Name the label, by its id or its full name. `workover support labels` lists them.');
|
|
36
|
+
const n = Number(raw);
|
|
37
|
+
const hit =
|
|
38
|
+
(Number.isInteger(n) && n > 0 ? labels.find((l) => l.id === n) : undefined) ??
|
|
39
|
+
labels.find((l) => l.path.toLowerCase() === raw.toLowerCase());
|
|
40
|
+
if (!hit) throw apiError(404, `There is no label "${raw}". \`workover support labels\` lists them.`);
|
|
41
|
+
return hit;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Every label with its count, archived ones marked, and the labels the catalog does not spell. */
|
|
45
|
+
export async function listLabels(call, { workspace } = {}) {
|
|
46
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
47
|
+
const res = await call(`/messenger/${messengerId}/label-usage`);
|
|
48
|
+
return { workspace: ws, ...res };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Rename, recolor, archive or restore one label. Fields left out stay. */
|
|
52
|
+
export async function updateLabel(call, { workspace, label, name, color, archived }) {
|
|
53
|
+
const body = {};
|
|
54
|
+
if (name !== undefined) body.name = String(name);
|
|
55
|
+
if (color !== undefined) {
|
|
56
|
+
const c = String(color).toLowerCase();
|
|
57
|
+
if (!LABEL_COLORS.includes(c)) throw apiError(400, `color is one of ${LABEL_COLORS.join(', ')}.`);
|
|
58
|
+
body.color = c;
|
|
59
|
+
}
|
|
60
|
+
if (archived !== undefined) body.archived = Boolean(archived);
|
|
61
|
+
if (!Object.keys(body).length) throw apiError(400, 'Give a new name, a color, or archive or restore it.');
|
|
62
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
63
|
+
const { labels } = await call(`/messenger/${messengerId}/label-usage`);
|
|
64
|
+
const target = findLabel(labels ?? [], label);
|
|
65
|
+
const res = await call(`/messenger/${messengerId}/labels/${target.id}`, { method: 'PATCH', body });
|
|
66
|
+
return { workspace: ws, label: res };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Add a label, optionally inside a top-level one. Safe to repeat: a live label with the same full
|
|
71
|
+
* name (whatever the case) is answered as it is (`created: false`); an archived one is named, to
|
|
72
|
+
* restore with `set <id> --restore`, rather than added again.
|
|
73
|
+
*/
|
|
74
|
+
export async function createLabel(call, { workspace, name, inside, color }) {
|
|
75
|
+
const own = String(name ?? '').trim();
|
|
76
|
+
if (!own) throw apiError(400, 'Name the label.');
|
|
77
|
+
if (own.includes('/')) throw apiError(400, 'A label name has no slash. Use --inside to nest it.');
|
|
78
|
+
let c;
|
|
79
|
+
if (color !== undefined) {
|
|
80
|
+
c = String(color).toLowerCase();
|
|
81
|
+
if (!LABEL_COLORS.includes(c)) throw apiError(400, `color is one of ${LABEL_COLORS.join(', ')}.`);
|
|
82
|
+
}
|
|
83
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
84
|
+
const { labels = [] } = await call(`/messenger/${messengerId}/label-usage`);
|
|
85
|
+
const parent = inside === undefined || inside === null || inside === '' ? null : findLabel(labels, inside);
|
|
86
|
+
if (parent && parent.parentId != null) throw apiError(400, 'Labels nest one level deep: pick a top-level label.');
|
|
87
|
+
const path = parent ? `${parent.path} / ${own}` : own;
|
|
88
|
+
const same = labels.find((l) => l.path.toLowerCase() === path.toLowerCase());
|
|
89
|
+
if (same?.archived)
|
|
90
|
+
throw apiError(409, `"${same.path}" is archived. Restore it: \`workover support labels set ${same.id} --restore\`.`);
|
|
91
|
+
if (same) return { workspace: ws, label: same, created: false };
|
|
92
|
+
const res = await call(`/messenger/${messengerId}/labels`, {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
body: { name: own, ...(c ? { color: c } : {}), parentId: parent ? parent.id : null },
|
|
95
|
+
});
|
|
96
|
+
return { workspace: ws, label: res, created: true };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Merge labels (catalog ones, or ones only conversations carry) into one catalog label. */
|
|
100
|
+
export async function mergeLabels(call, { workspace, into, from }) {
|
|
101
|
+
const list = (Array.isArray(from) ? from : String(from ?? '').split(','))
|
|
102
|
+
.map((s) => String(s).trim())
|
|
103
|
+
.filter(Boolean);
|
|
104
|
+
if (!list.length) throw apiError(400, 'Name the labels to merge, separated by commas.');
|
|
105
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
106
|
+
const { labels } = await call(`/messenger/${messengerId}/label-usage`);
|
|
107
|
+
const target = findLabel(labels ?? [], into);
|
|
108
|
+
const res = await call(`/messenger/${messengerId}/labels/${target.id}/merge`, {
|
|
109
|
+
method: 'POST',
|
|
110
|
+
body: { from: list },
|
|
111
|
+
});
|
|
112
|
+
return { workspace: ws, ...res };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
116
|
+
|
|
117
|
+
export function renderLabelLine(l) {
|
|
118
|
+
const indent = l.parentId != null ? ' ' : ' ';
|
|
119
|
+
const tags = [l.color, l.archived ? 'archived' : null].filter(Boolean).join(', ');
|
|
120
|
+
return `${indent}${l.id} ${l.path} (${plural(l.count ?? 0, 'conversation', 'conversations')}; ${tags})`;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A label after a change: its full name, color, and whether it is archived. */
|
|
124
|
+
export function renderLabelSaved(l, verb = 'Saved') {
|
|
125
|
+
return ['', ` ✓ ${verb}: ${l.id} ${l.path} (${[l.color, l.archived ? 'archived' : null].filter(Boolean).join(', ')})`, ''];
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function renderLabels(res) {
|
|
129
|
+
const out = [''];
|
|
130
|
+
const labels = res.labels ?? [];
|
|
131
|
+
if (!labels.length) out.push(' No labels yet. Teammates add them from a conversation.');
|
|
132
|
+
else out.push(' Labels:', ...labels.map(renderLabelLine));
|
|
133
|
+
const unlisted = res.unlisted ?? [];
|
|
134
|
+
if (unlisted.length) {
|
|
135
|
+
out.push('', ' Carried on conversations but not in the catalog (merge them into a label):');
|
|
136
|
+
for (const u of unlisted) out.push(` ${u.path} (${plural(u.count, 'conversation', 'conversations')})`);
|
|
137
|
+
}
|
|
138
|
+
if (res.canManage === false) out.push('', ' Only workspace owners and admins can change labels.');
|
|
139
|
+
out.push('');
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function renderLabelMerged(res) {
|
|
144
|
+
const out = [
|
|
145
|
+
'',
|
|
146
|
+
` ✓ Merged into ${res.label.path}: ${plural(res.conversations, 'conversation', 'conversations')} changed; it is on ${res.label.count} now.`,
|
|
147
|
+
];
|
|
148
|
+
if (res.removed?.length) out.push(` Removed from the catalog: ${res.removed.join(', ')}.`);
|
|
149
|
+
out.push('');
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const WORKSPACE = {
|
|
154
|
+
type: 'string',
|
|
155
|
+
description: 'The workspace, by slug or id. Needed only when the account has more than one.',
|
|
156
|
+
};
|
|
157
|
+
const LABEL_REF = { type: 'string', description: 'The label, by its id or its full name ("Billing / Refunds").' };
|
|
158
|
+
const SCOPE =
|
|
159
|
+
' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
|
|
160
|
+
|
|
161
|
+
/** The MCP server's label tools, listed with the other Support tools (index.mjs). */
|
|
162
|
+
export const LABEL_TOOL_DEFS = [
|
|
163
|
+
{
|
|
164
|
+
name: 'workover_support_labels',
|
|
165
|
+
description:
|
|
166
|
+
"Support's labels: each with its id, color, whether it is archived, and how many conversations the inbox's label filter finds for it; and the labels conversations carry that no catalog label spells (\"billing\" beside \"Billing\"), which are worth merging." +
|
|
167
|
+
SCOPE,
|
|
168
|
+
inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
name: 'workover_support_create_label',
|
|
172
|
+
description:
|
|
173
|
+
'Add a label to Support, optionally inside a top-level label (one level of nesting). Any teammate. Safe to repeat: a label with the same full name is answered as it is; an archived one is named so it can be restored instead.' +
|
|
174
|
+
SCOPE,
|
|
175
|
+
inputSchema: {
|
|
176
|
+
type: 'object',
|
|
177
|
+
properties: {
|
|
178
|
+
workspace: WORKSPACE,
|
|
179
|
+
name: { type: 'string', description: 'Its own name, without a parent and without a slash.' },
|
|
180
|
+
inside: { type: 'string', description: 'The top-level label to nest it under, by id or name.' },
|
|
181
|
+
color: { type: 'string', enum: LABEL_COLORS },
|
|
182
|
+
},
|
|
183
|
+
required: ['name'],
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
name: 'workover_support_update_label',
|
|
188
|
+
description:
|
|
189
|
+
'Rename, recolor or archive (archived: true) or restore (false) a label. A new name reaches every conversation carrying it. An archived label leaves the picker and the filter but stays on conversations. Owners and admins. Safe to repeat.' +
|
|
190
|
+
SCOPE,
|
|
191
|
+
inputSchema: {
|
|
192
|
+
type: 'object',
|
|
193
|
+
properties: {
|
|
194
|
+
workspace: WORKSPACE,
|
|
195
|
+
label: LABEL_REF,
|
|
196
|
+
name: { type: 'string', description: 'Its own new name, without its parent.' },
|
|
197
|
+
color: { type: 'string', enum: LABEL_COLORS },
|
|
198
|
+
archived: { type: 'boolean' },
|
|
199
|
+
},
|
|
200
|
+
required: ['label'],
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
name: 'workover_support_merge_labels',
|
|
205
|
+
description:
|
|
206
|
+
'Merge labels into one: every conversation carrying a label in `from` (a catalog label, or one only conversations carry, whatever its case) carries `into` instead, once; merged catalog labels are removed and their children move under `into`. Ask the person first. Owners and admins. Safe to repeat.' +
|
|
207
|
+
SCOPE,
|
|
208
|
+
inputSchema: {
|
|
209
|
+
type: 'object',
|
|
210
|
+
properties: {
|
|
211
|
+
workspace: WORKSPACE,
|
|
212
|
+
into: LABEL_REF,
|
|
213
|
+
from: { type: 'array', items: { type: 'string' }, description: 'The labels to fold in, 1 to 20.' },
|
|
214
|
+
},
|
|
215
|
+
required: ['into', 'from'],
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
];
|
|
219
|
+
|
|
220
|
+
/** The label tools' names, for the MCP dispatcher. */
|
|
221
|
+
export const LABEL_TOOLS = new Set(LABEL_TOOL_DEFS.map((t) => t.name));
|
|
222
|
+
|
|
223
|
+
/** One label tool, run: the lines to answer with. Throws as `call` does. */
|
|
224
|
+
export async function runLabelTool(call, name, args = {}) {
|
|
225
|
+
const workspace = args.workspace === undefined || args.workspace === null ? undefined : String(args.workspace);
|
|
226
|
+
if (name === 'workover_support_labels') return renderLabels(await listLabels(call, { workspace }));
|
|
227
|
+
if (name === 'workover_support_create_label') {
|
|
228
|
+
const res = await createLabel(call, { workspace, name: args.name, inside: args.inside, color: args.color });
|
|
229
|
+
return renderLabelSaved(res.label, res.created ? 'Added' : 'Already there');
|
|
230
|
+
}
|
|
231
|
+
if (name === 'workover_support_update_label') {
|
|
232
|
+
const res = await updateLabel(call, {
|
|
233
|
+
workspace,
|
|
234
|
+
label: args.label,
|
|
235
|
+
name: args.name,
|
|
236
|
+
color: args.color,
|
|
237
|
+
archived: typeof args.archived === 'boolean' ? args.archived : undefined,
|
|
238
|
+
});
|
|
239
|
+
return renderLabelSaved(res.label);
|
|
240
|
+
}
|
|
241
|
+
if (name === 'workover_support_merge_labels')
|
|
242
|
+
return renderLabelMerged(await mergeLabels(call, { workspace, into: args.into, from: args.from }));
|
|
243
|
+
throw apiError(400, `Unknown tool: ${name}`);
|
|
244
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// Walter AI's outcome ledger from a terminal: `workover support outcomes ...` and the MCP server's
|
|
2
|
+
// `workover_support_outcomes*` tools (WO-1752, S65).
|
|
3
|
+
//
|
|
4
|
+
// THE SAME FILE ships in @workover/cli (apps/cli/support-outcomes.mjs) and @workover/mcp
|
|
5
|
+
// (apps/mcp/support-outcomes.mjs), because the two packages are published separately and neither
|
|
6
|
+
// may depend on the other. `apps/mcp/support-outcomes.test.mjs` fails when the copies differ.
|
|
7
|
+
//
|
|
8
|
+
// Every conversation Walter AI took gets one outcome, recomputed as the conversation changes:
|
|
9
|
+
// confirmed (the visitor said it helped), assumed (quiet after an answer, never counted as
|
|
10
|
+
// confirmed), handed_off, corrected (a teammate stepped in after Walter answered) or abandoned
|
|
11
|
+
// (a miss, then silence). An owner or admin can mark one not_resolved with a reason; the mark is
|
|
12
|
+
// audited and the totals move. Marking the same way twice changes nothing (`changed: false`).
|
|
13
|
+
// Usage is this month's answered conversations against the fair-use cap (owners and admins).
|
|
14
|
+
//
|
|
15
|
+
// `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
|
|
16
|
+
// whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
|
|
17
|
+
// return lines, for a terminal or an MCP text result alike.
|
|
18
|
+
|
|
19
|
+
import { apiError, resolveWorkspace } from './site-setup.mjs';
|
|
20
|
+
|
|
21
|
+
export const OUTCOME_KEYS = ['confirmed', 'assumed', 'handed_off', 'corrected', 'abandoned', 'pending', 'not_resolved'];
|
|
22
|
+
/** The CSV holds at most this many rows, as the api's own export does. */
|
|
23
|
+
export const MAX_CSV_ROWS = 10000;
|
|
24
|
+
const PAGE = 200;
|
|
25
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
26
|
+
|
|
27
|
+
/** The Messenger the ledger belongs to: Support has to exist first. */
|
|
28
|
+
async function messengerOf(call, workspace) {
|
|
29
|
+
const ws = await resolveWorkspace(call, workspace);
|
|
30
|
+
const status = await call(`/messenger/agent-setup?organizationId=${encodeURIComponent(ws.id)}`);
|
|
31
|
+
const id = status?.messenger?.id;
|
|
32
|
+
if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
|
|
33
|
+
return { ws, messengerId: id };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const base = (messengerId) => `/messenger/${messengerId}/walter`;
|
|
37
|
+
|
|
38
|
+
/** The list's query string from the filters, checked before any request. */
|
|
39
|
+
export function outcomeQuery({ outcome, from, to, cursor, limit } = {}) {
|
|
40
|
+
const p = new URLSearchParams();
|
|
41
|
+
if (outcome !== undefined && outcome !== null && outcome !== '') {
|
|
42
|
+
if (!OUTCOME_KEYS.includes(outcome)) throw apiError(400, `--outcome is one of ${OUTCOME_KEYS.join(', ')}.`);
|
|
43
|
+
p.set('outcome', outcome);
|
|
44
|
+
}
|
|
45
|
+
for (const [k, v] of [['from', from], ['to', to]]) {
|
|
46
|
+
if (v === undefined || v === null || v === '') continue;
|
|
47
|
+
if (!DATE.test(String(v))) throw apiError(400, `--${k} is a date like 2026-11-01.`);
|
|
48
|
+
p.set(k, String(v));
|
|
49
|
+
}
|
|
50
|
+
if (cursor) p.set('cursor', String(cursor));
|
|
51
|
+
if (limit) p.set('limit', String(limit));
|
|
52
|
+
const s = p.toString();
|
|
53
|
+
return s ? `?${s}` : '';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** One page of the ledger (or every page with `all`, up to MAX_CSV_ROWS rows). */
|
|
57
|
+
export async function listOutcomes(call, { workspace, outcome, from, to, cursor, limit, all = false } = {}) {
|
|
58
|
+
const q = { outcome, from, to };
|
|
59
|
+
outcomeQuery(q);
|
|
60
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
61
|
+
const first = await call(`${base(messengerId)}/outcomes${outcomeQuery({ ...q, cursor, limit: all ? PAGE : limit })}`);
|
|
62
|
+
if (!all) return { workspace: ws, ...first, truncated: false };
|
|
63
|
+
const rows = [...(first.rows ?? [])];
|
|
64
|
+
let next = first.nextCursor;
|
|
65
|
+
while (next && rows.length < MAX_CSV_ROWS) {
|
|
66
|
+
const page = await call(`${base(messengerId)}/outcomes${outcomeQuery({ ...q, cursor: next, limit: PAGE })}`);
|
|
67
|
+
rows.push(...(page.rows ?? []));
|
|
68
|
+
next = page.nextCursor;
|
|
69
|
+
}
|
|
70
|
+
const truncated = rows.length > MAX_CSV_ROWS || Boolean(next);
|
|
71
|
+
return { workspace: ws, ...first, rows: rows.slice(0, MAX_CSV_ROWS), nextCursor: null, truncated };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Mark a conversation not resolved, with the reason. Owners and admins. */
|
|
75
|
+
export async function markOutcome(call, { workspace, conversation, reason } = {}) {
|
|
76
|
+
if (conversation === undefined || conversation === null || String(conversation).trim() === '')
|
|
77
|
+
throw apiError(400, 'Name the conversation, by its id or public id.');
|
|
78
|
+
const why = typeof reason === 'string' ? reason.trim() : '';
|
|
79
|
+
if (why.length < 3) throw apiError(400, 'Give a reason (at least 3 characters).');
|
|
80
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
81
|
+
const path = `${base(messengerId)}/outcomes/${encodeURIComponent(String(conversation).trim())}/override`;
|
|
82
|
+
return { workspace: ws, ...(await call(path, { method: 'PUT', body: { outcome: 'not_resolved', reason: why } })) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Clear a not-resolved mark: the computed outcome counts again. Owners and admins. */
|
|
86
|
+
export async function clearOutcome(call, { workspace, conversation } = {}) {
|
|
87
|
+
if (conversation === undefined || conversation === null || String(conversation).trim() === '')
|
|
88
|
+
throw apiError(400, 'Name the conversation, by its id or public id.');
|
|
89
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
90
|
+
const path = `${base(messengerId)}/outcomes/${encodeURIComponent(String(conversation).trim())}/override`;
|
|
91
|
+
return { workspace: ws, ...(await call(path, { method: 'DELETE' })) };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** This month's usage against the fair-use cap. Owners and admins. */
|
|
95
|
+
export async function getOutcomeUsage(call, { workspace } = {}) {
|
|
96
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
97
|
+
return { workspace: ws, ...(await call(`${base(messengerId)}/usage`)) };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ------------------------------------------------------------------ CSV
|
|
101
|
+
|
|
102
|
+
const FORMULA = /^[\s]*[=+\-@\t\r]/;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* One CSV cell. Text a visitor wrote (a name, a subject) that starts like a formula is prefixed
|
|
106
|
+
* with a single quote, so a spreadsheet shows it as text; a cell with a comma, quote or line break
|
|
107
|
+
* is quoted. The same rules as the api's export (views/csv.ts).
|
|
108
|
+
*/
|
|
109
|
+
export function csvCell(v) {
|
|
110
|
+
if (v === null || v === undefined) return '';
|
|
111
|
+
let s = typeof v === 'string' ? v : String(v);
|
|
112
|
+
if (typeof v === 'string' && FORMULA.test(s)) s = `'${s}`;
|
|
113
|
+
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const CSV_HEADER = [
|
|
117
|
+
'Conversation',
|
|
118
|
+
'Subject',
|
|
119
|
+
'Visitor',
|
|
120
|
+
'Email',
|
|
121
|
+
'Outcome',
|
|
122
|
+
'Computed outcome',
|
|
123
|
+
'Why',
|
|
124
|
+
'Handoff reason',
|
|
125
|
+
'Walter answers',
|
|
126
|
+
'Started',
|
|
127
|
+
'First answer',
|
|
128
|
+
'Last answer',
|
|
129
|
+
'Not resolved reason',
|
|
130
|
+
'Marked by',
|
|
131
|
+
'Marked at',
|
|
132
|
+
];
|
|
133
|
+
|
|
134
|
+
/** The ledger's rows as CSV, CRLF line ends, with a byte order mark so Excel reads UTF-8. */
|
|
135
|
+
export function outcomesCsv(rows) {
|
|
136
|
+
const line = (cells) => cells.map(csvCell).join(',');
|
|
137
|
+
const body = (rows ?? []).map((r) =>
|
|
138
|
+
line([
|
|
139
|
+
r.conversationPublicId,
|
|
140
|
+
r.title,
|
|
141
|
+
r.visitor?.name,
|
|
142
|
+
r.visitor?.email,
|
|
143
|
+
r.outcome,
|
|
144
|
+
r.computed,
|
|
145
|
+
r.why,
|
|
146
|
+
r.handoffReason,
|
|
147
|
+
r.answers,
|
|
148
|
+
r.startedAt,
|
|
149
|
+
r.firstAnswerAt,
|
|
150
|
+
r.lastAnswerAt,
|
|
151
|
+
r.override?.reason,
|
|
152
|
+
r.override?.byName,
|
|
153
|
+
r.override?.at,
|
|
154
|
+
]),
|
|
155
|
+
);
|
|
156
|
+
return String.fromCharCode(0xfeff) + [line(CSV_HEADER), ...body].join('\r\n') + '\r\n';
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ------------------------------------------------------------------ rendering
|
|
160
|
+
|
|
161
|
+
const pct = (r) => (r === null || r === undefined ? 'n/a' : `${Math.round(r * 100)}%`);
|
|
162
|
+
const LABEL = {
|
|
163
|
+
confirmed: 'Confirmed',
|
|
164
|
+
assumed: 'Assumed',
|
|
165
|
+
handed_off: 'Handed off',
|
|
166
|
+
corrected: 'Corrected',
|
|
167
|
+
abandoned: 'Abandoned',
|
|
168
|
+
pending: 'In progress',
|
|
169
|
+
not_resolved: 'Not resolved',
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
export function renderOutcomes(res) {
|
|
173
|
+
const t = res.totals ?? {};
|
|
174
|
+
const c = t.counts ?? {};
|
|
175
|
+
const out = ['', ` Walter AI outcomes in ${res.workspace?.name ?? 'this workspace'}`, ''];
|
|
176
|
+
out.push(
|
|
177
|
+
` ${t.total ?? 0} conversations: confirmed ${pct(t.confirmedRate)}, resolved ${pct(t.resolutionRate)} (${t.resolved ?? 0})`,
|
|
178
|
+
);
|
|
179
|
+
out.push(
|
|
180
|
+
` ${OUTCOME_KEYS.filter((k) => k !== 'pending')
|
|
181
|
+
.map((k) => `${LABEL[k]} ${c[k] ?? 0}`)
|
|
182
|
+
.join(' · ')}${t.pending ? ` · ${t.pending} in progress` : ''}`,
|
|
183
|
+
);
|
|
184
|
+
const f = res.filter ?? {};
|
|
185
|
+
if (f.outcome || f.from || f.to)
|
|
186
|
+
out.push(` Filter: ${[f.outcome && LABEL[f.outcome], f.from && `from ${f.from}`, f.to && `to ${f.to}`].filter(Boolean).join(', ')}`);
|
|
187
|
+
out.push('');
|
|
188
|
+
const rows = res.rows ?? [];
|
|
189
|
+
if (!rows.length) out.push(' No conversations match.');
|
|
190
|
+
for (const r of rows) {
|
|
191
|
+
const who = r.visitor?.name || r.visitor?.email || 'Visitor';
|
|
192
|
+
const marked = r.override ? ` (marked: ${r.override.reason ?? 'no reason'})` : '';
|
|
193
|
+
out.push(` ${String(r.startedAt ?? '').slice(0, 10)} ${LABEL[r.outcome] ?? r.outcome}${marked}`);
|
|
194
|
+
out.push(` ${r.title || 'Untitled'} · ${who} · ${r.conversationPublicId}`);
|
|
195
|
+
out.push(` ${r.why}`);
|
|
196
|
+
}
|
|
197
|
+
if (res.nextCursor) out.push('', ` More: pass --cursor ${res.nextCursor}`);
|
|
198
|
+
out.push('');
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function renderOutcomeMark(res) {
|
|
203
|
+
const r = res.row ?? {};
|
|
204
|
+
const state = r.override ? `marked not resolved: ${r.override.reason}` : `back to ${LABEL[r.computed] ?? r.computed}`;
|
|
205
|
+
return [
|
|
206
|
+
'',
|
|
207
|
+
` ${res.changed ? '✓' : '='} ${r.title || r.conversationPublicId}: ${state}${res.changed ? '' : ' (no change)'}`,
|
|
208
|
+
` Resolved now ${pct(res.totals?.resolutionRate)}, confirmed ${pct(res.totals?.confirmedRate)}`,
|
|
209
|
+
'',
|
|
210
|
+
];
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function renderOutcomeUsage(res) {
|
|
214
|
+
return [
|
|
215
|
+
'',
|
|
216
|
+
` Walter AI usage in ${res.workspace?.name ?? 'this workspace'}, ${res.month}`,
|
|
217
|
+
` ${res.conversations} of ${res.cap} conversations (${pct(res.share)}), ${res.answers} answers · ${res.state}`,
|
|
218
|
+
` ${res.line}`,
|
|
219
|
+
// B1: a Walter that is not answering says so here too, with what to do.
|
|
220
|
+
...(res.paused ? [` ✗ ${res.paused.line}`] : []),
|
|
221
|
+
'',
|
|
222
|
+
];
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ------------------------------------------------------------------ MCP tool definitions
|
|
226
|
+
|
|
227
|
+
const WORKSPACE = {
|
|
228
|
+
type: ['string', 'number'],
|
|
229
|
+
description: 'The workspace, by slug or id. Needed only when the account has more than one.',
|
|
230
|
+
};
|
|
231
|
+
const SCOPE =
|
|
232
|
+
' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
|
|
233
|
+
|
|
234
|
+
/** The MCP server's outcome ledger tools, listed with the other Support tools (index.mjs). */
|
|
235
|
+
export const OUTCOME_TOOL_DEFS = [
|
|
236
|
+
{
|
|
237
|
+
name: 'workover_support_outcomes',
|
|
238
|
+
description:
|
|
239
|
+
"What became of each conversation Walter AI (Support's AI agent) took, newest first: confirmed (the visitor said it helped), assumed (quiet after an answer; never counted as confirmed), handed_off, corrected (a teammate stepped in after Walter answered), abandoned (a miss, then silence), pending, or not_resolved when an admin marked it. Includes the totals with the confirmed and resolution rates. Pass `csv: true` for every matching row as CSV (up to 10,000). Members can read it." +
|
|
240
|
+
SCOPE,
|
|
241
|
+
inputSchema: {
|
|
242
|
+
type: 'object',
|
|
243
|
+
properties: {
|
|
244
|
+
workspace: WORKSPACE,
|
|
245
|
+
outcome: { type: 'string', enum: OUTCOME_KEYS, description: 'Only conversations with this outcome.' },
|
|
246
|
+
from: { type: 'string', description: 'Started on or after this date, YYYY-MM-DD.' },
|
|
247
|
+
to: { type: 'string', description: 'Started on or before this date, YYYY-MM-DD.' },
|
|
248
|
+
cursor: { type: 'string', description: 'The `More:` cursor from the previous page.' },
|
|
249
|
+
csv: { type: 'boolean', description: 'Answer every matching row as CSV instead of one page as text.' },
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
},
|
|
253
|
+
{
|
|
254
|
+
name: 'workover_support_outcome_mark',
|
|
255
|
+
description:
|
|
256
|
+
'Mark a conversation Walter AI took as not resolved, with a reason, or clear the mark (`clear: true`). The computed outcome is kept beside the mark, the totals move, and the change is audited. Safe to repeat: the same mark again changes nothing. Owners and admins.' +
|
|
257
|
+
SCOPE,
|
|
258
|
+
inputSchema: {
|
|
259
|
+
type: 'object',
|
|
260
|
+
required: ['conversation'],
|
|
261
|
+
properties: {
|
|
262
|
+
workspace: WORKSPACE,
|
|
263
|
+
conversation: { type: ['string', 'number'], description: 'The conversation, by id or public id.' },
|
|
264
|
+
reason: { type: 'string', description: 'Why it was not resolved (3 to 500 characters). Needed unless clearing.' },
|
|
265
|
+
clear: { type: 'boolean', description: 'Remove the mark instead.' },
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
{
|
|
270
|
+
name: 'workover_support_outcome_usage',
|
|
271
|
+
description:
|
|
272
|
+
"This calendar month (UTC): the conversations Walter AI answered across the workspace, its answers, the fair-use cap and the share used (ok, near or over). Walter is included with Support; nothing is billed per answer. Owners and admins." +
|
|
273
|
+
SCOPE,
|
|
274
|
+
inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
|
|
275
|
+
},
|
|
276
|
+
];
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Support's outside bot from a terminal: `workover support outside-bot ...` and the MCP server's
|
|
2
|
+
// `workover_support_*outside_bot*` tools (WO-1752, S14).
|
|
3
|
+
//
|
|
4
|
+
// THE SAME FILE ships in @workover/cli (apps/cli/support-outside-bot.mjs) and @workover/mcp
|
|
5
|
+
// (apps/mcp/support-outside-bot.mjs), because the two packages are published separately and neither
|
|
6
|
+
// may depend on the other. `apps/mcp/support-outside-bot.test.mjs` fails when the copies differ.
|
|
7
|
+
//
|
|
8
|
+
// An outside bot (RunCloud's RC Brain, or any bot that speaks its API) answers the Messenger's
|
|
9
|
+
// visitors first and hands a conversation to the team when it cannot help. Every call goes to a
|
|
10
|
+
// route opened to tokens holding the `support` scope (`workover login --support`). Setting is safe
|
|
11
|
+
// to repeat: the API answers the whole state. The key is sent once and never shown again; the
|
|
12
|
+
// answers only say whether one is set. The check asks the bot one test question and reports what
|
|
13
|
+
// came back, which is how an agent confirms the setup worked.
|
|
14
|
+
//
|
|
15
|
+
// `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
|
|
16
|
+
// whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
|
|
17
|
+
// return lines, for a terminal or an MCP text result alike.
|
|
18
|
+
|
|
19
|
+
import { apiError, resolveWorkspace } from './site-setup.mjs';
|
|
20
|
+
|
|
21
|
+
const FIELDS = ['enabled', 'url', 'keyHeader', 'persona', 'name', 'when', 'minConfidence', 'perMinute', 'burst'];
|
|
22
|
+
|
|
23
|
+
/** The Messenger the bot answers on: Support has to exist first. */
|
|
24
|
+
async function messengerOf(call, workspace) {
|
|
25
|
+
const ws = await resolveWorkspace(call, workspace);
|
|
26
|
+
const status = await call(`/messenger/agent-setup?organizationId=${encodeURIComponent(ws.id)}`);
|
|
27
|
+
const id = status?.messenger?.id;
|
|
28
|
+
if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
|
|
29
|
+
return { ws, messengerId: id };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const base = (messengerId) => `/messenger/${messengerId}/outside-bot`;
|
|
33
|
+
|
|
34
|
+
/** The bot's settings, whether a key is set, and its last day of turns. */
|
|
35
|
+
export async function getOutsideBot(call, { workspace } = {}) {
|
|
36
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
37
|
+
return { workspace: ws, ...(await call(base(messengerId))) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Change some of the bot's settings; `key` sets a new key, `key: null` removes it. */
|
|
41
|
+
export async function setOutsideBot(call, { workspace, key, ...rest } = {}) {
|
|
42
|
+
const body = {};
|
|
43
|
+
for (const f of FIELDS) if (rest[f] !== undefined) body[f] = rest[f];
|
|
44
|
+
if (key === null) body.key = null;
|
|
45
|
+
else if (typeof key === 'string') {
|
|
46
|
+
if (!key.trim()) throw apiError(400, 'The key is empty.');
|
|
47
|
+
body.key = key.trim();
|
|
48
|
+
}
|
|
49
|
+
if (!Object.keys(body).length) throw apiError(400, 'Nothing to change: pass at least one setting.');
|
|
50
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
51
|
+
return { workspace: ws, ...(await call(base(messengerId), { method: 'PUT', body })) };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** One test question to the saved bot; nothing is posted anywhere. */
|
|
55
|
+
export async function checkOutsideBot(call, { workspace } = {}) {
|
|
56
|
+
const { ws, messengerId } = await messengerOf(call, workspace);
|
|
57
|
+
return { workspace: ws, ...(await call(`${base(messengerId)}/check`, { method: 'POST', body: {} })) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// ------------------------------------------------------------------ rendering
|
|
61
|
+
|
|
62
|
+
export function renderOutsideBot(res) {
|
|
63
|
+
const state = res.ready ? 'on' : res.enabled ? 'on, but missing its address or key' : 'off';
|
|
64
|
+
const out = ['', ` Outside bot in ${res.workspace?.name ?? 'this workspace'}: ${state}`, ''];
|
|
65
|
+
out.push(` Address ${res.url ?? 'not set'}`);
|
|
66
|
+
out.push(` Key ${res.keySet ? `set (sent as ${res.keyHeader})` : 'not set'}`);
|
|
67
|
+
out.push(` Name ${res.name} persona ${res.persona}`);
|
|
68
|
+
out.push(` Answers ${res.when === 'away' ? 'outside office hours only' : 'every conversation'}`);
|
|
69
|
+
if (res.minConfidence > 0) out.push(` Minimum ${Math.round(res.minConfidence * 100)}% sure, or a person takes it`);
|
|
70
|
+
out.push(` Rate ${res.perMinute} a minute, bursts of ${res.burst}`);
|
|
71
|
+
const d = res.last24h;
|
|
72
|
+
if (d) out.push('', ` Last 24 hours: ${d.answered} answered, ${d.handed} handed to the team, ${d.dropped} dropped`);
|
|
73
|
+
out.push('');
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function renderOutsideBotCheck(res) {
|
|
78
|
+
if (res.ok)
|
|
79
|
+
return [
|
|
80
|
+
'',
|
|
81
|
+
` ✓ The bot answered in ${res.latencyMs} ms${res.confidence != null ? ` (${Math.round(res.confidence * 100)}% sure)` : ''}:`,
|
|
82
|
+
` ${res.answer}`,
|
|
83
|
+
...(res.wouldHandOff ? ['', ' That answer would go to the team, not the visitor (a handoff, or under the minimum).'] : []),
|
|
84
|
+
'',
|
|
85
|
+
];
|
|
86
|
+
const why = {
|
|
87
|
+
not_ready: 'Give the bot an address and a key first.',
|
|
88
|
+
waiting: 'The bot is at its rate limit. Try again in a minute.',
|
|
89
|
+
timeout: 'The bot did not answer in time.',
|
|
90
|
+
unreachable: 'The bot could not be reached.',
|
|
91
|
+
unreadable: 'The bot answered, but not with an answer Support can read.',
|
|
92
|
+
limited: 'The bot asked us to slow down (429).',
|
|
93
|
+
key_unreadable: 'The saved key could not be read. Set it again.',
|
|
94
|
+
}[res.result];
|
|
95
|
+
return ['', ` ✗ ${why ?? `The bot answered ${res.status ?? res.result}.`}`, ''];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ------------------------------------------------------------------ MCP tool definitions
|
|
99
|
+
|
|
100
|
+
const WORKSPACE = {
|
|
101
|
+
type: ['string', 'number'],
|
|
102
|
+
description: 'The workspace, by slug or id. Needed only when the account has more than one.',
|
|
103
|
+
};
|
|
104
|
+
const SCOPE =
|
|
105
|
+
' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
|
|
106
|
+
|
|
107
|
+
/** The MCP server's outside bot tools, listed with the other Support tools (index.mjs). */
|
|
108
|
+
export const OUTSIDE_BOT_TOOL_DEFS = [
|
|
109
|
+
{
|
|
110
|
+
name: 'workover_support_outside_bot',
|
|
111
|
+
description:
|
|
112
|
+
"Support's outside bot: a bot such as RunCloud's RC Brain that answers the Messenger's visitors first and hands a conversation to the team when it cannot help. Shows its address, whether a key is set (never the key), its name, persona, when it answers, its minimum score, its rate limit and its last day of turns." +
|
|
113
|
+
SCOPE,
|
|
114
|
+
inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
|
|
115
|
+
},
|
|
116
|
+
{
|
|
117
|
+
name: 'workover_support_set_outside_bot',
|
|
118
|
+
description:
|
|
119
|
+
"Set up or change Support's outside bot. Pass only what changes. It answers `POST <url>/chat` with the key in `keyHeader` (X-Brain-Key by default); it switches on only with an address and a key. Changing `url` needs `key` again in the same call. Safe to repeat. Owners and admins. Run workover_support_check_outside_bot afterwards to confirm it answers." +
|
|
120
|
+
SCOPE,
|
|
121
|
+
inputSchema: {
|
|
122
|
+
type: 'object',
|
|
123
|
+
properties: {
|
|
124
|
+
workspace: WORKSPACE,
|
|
125
|
+
enabled: { type: 'boolean', description: 'On or off.' },
|
|
126
|
+
url: { type: 'string', description: 'The bot’s https base address on a public host, such as https://brain.example.com.' },
|
|
127
|
+
key: { type: ['string', 'null'], description: 'The bot’s key. Stored sealed and never shown again; null removes it.' },
|
|
128
|
+
keyHeader: { type: 'string', description: 'The header the key is sent in. X-Brain-Key by default.' },
|
|
129
|
+
persona: { type: 'string', enum: ['presale', 'support', 'onboarding'] },
|
|
130
|
+
name: { type: 'string', description: 'The name visitors see on its answers.' },
|
|
131
|
+
when: { type: 'string', enum: ['always', 'away'], description: 'away: only outside office hours.' },
|
|
132
|
+
minConfidence: { type: 'number', description: 'Below this score (0 to 1) an answer goes to a person. 0 sends every answer.' },
|
|
133
|
+
perMinute: { type: 'integer', description: 'Calls a minute to the bot’s host. 100 by default.' },
|
|
134
|
+
burst: { type: 'integer', description: 'How many of those may go at once. 20 by default.' },
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
name: 'workover_support_check_outside_bot',
|
|
140
|
+
description:
|
|
141
|
+
'Ask the saved outside bot one test question and report what came back: answered, timed out, unreachable or an HTTP status, with the time it took. Nothing is posted to any conversation. Owners and admins.' +
|
|
142
|
+
SCOPE,
|
|
143
|
+
inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
|
|
144
|
+
},
|
|
145
|
+
];
|