@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.
@@ -0,0 +1,313 @@
1
+ // Support's reply targets, auto-assignment and availability from a terminal: `workover support
2
+ // sla | assignment | away` and the MCP server's `workover_support_sla`, `workover_support_assignment`
3
+ // and `workover_support_availability` tools (WO-1752, S08).
4
+ //
5
+ // THE SAME FILE ships in @workover/cli (apps/cli/support-inbox.mjs) and @workover/mcp
6
+ // (apps/mcp/support-inbox.mjs), because the two packages are published separately and neither may
7
+ // depend on the other. `apps/mcp/support-inbox.test.mjs` fails when the copies differ.
8
+ //
9
+ // Every call goes to a route opened to tokens holding the `support` scope (`workover login
10
+ // --support`). Reading changes nothing; each write sends only what was given, the same values again
11
+ // answer `changed: []` (or `changed: false` for away), and the answer is the whole new state, so an
12
+ // agent can check what it set. Changing targets or assignment needs a workspace owner or admin;
13
+ // anyone on the team sets their own away.
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 AUTO_ASSIGN = ['off', 'load', 'round_robin'];
22
+
23
+ /** The Messenger whose rules 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
+ const rulesPath = (id) => `/messenger/${id}/inbox-rules`;
33
+ const waitsPath = (id) => `/messenger/${id}/inbox-rules/waits`;
34
+ const awayPath = (id) => `/messenger/${id}/availability`;
35
+
36
+ /** `"none"`, `null` or `""` clear a target; otherwise whole minutes. Undefined leaves it. */
37
+ export function targetOf(raw, name) {
38
+ if (raw === undefined) return undefined;
39
+ if (raw === null || raw === '' || String(raw).toLowerCase() === 'none') return null;
40
+ const n = Number(raw);
41
+ if (!Number.isInteger(n) || n < 1 || n > 43_200)
42
+ throw apiError(400, `${name} is whole business minutes from 1 to 43200, or "none".`);
43
+ return n;
44
+ }
45
+
46
+ /** `on`/`off`/true/false; undefined leaves it. */
47
+ export function switchOf(raw, name) {
48
+ if (raw === undefined) return undefined;
49
+ if (raw === true || raw === 'on' || raw === 'true') return true;
50
+ if (raw === false || raw === 'off' || raw === 'false') return false;
51
+ throw apiError(400, `${name} is on or off.`);
52
+ }
53
+
54
+ function listOf(raw) {
55
+ if (raw === undefined) return undefined;
56
+ if (Array.isArray(raw)) return raw;
57
+ return String(raw)
58
+ .split(',')
59
+ .map((s) => s.trim())
60
+ .filter(Boolean);
61
+ }
62
+
63
+ /**
64
+ * The reply targets: read them (and the conversations waiting against them), or set what is given.
65
+ * `holidays` replaces the list (YYYY-MM-DD days); `tiers` replaces the tiers
66
+ * ([{ name, label, first, next }]).
67
+ */
68
+ export async function supportSla(call, { workspace, firstTarget, nextTarget, holidays, tiers, breachWarnings } = {}) {
69
+ const body = {};
70
+ const first = targetOf(firstTarget, 'firstTarget');
71
+ const next = targetOf(nextTarget, 'nextTarget');
72
+ if (first !== undefined) body.firstTarget = first;
73
+ if (next !== undefined) body.nextTarget = next;
74
+ const days = listOf(holidays);
75
+ if (days !== undefined) body.holidays = days;
76
+ if (tiers !== undefined) {
77
+ let t = tiers;
78
+ if (typeof t === 'string') {
79
+ try {
80
+ t = JSON.parse(t);
81
+ } catch {
82
+ throw apiError(400, 'tiers is JSON: [{"name":"VIP","label":"VIP","first":15,"next":null}].');
83
+ }
84
+ }
85
+ if (!Array.isArray(t)) throw apiError(400, 'tiers is a list: [{"name":"VIP","label":"VIP","first":15,"next":null}].');
86
+ body.tiers = t;
87
+ }
88
+ const warn = switchOf(breachWarnings, 'breachWarnings');
89
+ if (warn !== undefined) body.breachWarnings = warn;
90
+ const { ws, messengerId } = await messengerOf(call, workspace);
91
+ const rules = Object.keys(body).length
92
+ ? await call(rulesPath(messengerId), { method: 'PUT', body })
93
+ : await call(rulesPath(messengerId));
94
+ const waits = await call(waitsPath(messengerId));
95
+ return { workspace: ws, rules, waits, wrote: Object.keys(body).length > 0 };
96
+ }
97
+
98
+ /** Auto-assignment: read it, or set the mode, the capacity per person and who takes part. */
99
+ export async function supportAssignment(call, { workspace, autoAssign, capacity, pool, claimOnWrite } = {}) {
100
+ const body = {};
101
+ const claim = switchOf(claimOnWrite, 'claimOnWrite');
102
+ if (claim !== undefined) body.claimOnWrite = claim;
103
+ if (autoAssign !== undefined) {
104
+ const mode = String(autoAssign).trim().toLowerCase().replace('-', '_');
105
+ if (!AUTO_ASSIGN.includes(mode)) throw apiError(400, `autoAssign is ${AUTO_ASSIGN.join(', ')}.`);
106
+ body.autoAssign = mode;
107
+ }
108
+ if (capacity !== undefined) {
109
+ const n = Number(capacity);
110
+ if (!Number.isInteger(n) || n < 1 || n > 100) throw apiError(400, 'capacity is a whole number from 1 to 100.');
111
+ body.capacity = n;
112
+ }
113
+ if (pool !== undefined) {
114
+ const ids = String(pool).toLowerCase() === 'everyone' ? [] : listOf(pool).map(Number);
115
+ if (ids.some((n) => !Number.isInteger(n) || n <= 0))
116
+ throw apiError(400, 'pool is user ids (`workover support assignment` lists them), or "everyone".');
117
+ body.pool = ids;
118
+ }
119
+ const { ws, messengerId } = await messengerOf(call, workspace);
120
+ const rules = Object.keys(body).length
121
+ ? await call(rulesPath(messengerId), { method: 'PUT', body })
122
+ : await call(rulesPath(messengerId));
123
+ const availability = await call(awayPath(messengerId));
124
+ return { workspace: ws, rules, availability, wrote: Object.keys(body).length > 0 };
125
+ }
126
+
127
+ /** Your own availability: read it (and the team's), or set yourself away or back. */
128
+ export async function supportAvailability(call, { workspace, away } = {}) {
129
+ const value = switchOf(away, 'away');
130
+ const { ws, messengerId } = await messengerOf(call, workspace);
131
+ const availability =
132
+ value === undefined
133
+ ? await call(awayPath(messengerId))
134
+ : await call(awayPath(messengerId), { method: 'POST', body: { away: value } });
135
+ return { workspace: ws, availability, wrote: value !== undefined };
136
+ }
137
+
138
+ // ------------------------------------------------------------------ rendering
139
+
140
+ const mins = (n) => (n == null ? 'none' : `${n} business ${n === 1 ? 'minute' : 'minutes'}`);
141
+ const MODE = { off: 'off', load: 'balanced by load', round_robin: 'round robin' };
142
+
143
+ function changedLine(res) {
144
+ const changed = res.rules?.changed;
145
+ if (!res.wrote) return [];
146
+ return changed?.length ? [` ✓ Saved: ${changed.join(', ')}.`] : [' ✓ Already set that way; nothing changed.'];
147
+ }
148
+
149
+ export function renderSla(res) {
150
+ const r = res.rules;
151
+ const out = ['', ` Reply targets in ${res.workspace?.name ?? 'this workspace'}`, ...changedLine(res), ''];
152
+ out.push(` First reply ${mins(r.firstTarget)}`);
153
+ out.push(` Next reply ${mins(r.nextTarget)}`);
154
+ out.push(` Warnings ${r.breachWarnings ? 'on: the assignee is told once as a target comes due' : 'off'}`);
155
+ // The api answers the office hours as { tz, days }, or null when there are none.
156
+ out.push(` Office hours ${r.hours?.tz ? `${r.hours.tz}, set in Support settings > Office hours` : 'none: every minute counts'}`);
157
+ out.push(` Holidays ${r.holidays?.length ? r.holidays.join(', ') : 'none'}`);
158
+ if (r.tiers?.length) {
159
+ out.push(' Tiers');
160
+ for (const t of r.tiers) out.push(` ${t.name} (label ${t.label}): first ${mins(t.first)}, next ${mins(t.next)}`);
161
+ }
162
+ const w = res.waits;
163
+ if (w?.on) {
164
+ const overdue = w.waits.filter((x) => x.state === 'overdue').length;
165
+ const soon = w.waits.filter((x) => x.state === 'due_soon').length;
166
+ out.push('', ` Waiting now: ${w.waits.length} (${overdue} overdue, ${soon} due soon).`);
167
+ }
168
+ out.push('');
169
+ return out;
170
+ }
171
+
172
+ function teamLines(availability) {
173
+ return (availability?.team ?? []).map((t) => {
174
+ const state = t.away ? 'away' : t.online ? 'online' : 'offline';
175
+ const you = t.userId === availability.you?.userId ? ' (you)' : '';
176
+ return ` #${t.userId}${you} ${state} · ${t.open} open`;
177
+ });
178
+ }
179
+
180
+ export function renderAssignment(res) {
181
+ const r = res.rules;
182
+ const out = ['', ` Auto-assignment in ${res.workspace?.name ?? 'this workspace'}`, ...changedLine(res), ''];
183
+ out.push(` Claim ${r.claimOnWrite === false ? 'off: replying leaves it unassigned' : 'on: whoever replies or notes first takes it'}`);
184
+ out.push(` Mode ${MODE[r.autoAssign] ?? r.autoAssign}`);
185
+ out.push(` Capacity ${r.capacity} open per person`);
186
+ out.push(` Who ${r.pool?.length ? r.pool.map((id) => `#${id}`).join(', ') : 'everyone on the team'}`);
187
+ out.push(' Team', ...teamLines(res.availability), '');
188
+ return out;
189
+ }
190
+
191
+ export function renderAvailability(res) {
192
+ const a = res.availability;
193
+ const head = res.wrote
194
+ ? a.changed
195
+ ? ` ✓ You are now ${a.you.away ? 'away' : 'available'}.`
196
+ : ` ✓ You were already ${a.you.away ? 'away' : 'available'}; nothing changed.`
197
+ : ` You are ${a.you.away ? 'away' : 'available'}.`;
198
+ const note = a.you.away ? [' New conversations are not assigned to you.'] : [];
199
+ return ['', head, ...note, '', ' Team', ...teamLines(a), ''];
200
+ }
201
+
202
+ // ------------------------------------------------------------------ MCP tools
203
+
204
+ const WORKSPACE = {
205
+ type: ['string', 'number'],
206
+ description: 'The workspace, by slug or id. Needed only when the account has more than one.',
207
+ };
208
+ const SCOPE =
209
+ ' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
210
+ const MINUTES = {
211
+ type: ['number', 'null'],
212
+ description: 'Whole business minutes (only office hours count, holidays skipped); null for no target.',
213
+ };
214
+
215
+ /** The MCP server's inbox-rules tools, listed with the other Support tools (index.mjs). */
216
+ export const INBOX_TOOL_DEFS = [
217
+ {
218
+ name: 'workover_support_sla',
219
+ description:
220
+ "Support's reply targets: first and next reply in business minutes, tiers that tighten them for a label (VIP), holidays, and whether the assignee is warned once as a target comes due. With no other argument it reads them and counts the conversations overdue and due soon; anything given is set (owners and admins), and the same values again change nothing." +
221
+ SCOPE,
222
+ inputSchema: {
223
+ type: 'object',
224
+ properties: {
225
+ workspace: WORKSPACE,
226
+ firstTarget: MINUTES,
227
+ nextTarget: MINUTES,
228
+ holidays: { type: 'array', items: { type: 'string' }, description: 'Replaces the holidays: YYYY-MM-DD days.' },
229
+ tiers: {
230
+ type: 'array',
231
+ description: 'Replaces the tiers. A conversation with the label (or a child label) waits against the tier; the tightest wins.',
232
+ items: {
233
+ type: 'object',
234
+ properties: {
235
+ name: { type: 'string' },
236
+ label: { type: 'string' },
237
+ first: MINUTES,
238
+ next: MINUTES,
239
+ },
240
+ required: ['name', 'label'],
241
+ },
242
+ },
243
+ breachWarnings: { type: 'boolean', description: 'Warn the assignee (or the owners and admins) once per wait.' },
244
+ },
245
+ additionalProperties: false,
246
+ },
247
+ },
248
+ {
249
+ name: 'workover_support_assignment',
250
+ description:
251
+ 'Claim on write (a conversation nobody has becomes whoever replies or notes in it) and auto-assignment of new conversations: off, load (to whoever holds the fewest open) or round_robin (each in turn), the most open conversations per person, and who takes part (user ids; empty is everyone). Nobody away or at capacity is given one, and nothing assigned is moved. With no other argument it reads the settings and the team: each person online, away or offline with their open count. Owners and admins set it; the same values again change nothing.' +
252
+ SCOPE,
253
+ inputSchema: {
254
+ type: 'object',
255
+ properties: {
256
+ workspace: WORKSPACE,
257
+ autoAssign: { type: 'string', enum: AUTO_ASSIGN },
258
+ capacity: { type: 'number', description: 'Most open conversations per person, 1 to 100.' },
259
+ pool: { type: 'array', items: { type: 'number' }, description: 'User ids who take part; [] for everyone.' },
260
+ claimOnWrite: {
261
+ type: 'boolean',
262
+ description: 'Whether a conversation nobody has becomes whoever replies or writes a note in it (on by default).',
263
+ },
264
+ },
265
+ additionalProperties: false,
266
+ },
267
+ },
268
+ {
269
+ name: 'workover_support_availability',
270
+ description:
271
+ "The signed-in person's own availability in Support: away keeps auto-assignment from giving them new conversations. With no argument it reads theirs and the team's; away true or false sets it, and the same value again changes nothing. It only ever changes the caller's own switch." +
272
+ SCOPE,
273
+ inputSchema: {
274
+ type: 'object',
275
+ properties: { workspace: WORKSPACE, away: { type: 'boolean' } },
276
+ additionalProperties: false,
277
+ },
278
+ },
279
+ ];
280
+
281
+ export const INBOX_TOOLS = new Set(INBOX_TOOL_DEFS.map((t) => t.name));
282
+
283
+ /** One inbox-rules tool, as lines. Errors throw, for the dispatcher to put into words. */
284
+ export async function inboxToolLines(call, name, args = {}) {
285
+ const workspace = args.workspace === undefined || args.workspace === null ? undefined : String(args.workspace);
286
+ if (name === 'workover_support_sla') {
287
+ return renderSla(
288
+ await supportSla(call, {
289
+ workspace,
290
+ firstTarget: args.firstTarget,
291
+ nextTarget: args.nextTarget,
292
+ holidays: args.holidays,
293
+ tiers: args.tiers,
294
+ breachWarnings: args.breachWarnings,
295
+ }),
296
+ );
297
+ }
298
+ if (name === 'workover_support_assignment') {
299
+ return renderAssignment(
300
+ await supportAssignment(call, {
301
+ workspace,
302
+ autoAssign: args.autoAssign,
303
+ capacity: args.capacity,
304
+ pool: Array.isArray(args.pool) ? (args.pool.length ? args.pool.join(',') : 'everyone') : args.pool,
305
+ claimOnWrite: args.claimOnWrite,
306
+ }),
307
+ );
308
+ }
309
+ if (name === 'workover_support_availability') {
310
+ return renderAvailability(await supportAvailability(call, { workspace, away: args.away }));
311
+ }
312
+ throw apiError(400, `Unknown tool: ${name}`);
313
+ }
@@ -0,0 +1,136 @@
1
+ // When Support's AI adds each label, from a terminal: `workover support label-rules ...` and the MCP
2
+ // server's `workover_support_*label_rule*` tools (WO-1752, S09).
3
+ //
4
+ // THE SAME FILE ships in @workover/cli (apps/cli/support-label-rules.mjs) and @workover/mcp
5
+ // (apps/mcp/support-label-rules.mjs), because the two packages are published separately and neither
6
+ // may depend on the other. `apps/mcp/support-label-rules.test.mjs` fails when the copies differ.
7
+ //
8
+ // One plain-language rule per label ("the customer asks for money back"). The AI checks the rules
9
+ // when a conversation is handed to the team, and when a teammate asks for a summary, and only ever
10
+ // ADDS a label. Every call goes to a route opened to tokens holding the `support` scope
11
+ // (`workover login --support`). Each write is safe to repeat: setting a rule again answers
12
+ // `created: false`, and removing one again `removed: false`.
13
+ //
14
+ // `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
15
+ // whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
16
+ // return lines, for a terminal or an MCP text result alike.
17
+
18
+ import { apiError, resolveWorkspace } from './site-setup.mjs';
19
+
20
+ /** The longest rule the API takes. */
21
+ export const MAX_RULE = 500;
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
+ const base = (messengerId) => `/messenger/${messengerId}/label-ai-rules`;
33
+
34
+ /** Every rule, and every label in the catalog with whether it has one. */
35
+ export async function listLabelRules(call, { workspace } = {}) {
36
+ const { ws, messengerId } = await messengerOf(call, workspace);
37
+ const res = await call(base(messengerId));
38
+ return { workspace: ws, ...res };
39
+ }
40
+
41
+ /** Set a label's rule, by the label's name ("Billing / Refunds") or id. Replaces the one it had. */
42
+ export async function setLabelRule(call, { workspace, label, labelId, instruction, enabled }) {
43
+ const text = typeof instruction === 'string' ? instruction.trim() : '';
44
+ if (!text) throw apiError(400, 'Say when the label applies, as a plain sentence ("the customer asks for money back").');
45
+ if (text.length > MAX_RULE) throw apiError(400, `The rule is ${MAX_RULE} characters at most.`);
46
+ const body = { instruction: text };
47
+ const id = Number(labelId);
48
+ if (Number.isInteger(id) && id > 0) body.labelId = id;
49
+ else if (typeof label === 'string' && label.trim()) body.label = label.trim();
50
+ else throw apiError(400, 'Name the label, as it reads in the inbox ("Billing / Refunds").');
51
+ if (enabled !== undefined) body.enabled = !!enabled;
52
+ const { ws, messengerId } = await messengerOf(call, workspace);
53
+ const res = await call(base(messengerId), { method: 'PUT', body });
54
+ return { workspace: ws, ...res };
55
+ }
56
+
57
+ /** Remove a label's rule, by the label's name or id. */
58
+ export async function removeLabelRule(call, { workspace, label, labelId }) {
59
+ const { ws, messengerId } = await messengerOf(call, workspace);
60
+ let id = Number(labelId);
61
+ if (!Number.isInteger(id) || id <= 0) {
62
+ const name = typeof label === 'string' ? label.trim().toLowerCase() : '';
63
+ if (!name) throw apiError(400, 'Name the label whose rule to remove.');
64
+ const res = await call(base(messengerId));
65
+ const hit = (res.labels || []).find((l) => String(l.path).toLowerCase() === name);
66
+ if (!hit) throw apiError(404, `There is no label "${label}". \`workover support label-rules\` lists them.`);
67
+ id = hit.id;
68
+ }
69
+ const res = await call(`${base(messengerId)}/${id}`, { method: 'DELETE' });
70
+ return { workspace: ws, ...res };
71
+ }
72
+
73
+ // ------------------------------------------------------------------ rendering
74
+
75
+ export function renderLabelRules(res) {
76
+ const out = ['', ` When the AI adds labels in ${res.workspace?.name ?? 'this workspace'}`, ''];
77
+ if (!res.rules?.length) out.push(' No rules yet: the AI adds no labels.');
78
+ for (const r of res.rules || [])
79
+ out.push(` ${r.label}${r.enabled ? '' : ' (off)'}`, ` ${r.instruction}`);
80
+ const open = (res.labels || []).filter((l) => !l.hasRule);
81
+ if (open.length) out.push('', ` Labels without a rule: ${open.map((l) => l.path).join(', ')}`);
82
+ out.push('');
83
+ return out;
84
+ }
85
+
86
+ export function renderLabelRuleSet(res) {
87
+ const r = res.rule;
88
+ const head = res.created ? ` ✓ The AI now adds ${r.label} when:` : ` ✓ Updated the rule for ${r.label}:`;
89
+ return ['', head, ` ${r.instruction}${r.enabled ? '' : ' (off)'}`, ''];
90
+ }
91
+
92
+ export function renderLabelRuleRemoved(res) {
93
+ return ['', res.removed ? ' ✓ Removed. The AI no longer adds that label.' : ' ✓ That label had no rule; nothing changed.', ''];
94
+ }
95
+
96
+ // ------------------------------------------------------------------ MCP tool definitions
97
+
98
+ const WORKSPACE = {
99
+ type: ['string', 'number'],
100
+ description: 'The workspace, by slug or id. Needed only when the account has more than one.',
101
+ };
102
+ const SCOPE =
103
+ ' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
104
+ const LABEL = { type: 'string', description: 'The label as it reads in the inbox, such as "Billing / Refunds".' };
105
+
106
+ /** The MCP server's label-rule tools, listed with the other Support tools (index.mjs). */
107
+ export const LABEL_RULE_TOOL_DEFS = [
108
+ {
109
+ name: 'workover_support_label_rules',
110
+ description:
111
+ "When Support's AI adds each label to a conversation: one plain-language rule per label, checked when a conversation is handed to the team and when a teammate asks for a summary. Also lists the labels that have no rule." +
112
+ SCOPE,
113
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
114
+ },
115
+ {
116
+ name: 'workover_support_set_label_rule',
117
+ description:
118
+ 'Set when the AI adds a label: the label by its name, and a plain sentence saying when it applies (500 characters at most). Replaces the rule the label had. The AI only ever adds labels, never removes them. Safe to repeat. Owners and admins.' +
119
+ SCOPE,
120
+ inputSchema: {
121
+ type: 'object',
122
+ properties: {
123
+ workspace: WORKSPACE,
124
+ label: LABEL,
125
+ instruction: { type: 'string', description: 'When the label applies, such as "the customer asks for money back".' },
126
+ enabled: { type: 'boolean', description: 'False keeps the rule but stops the AI using it.' },
127
+ },
128
+ required: ['label', 'instruction'],
129
+ },
130
+ },
131
+ {
132
+ name: 'workover_support_remove_label_rule',
133
+ description: 'The AI stops adding this label. Safe to repeat. Owners and admins.' + SCOPE,
134
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, label: LABEL }, required: ['label'] },
135
+ },
136
+ ];