@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,660 @@
1
+ // Setting up Workover Support from a terminal: `workover support` and the MCP server's Support
2
+ // setup tools (WO-1752, S43).
3
+ //
4
+ // THE SAME FILE ships in @workover/cli (apps/cli/support-setup.mjs) and @workover/mcp
5
+ // (apps/mcp/support-setup.mjs), because the two packages are published separately and neither may
6
+ // depend on the other. `apps/mcp/support-setup.test.mjs` fails when the copies differ.
7
+ //
8
+ // WHY THIS EXISTS. Alex, 22 Nov 2026: Support must onboard agent-first, the way the rest of Workover
9
+ // does with /setup.md and the homepage prompt. A person pastes one prompt into their coding agent;
10
+ // the agent turns Support on, configures it, adds the Messenger to their app, signs who is signed in
11
+ // on their server, sends a test conversation and switches it on, while "Your agent is setting up
12
+ // Support" in the app ticks each step. Every call here goes to a route opened to tokens holding the
13
+ // `support` scope (`workover login --support`), and to nothing else.
14
+ //
15
+ // No ANSI and no side effects beyond the env file `writeIdentitySecret` is told to write:
16
+ // `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
17
+ // whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
18
+ // return lines, for a terminal or an MCP text result alike.
19
+
20
+ import { apiError, resolveWorkspace } from './site-setup.mjs';
21
+
22
+ /** The token scope these routes need, and the sign-in that grants it. */
23
+ export const SUPPORT_SCOPE = 'support';
24
+ export const SUPPORT_LOGIN = 'workover login --support';
25
+
26
+ /** The steps an agent reports itself; Workover checks the rest. Mirrors setup-steps.ts AGENT_STEPS. */
27
+ export const AGENT_STEPS = ['analyze_app', 'install_snippet'];
28
+
29
+ /** The sentence an agent needs when a Support route refuses the token. */
30
+ export const supportScopeHelp = (message) =>
31
+ /"support" scope|--support/.test(String(message || ''))
32
+ ? `This sign-in cannot set up Support. Run \`${SUPPORT_LOGIN}\` and ask the person to approve it in the browser (the approval screen lists "Set up Workover Support").`
33
+ : /^Support not found/.test(String(message || ''))
34
+ ? 'Support is not available in this workspace yet, or this account is not in it. Check the workspace with `workover whoami`.'
35
+ : null;
36
+
37
+ const SETUP = '/messenger/agent-setup';
38
+
39
+ // ------------------------------------------------------------------ office hours
40
+
41
+ const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
42
+
43
+ /** `9`, `9:30`, `17:00` → minutes after midnight; null for anything else. */
44
+ function minutesOf(raw) {
45
+ const m = /^(\d{1,2})(?::(\d{2}))?$/.exec(String(raw).trim());
46
+ if (!m) return null;
47
+ const h = Number(m[1]);
48
+ const min = Number(m[2] ?? 0);
49
+ if (h > 24 || min > 59 || (h === 24 && min > 0)) return null;
50
+ return h * 60 + min;
51
+ }
52
+
53
+ /**
54
+ * Office hours as a person says them, into what Support stores: `"mon-fri 9:00-17:00, sat 10-14"`
55
+ * in `tz` → `{ tz, days: { mon: [540, 1020], ... } }`. A day not named is closed. Throws an Error
56
+ * saying what it could not read.
57
+ */
58
+ export function parseHours(spec, tz) {
59
+ const zone = String(tz ?? '').trim();
60
+ if (!zone) throw apiError(400, 'Give the time zone the hours are in, such as --tz America/New_York.');
61
+ const days = {};
62
+ for (const part of String(spec ?? '').split(',').map((s) => s.trim()).filter(Boolean)) {
63
+ const m = /^([a-z]{3})(?:\s*-\s*([a-z]{3}))?\s+(\S+)\s*-\s*(\S+)$/i.exec(part);
64
+ if (!m) throw apiError(400, `Could not read "${part}". Write hours like "mon-fri 9:00-17:00, sat 10-14".`);
65
+ const from = DAYS.indexOf(m[1].toLowerCase());
66
+ const to = m[2] ? DAYS.indexOf(m[2].toLowerCase()) : from;
67
+ const start = minutesOf(m[3]);
68
+ const end = minutesOf(m[4]);
69
+ if (from < 0 || to < 0) throw apiError(400, `"${part}": days are sun, mon, tue, wed, thu, fri and sat.`);
70
+ if (start === null || end === null) throw apiError(400, `"${part}": times are like 9, 9:30 or 17:00.`);
71
+ for (let i = from; ; i = (i + 1) % 7) {
72
+ days[DAYS[i]] = [start, end];
73
+ if (i === to) break;
74
+ }
75
+ }
76
+ if (!Object.keys(days).length) throw apiError(400, 'Name at least one day, such as "mon-fri 9:00-17:00".');
77
+ return { tz: zone, days };
78
+ }
79
+
80
+ // ------------------------------------------------------------------ the app being set up
81
+
82
+ /**
83
+ * What the app in `dir` is built with, from its files, so the snippet goes in the right place.
84
+ * `fs` is `{ exists(path), read(path) }` (injected, so tests need no disk). Returns
85
+ * `{ framework, evidence, file }`, where `file` is where the snippet goes (relative), or a null
86
+ * framework when nothing is recognized.
87
+ */
88
+ export function detectFramework(fs, dir = '.') {
89
+ const at = (p) => `${String(dir).replace(/\/+$/, '')}/${p}`;
90
+ const has = (p) => {
91
+ try {
92
+ return fs.exists(at(p));
93
+ } catch {
94
+ return false;
95
+ }
96
+ };
97
+ const read = (p) => {
98
+ try {
99
+ return fs.read(at(p));
100
+ } catch {
101
+ return '';
102
+ }
103
+ };
104
+ let pkg = null;
105
+ try {
106
+ pkg = has('package.json') ? JSON.parse(read('package.json')) : null;
107
+ } catch {
108
+ pkg = null;
109
+ }
110
+ const deps = { ...(pkg?.dependencies || {}), ...(pkg?.devDependencies || {}) };
111
+ const first = (paths) => paths.find(has) || null;
112
+
113
+ if (deps.next) {
114
+ const layout = first(['app/layout.tsx', 'app/layout.jsx', 'app/layout.js', 'src/app/layout.tsx', 'src/app/layout.jsx', 'src/app/layout.js']);
115
+ if (layout) return { framework: 'nextjs-app', evidence: `next ${deps.next} with ${layout}`, file: layout };
116
+ const pages = first(['pages/_app.tsx', 'pages/_app.jsx', 'pages/_app.js', 'src/pages/_app.tsx', 'src/pages/_app.jsx', 'src/pages/_app.js']);
117
+ return { framework: 'nextjs-pages', evidence: `next ${deps.next}${pages ? ` with ${pages}` : ''}`, file: pages || 'pages/_app.tsx' };
118
+ }
119
+ if (has('wp-config.php') || has('wp-content') || /Theme Name:/i.test(read('style.css')) || /Plugin Name:/i.test(read('plugin.php'))) {
120
+ return { framework: 'wordpress', evidence: 'WordPress files', file: 'wp-content/mu-plugins/workover-support.php' };
121
+ }
122
+ if (deps.react) {
123
+ const html = first(['index.html', 'public/index.html']);
124
+ return { framework: 'react', evidence: `react ${deps.react}${html ? ` with ${html}` : ''}`, file: html || 'index.html' };
125
+ }
126
+ const html = first(['index.html', 'public/index.html']);
127
+ if (html) return { framework: 'html', evidence: html, file: html };
128
+ return { framework: null, evidence: null, file: null };
129
+ }
130
+
131
+ export const FRAMEWORKS = ['nextjs-app', 'nextjs-pages', 'react', 'html', 'wordpress'];
132
+
133
+ const LABELS = {
134
+ 'nextjs-app': 'Next.js (App Router)',
135
+ 'nextjs-pages': 'Next.js (Pages Router)',
136
+ react: 'React',
137
+ html: 'plain HTML',
138
+ wordpress: 'WordPress',
139
+ };
140
+
141
+ /** The loader tags, as the settings page's Install section prints them. */
142
+ export function loaderTags(host, key) {
143
+ const origin = String(host).replace(/\/+$/, '');
144
+ return [
145
+ '<script>',
146
+ ' window.Messenger = window.Messenger || function () {',
147
+ ' (window.Messenger.q = window.Messenger.q || []).push(arguments);',
148
+ ' };',
149
+ '</script>',
150
+ `<script src="${origin}/messenger/v1.js" data-key="${key}" async></script>`,
151
+ ].join('\n');
152
+ }
153
+
154
+ /**
155
+ * The snippet for one framework: `{ framework, label, file, code, steps }`. `identify` adds the
156
+ * call that tells the Messenger who is signed in, with the hash from the site's server.
157
+ */
158
+ export function installSnippet({ framework, host, key, file }) {
159
+ const origin = String(host).replace(/\/+$/, '');
160
+ const src = `${origin}/messenger/v1.js`;
161
+ const queue = "window.Messenger = window.Messenger || function () { (window.Messenger.q = window.Messenger.q || []).push(arguments); };";
162
+ if (framework === 'nextjs-app' || framework === 'nextjs-pages') {
163
+ const code = `import Script from 'next/script';
164
+
165
+ // Workover Support: the Messenger, on every page.
166
+ export function WorkoverMessenger() {
167
+ return (
168
+ <>
169
+ <Script id="workover-messenger-queue" strategy="afterInteractive">
170
+ {\`${queue}\`}
171
+ </Script>
172
+ <Script src="${src}" data-key="${key}" strategy="afterInteractive" />
173
+ </>
174
+ );
175
+ }
176
+ `;
177
+ return {
178
+ framework,
179
+ label: LABELS[framework],
180
+ file: file || (framework === 'nextjs-app' ? 'app/layout.tsx' : 'pages/_app.tsx'),
181
+ code,
182
+ steps: [
183
+ framework === 'nextjs-app'
184
+ ? 'Render <WorkoverMessenger /> inside <body> in the root layout.'
185
+ : 'Render <WorkoverMessenger /> once in _app, beside <Component />.',
186
+ ],
187
+ };
188
+ }
189
+ if (framework === 'wordpress') {
190
+ const code = `<?php
191
+ /**
192
+ * Plugin Name: Workover Support
193
+ * Description: The Workover Messenger on every page.
194
+ */
195
+ add_action('wp_footer', function () {
196
+ ?>
197
+ ${loaderTags(origin, key)}
198
+ <?php
199
+ });
200
+ `;
201
+ return {
202
+ framework,
203
+ label: LABELS.wordpress,
204
+ file: file || 'wp-content/mu-plugins/workover-support.php',
205
+ code,
206
+ steps: ['Save it as a must-use plugin, or add the action to the theme’s functions.php.'],
207
+ };
208
+ }
209
+ return {
210
+ framework: framework || 'html',
211
+ label: LABELS[framework] || LABELS.html,
212
+ file: file || 'index.html',
213
+ code: `${loaderTags(origin, key)}\n`,
214
+ steps: ['Paste it before the closing </body> tag on every page that should show the Messenger.'],
215
+ };
216
+ }
217
+
218
+ /** The env variable the identity secret goes in, unless told otherwise. */
219
+ export const SECRET_VAR = 'WORKOVER_SUPPORT_IDENTITY_SECRET';
220
+
221
+ /**
222
+ * How the site's server signs who is signed in, so the Messenger can trust the email (Node or
223
+ * PHP). Matches messenger/public/identity.ts: hex HMAC-SHA256 of `lower(email)|exp`, with the
224
+ * secret from `SECRET_VAR`, and `Messenger('identify', { email, name, hash, exp })` in the page.
225
+ */
226
+ export function identitySnippet(framework, varName = SECRET_VAR) {
227
+ if (framework === 'wordpress') {
228
+ return {
229
+ language: 'php',
230
+ code: `<?php
231
+ // Who is signed in, signed for the Workover Messenger. Keep ${varName} on the server only.
232
+ add_action('wp_footer', function () {
233
+ $secret = getenv('${varName}');
234
+ // No secret on this server yet: send no identity rather than one Workover will refuse.
235
+ if (!is_user_logged_in() || !$secret) return;
236
+ $user = wp_get_current_user();
237
+ $email = strtolower(trim($user->user_email));
238
+ $exp = time() + 7 * 86400;
239
+ $hash = hash_hmac('sha256', $email . '|' . $exp, $secret);
240
+ $identity = ['email' => $email, 'name' => $user->display_name, 'hash' => $hash, 'exp' => $exp];
241
+ // The queue line first: this may run before the loader's own, and it is safe to repeat.
242
+ echo '<script>window.Messenger = window.Messenger || function () { (window.Messenger.q = window.Messenger.q || []).push(arguments); };'
243
+ . 'window.Messenger("identify", ' . wp_json_encode($identity) . ');</script>';
244
+ });
245
+ `,
246
+ };
247
+ }
248
+ return {
249
+ language: 'ts',
250
+ code: `import { createHmac } from 'node:crypto';
251
+
252
+ // Who is signed in, signed for the Workover Messenger. Server-side only: ${varName}
253
+ // must never reach the browser.
254
+ export function messengerIdentity(user: { email: string; name?: string }) {
255
+ const secret = process.env.${varName};
256
+ if (!secret) throw new Error('${varName} is not set on this server.');
257
+ const email = user.email.trim().toLowerCase();
258
+ const exp = Math.floor(Date.now() / 1000) + 7 * 86400;
259
+ const hash = createHmac('sha256', secret)
260
+ .update(\`\${email}|\${exp}\`)
261
+ .digest('hex');
262
+ return { email, name: user.name, hash, exp };
263
+ }
264
+
265
+ // In the page, once the person is known:
266
+ // window.Messenger('identify', messengerIdentity(user));
267
+ `,
268
+ };
269
+ }
270
+
271
+ // ------------------------------------------------------------------ the calls
272
+
273
+ const orgQuery = (ws) => `organizationId=${encodeURIComponent(ws.id)}`;
274
+
275
+ /** The checklist, and Support as it stands. Connects the agent on its first read. */
276
+ export async function supportStatus(call, { workspace } = {}) {
277
+ const ws = await resolveWorkspace(call, workspace);
278
+ const status = await call(`${SETUP}?${orgQuery(ws)}`);
279
+ return { workspace: ws, ...status };
280
+ }
281
+
282
+ /**
283
+ * Support set up as asked, in one call: created switched off when there is none, plain settings
284
+ * set, sites, topics and docs projects added (never replaced). Safe to run again: `changed` is
285
+ * empty when nothing needed changing.
286
+ */
287
+ export async function supportSetup(call, { workspace, ...fields }) {
288
+ const ws = await resolveWorkspace(call, workspace);
289
+ const body = { organizationId: ws.id };
290
+ for (const k of ['name', 'color', 'greeting', 'intro', 'hours', 'replyTime', 'agentEnabled', 'agentName', 'enabled', 'origins', 'topics', 'projectIds'])
291
+ if (fields[k] !== undefined) body[k] = fields[k];
292
+ const res = await call(`${SETUP}/configure`, { method: 'POST', body });
293
+ return { workspace: ws, ...res };
294
+ }
295
+
296
+ /** A step only the agent can see: `analyze_app` or `install_snippet`. */
297
+ export async function reportStep(call, { workspace, step, state = 'done', detail }) {
298
+ if (!AGENT_STEPS.includes(step))
299
+ throw apiError(400, `Report one of ${AGENT_STEPS.join(' or ')}. Workover checks the other steps itself.`);
300
+ const ws = await resolveWorkspace(call, workspace);
301
+ const res = await call(`${SETUP}/steps`, {
302
+ method: 'POST',
303
+ body: { organizationId: ws.id, step, state, ...(detail ? { detail: String(detail) } : {}) },
304
+ });
305
+ return { workspace: ws, ...res };
306
+ }
307
+
308
+ /**
309
+ * The test conversation: sent, then read back from the checklist until Workover finds it in the
310
+ * inbox (`confirm`), or `timeoutMs` passes. One per workspace; running it again finds the first.
311
+ */
312
+ export async function sendTest(call, { workspace, timeoutMs = 20_000, everyMs = 1_000, sleep } = {}) {
313
+ const ws = await resolveWorkspace(call, workspace);
314
+ const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
315
+ const sent = await call(`${SETUP}/test`, { method: 'POST', body: { organizationId: ws.id } });
316
+ let status = sent;
317
+ const started = Date.now();
318
+ const confirmed = (s) => s?.steps?.find((x) => x.key === 'confirm')?.state === 'done';
319
+ while (!confirmed(status) && Date.now() - started < timeoutMs) {
320
+ await wait(everyMs);
321
+ status = await call(`${SETUP}?${orgQuery(ws)}`);
322
+ }
323
+ return { workspace: ws, created: !!sent?.created, confirmed: confirmed(status), ...status };
324
+ }
325
+
326
+ /**
327
+ * The "closed stays closed" switch (S35b): read it, or set it when `closedStaysClosed` is a
328
+ * boolean. When it is on, a visitor writing to a closed conversation starts a new one and the
329
+ * closed one stays closed; off (the default), the message reopens it. Safe to run again: `changed`
330
+ * is false when the switch already had that value, and nothing is written.
331
+ */
332
+ export async function supportThread(call, { workspace, closedStaysClosed } = {}) {
333
+ if (closedStaysClosed !== undefined && typeof closedStaysClosed !== 'boolean')
334
+ throw apiError(400, 'closedStaysClosed is true or false.');
335
+ const status = await supportStatus(call, { workspace });
336
+ const id = status?.messenger?.id;
337
+ if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
338
+ const path = `/messenger/${encodeURIComponent(id)}/thread`;
339
+ const before = await call(path);
340
+ if (closedStaysClosed === undefined || before?.closedStaysClosed === closedStaysClosed)
341
+ return {
342
+ workspace: status.workspace,
343
+ messengerId: id,
344
+ closedStaysClosed: !!before?.closedStaysClosed,
345
+ asked: closedStaysClosed !== undefined,
346
+ changed: false,
347
+ };
348
+ const after = await call(path, { method: 'PUT', body: { closedStaysClosed } });
349
+ return { workspace: status.workspace, messengerId: id, closedStaysClosed: !!after?.closedStaysClosed, asked: true, changed: true };
350
+ }
351
+
352
+ /** `VAR=value` set in env text: the line replaced where it is, or added at the end. */
353
+ export function setEnvLine(text, name, value) {
354
+ const line = `${name}=${value}`;
355
+ const lines = String(text ?? '').split('\n');
356
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
357
+ const at = lines.findIndex((l) => new RegExp(`^\\s*(?:export\\s+)?${name}\\s*=`).test(l));
358
+ if (at >= 0) lines[at] = line;
359
+ else lines.push(line);
360
+ return `${lines.join('\n')}\n`;
361
+ }
362
+
363
+ /**
364
+ * The identity secret, written straight into the server's env file and never printed or returned:
365
+ * a secret in an agent's transcript is a secret in every log that transcript reaches. A Support
366
+ * that already has one keeps it unless `rotate` (the site may be signing with it now).
367
+ * `files` is `{ read(path), write(path, text) }`, injected.
368
+ */
369
+ export async function writeIdentitySecret(call, files, { workspace, envFile, varName = SECRET_VAR, rotate = false }) {
370
+ if (!envFile || typeof envFile !== 'string')
371
+ throw apiError(400, 'Name the env file the secret goes in, such as --env-file .env.local. It is written there and never printed.');
372
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(varName)) throw apiError(400, `"${varName}" is not an env variable name.`);
373
+ const ws = await resolveWorkspace(call, workspace);
374
+ let before = '';
375
+ try {
376
+ before = files.read(envFile);
377
+ } catch {
378
+ before = '';
379
+ }
380
+ // Prove the file can be written BEFORE Workover makes the secret: it is returned once, and with
381
+ // `rotate` the old one stops working at once, so a write failing afterwards would leave the site
382
+ // with no secret that works and no way to read the new one back.
383
+ try {
384
+ files.write(envFile, before);
385
+ } catch (e) {
386
+ throw apiError(400, `Cannot write ${envFile} (${e?.code || e?.message || 'refused'}). Nothing was created; fix the path and run this again.`);
387
+ }
388
+ const { secret, rotatedAt } = await call(`${SETUP}/secret`, {
389
+ method: 'POST',
390
+ body: { organizationId: ws.id, ...(rotate ? { rotate: true } : {}) },
391
+ });
392
+ files.write(envFile, setEnvLine(before, varName, secret));
393
+ return { workspace: ws, envFile, varName, rotatedAt, rotated: !!rotate };
394
+ }
395
+
396
+ // ------------------------------------------------------------------ notification switches (S05)
397
+
398
+ /** The person's own Support notification switches. Not under a workspace: they apply in every one. */
399
+ const NOTIFY = '/messenger/notification-preferences';
400
+
401
+ /** Where Support's notifications arrive, and what they are about, as the api names them. */
402
+ export const NOTIFY_CHANNELS = ['inApp', 'email', 'slack', 'push'];
403
+ export const NOTIFY_EVENTS = ['newConversation', 'handoff', 'assigned', 'mention'];
404
+ const NOTIFY_SWITCHES = [...NOTIFY_CHANNELS, ...NOTIFY_EVENTS];
405
+ const ON = new Set(['on', 'true', 'yes', '1']);
406
+ const OFF = new Set(['off', 'false', 'no', '0']);
407
+
408
+ /**
409
+ * `email=off, slack=on` (a terminal's way of saying it) → `{ email: false, slack: true }`. Throws an
410
+ * Error naming what it cannot read, before anything is sent.
411
+ */
412
+ export function parseSwitches(spec) {
413
+ const out = {};
414
+ for (const part of String(spec ?? '').split(',').map((s) => s.trim()).filter(Boolean)) {
415
+ const m = /^([A-Za-z]+)\s*=\s*(\S+)$/.exec(part);
416
+ if (!m) throw apiError(400, `Could not read "${part}". Write switches like "email=off,slack=on".`);
417
+ const key = NOTIFY_SWITCHES.find((k) => k.toLowerCase() === m[1].toLowerCase());
418
+ if (!key) throw apiError(400, `"${m[1]}" is not a Support notification switch. One of: ${NOTIFY_SWITCHES.join(', ')}.`);
419
+ const v = m[2].toLowerCase();
420
+ if (!ON.has(v) && !OFF.has(v)) throw apiError(400, `"${part}": a switch is on or off.`);
421
+ out[key] = ON.has(v);
422
+ }
423
+ if (!Object.keys(out).length) throw apiError(400, 'Name at least one switch, such as "email=off".');
424
+ return out;
425
+ }
426
+
427
+ /**
428
+ * Read, or with `set` change, the signed-in person's Support notification switches. Safe to repeat:
429
+ * the answer's `changed` names what this call changed, and is empty when nothing did. Only the
430
+ * switches in `set` are sent; anything else in it is refused by the api with a sentence naming it.
431
+ */
432
+ export async function supportNotifications(call, { set } = {}) {
433
+ if (set && Object.keys(set).length) return call(NOTIFY, { method: 'PUT', body: set });
434
+ return call(NOTIFY);
435
+ }
436
+
437
+ const SWITCH_LABEL = {
438
+ inApp: 'In Workover (the bell)',
439
+ email: 'Email',
440
+ slack: 'Slack',
441
+ push: 'Phone',
442
+ newConversation: 'New conversations',
443
+ handoff: 'Handoffs',
444
+ assigned: 'Assigned to you',
445
+ mention: 'Mentions',
446
+ };
447
+
448
+ /** The switches as lines, with what a change did and why email or push may still be held off. */
449
+ export function renderSupportNotifications(s) {
450
+ const prefs = s?.prefs || {};
451
+ const master = s?.master || {};
452
+ const mark = (on) => (on ? '[x]' : '[ ]');
453
+ const head = Array.isArray(s?.changed)
454
+ ? s.changed.length
455
+ ? ` ✓ Changed: ${s.changed.join(', ')}.`
456
+ : ' Nothing to change: the switches already read like that.'
457
+ : ' Your Support notification switches (yours, in every workspace):';
458
+ const out = ['', head, '', ' Tell me about'];
459
+ for (const k of NOTIFY_EVENTS) out.push(` ${mark(prefs[k])} ${SWITCH_LABEL[k]} (${k})`);
460
+ out.push('', ' Where');
461
+ for (const k of NOTIFY_CHANNELS) {
462
+ const held =
463
+ (k === 'email' && master.emailEnabled === false) || (k === 'push' && master.pushEnabled === false)
464
+ ? `, held off by your general ${k === 'email' ? '"All emails"' : 'phone'} switch`
465
+ : '';
466
+ out.push(` ${mark(prefs[k] && !held)} ${SWITCH_LABEL[k]} (${k}${held})`);
467
+ }
468
+ out.push('', ' Change one with: workover support notifications --set "email=off,slack=on"', '');
469
+ return out;
470
+ }
471
+
472
+ // ------------------------------------------------------------------ the chat's look (S35a)
473
+
474
+ /** What `support home` may set; the api refuses anything else. */
475
+ export const HOME_FIELDS = ['showFaces', 'typingIntro', 'logoUrl', 'botAvatarUrl', 'faces'];
476
+ /** The picture slots: the logo, the agent's picture, and up to six team faces. */
477
+ export const HOME_SLOTS = ['logo', 'bot', 'face-0', 'face-1', 'face-2', 'face-3', 'face-4', 'face-5'];
478
+
479
+ async function homeOf(call, workspace) {
480
+ const status = await supportStatus(call, { workspace });
481
+ if (!status.messenger) throw apiError(404, 'Support is not set up yet. Run `workover support setup` first.');
482
+ return { workspace: status.workspace, path: `/messenger/${status.messenger.id}/home` };
483
+ }
484
+
485
+ /**
486
+ * The look of the chat's Home screen: read it, or set what is given. Safe to run again: the same
487
+ * values change nothing. `faces` replaces the list; keep an uploaded photo by passing its `photoId`
488
+ * (the `id` of the face's `photo` in the answer). A `logoUrl` or `botAvatarUrl` of null removes it.
489
+ */
490
+ export async function supportHome(call, { workspace, ...fields }) {
491
+ const { workspace: ws, path } = await homeOf(call, workspace);
492
+ const body = {};
493
+ for (const k of HOME_FIELDS) if (fields[k] !== undefined) body[k] = fields[k];
494
+ const changed = Object.keys(body);
495
+ const home = changed.length ? await call(path, { method: 'PUT', body }) : await call(path);
496
+ return { workspace: ws, home, changed };
497
+ }
498
+
499
+ /**
500
+ * A picture into one slot (`file` is `{ bytes, filename, type }`), or with `remove` the slot
501
+ * cleared. `face-N` with N equal to the number of faces adds one, and needs `name`.
502
+ */
503
+ export async function supportHomeImage(call, { workspace, slot, file, name, remove = false }) {
504
+ if (!HOME_SLOTS.includes(slot)) throw apiError(400, `The slot is one of ${HOME_SLOTS.join(', ')}.`);
505
+ const { workspace: ws, path } = await homeOf(call, workspace);
506
+ const at = `${path}/images/${slot}`;
507
+ if (remove) return { workspace: ws, home: await call(at, { method: 'DELETE' }), changed: [slot] };
508
+ if (!file?.bytes) throw apiError(400, 'Name the picture file to upload.');
509
+ const form = new FormData();
510
+ form.append('file', new Blob([file.bytes], { type: file.type || 'application/octet-stream' }), file.filename || 'picture');
511
+ if (name) form.append('name', String(name));
512
+ return { workspace: ws, home: await call(at, { method: 'PUT', body: form }), changed: [slot] };
513
+ }
514
+
515
+ /** A picture's type from its file name, for the upload; the api still checks the bytes. */
516
+ export function imageTypeFor(filename) {
517
+ const ext = String(filename).toLowerCase().split('.').pop();
518
+ return { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' }[ext] || 'application/octet-stream';
519
+ }
520
+
521
+ // ------------------------------------------------------------------ what it says
522
+
523
+ const MARK = { done: '[x]', running: '[~]', failed: '[!]', pending: '[ ]', skipped: '[-]' };
524
+
525
+ /** The checklist as lines: each step, who did it, and the next thing to run. */
526
+ export function renderSupportStatus(s, { web } = {}) {
527
+ const out = ['', ` Support setup in ${s.workspace?.name || s.workspaceSlug || 'the workspace'}: ${s.done} of ${s.total} done`, ''];
528
+ for (const step of s.steps || []) {
529
+ const by = step.state === 'done' && step.by ? ` (${step.by})` : '';
530
+ // Live by hand (admin setup walk round 3, B1): an agent step no agent needed reads [-], and
531
+ // what is still open is optional rather than holding setup up.
532
+ const optional = step.optional && step.state !== 'done' ? ' (optional)' : '';
533
+ out.push(` ${MARK[step.state] || '[ ]'} ${step.label}${by}${optional}`);
534
+ if (step.detail) out.push(` ${step.detail}`);
535
+ }
536
+ if (s.messenger) {
537
+ const m = s.messenger;
538
+ out.push('', ` ${m.name}: ${m.enabled ? 'on' : 'off'}. Sites: ${m.origins.length ? m.origins.join(', ') : 'none yet'}.`);
539
+ if (m.topics?.length) out.push(` Topics: ${m.topics.join(', ')}.`);
540
+ out.push(` Docs it answers from: ${m.projects.length ? m.projects.map((p) => `${p.name} (#${p.projectId})`).join(', ') : 'none yet'}.`);
541
+ out.push(` Identity secret: ${m.hasIdentitySecret ? 'set' : 'not yet'}.`);
542
+ }
543
+ const next = (s.steps || []).find((x) => x.key === s.next);
544
+ if (next) {
545
+ out.push('', ` Next: ${next.label}. ${next.hint}`);
546
+ if (next.command) out.push(` ${next.command}`);
547
+ } else {
548
+ out.push('', ' Support is live: it is on and loading on your site.');
549
+ const test = (s.steps || []).find((x) => x.key === 'send_test' && x.state !== 'done');
550
+ if (test) out.push(' Optional: send a test conversation to check it arrives.', ` ${test.command}`);
551
+ }
552
+ // The api names the page in full (pageUrl); an older api gives only the path.
553
+ const page = s.pageUrl || (web && s.pagePath ? `${web}${s.pagePath}` : null);
554
+ if (page) out.push('', ` Live checklist: ${page}`);
555
+ out.push('');
556
+ return out;
557
+ }
558
+
559
+ /** What `support setup` did. */
560
+ export function renderSupportSetup(s, opts = {}) {
561
+ const head = s.created
562
+ ? ' ✓ Turned Support on (the Messenger stays off until you go live).'
563
+ : s.changed?.length
564
+ ? ` ✓ Updated Support: ${s.changed.join(', ')}.`
565
+ : ' Nothing to change: Support already has these settings.';
566
+ return ['', head, ...renderSupportStatus(s, opts).slice(1)];
567
+ }
568
+
569
+ /** What `support test` found. */
570
+ export function renderSupportTest(s, { web } = {}) {
571
+ const where = web && s.test?.inboxPath ? `${web}${s.test.inboxPath}` : s.test?.conversationId;
572
+ return [
573
+ '',
574
+ s.created ? ' ✓ Sent a test conversation.' : ' The test conversation was sent before; nothing new was sent.',
575
+ s.confirmed
576
+ ? ` ✓ It is in the inbox${where ? `: ${where}` : '.'}`
577
+ : ' ✗ It has not reached the inbox yet. Run `workover support status` in a moment.',
578
+ '',
579
+ ];
580
+ }
581
+
582
+ /** What `support thread` found or changed. */
583
+ export function renderSupportThread(s) {
584
+ const what = s.closedStaysClosed
585
+ ? 'Closed conversations stay closed: a visitor writing again starts a new conversation.'
586
+ : 'Closed conversations reopen when the visitor writes again.';
587
+ if (s.changed) return ['', ` ✓ ${what}`, ''];
588
+ return ['', ` ${what}${s.asked ? ' It was already set; nothing changed.' : ''}`, ''];
589
+ }
590
+
591
+ /**
592
+ * The pinned loader (S35b), for a site that decides when its loader changes: the same Messenger,
593
+ * with the file's integrity hash, so the browser refuses it if its bytes ever differ. Nothing when
594
+ * the api has none (no host, or an api before S35b).
595
+ */
596
+ function pinnedLines(pinned) {
597
+ if (!pinned || typeof pinned.snippet !== 'string') return [];
598
+ return [
599
+ ` To pin loader version ${pinned.version} instead (plain HTML, with its integrity hash):`,
600
+ '',
601
+ ...pinned.snippet.trimEnd().split('\n').map((l) => ` ${l}`),
602
+ '',
603
+ ];
604
+ }
605
+
606
+ /** The snippet and the identity signing, for the framework found or named. */
607
+ export function renderInstall({ status, detected, framework }) {
608
+ const key = status?.install?.key;
609
+ const host = status?.install?.host;
610
+ if (!key) return ['', ' Support is not set up yet. Run `workover support setup` first.', ''];
611
+ if (!host)
612
+ return ['', ` This Workover server has no chat address set up, so it cannot give an install snippet yet. Contact Workover support. Your Messenger key is ${key}.`, ''];
613
+ const fw = framework || detected?.framework || 'html';
614
+ const snip = installSnippet({ framework: fw, host, key, file: framework ? null : detected?.file });
615
+ const id = identitySnippet(fw);
616
+ return [
617
+ '',
618
+ detected?.framework && !framework
619
+ ? ` Found ${LABELS[detected.framework]} (${detected.evidence}).`
620
+ : ` For ${snip.label}.`,
621
+ '',
622
+ ` 1. Add the Messenger (${snip.file}):`,
623
+ '',
624
+ ...snip.code.trimEnd().split('\n').map((l) => ` ${l}`),
625
+ '',
626
+ ...snip.steps.map((s) => ` ${s}`),
627
+ '',
628
+ ...pinnedLines(status?.install?.pinned),
629
+ ` 2. Sign who is signed in, on the server (${id.language === 'php' ? 'PHP' : 'Node'}). The secret comes from`,
630
+ ` \`workover support secret --env-file <file>\`, which writes ${SECRET_VAR} there:`,
631
+ '',
632
+ ...id.code.trimEnd().split('\n').map((l) => ` ${l}`),
633
+ '',
634
+ ' 3. Then: workover support step install_snippet --detail "<the file you changed>"',
635
+ '',
636
+ ];
637
+ }
638
+
639
+ /** The chat's Home look, as `support home` changed or found it. */
640
+ export function renderSupportHome(s) {
641
+ const h = s.home || {};
642
+ const pic = (p) => (!p ? 'none' : p.kind === 'url' ? p.url : 'uploaded');
643
+ const onOff = (v) => (v ? 'on' : 'off');
644
+ const out = [
645
+ '',
646
+ s.changed?.length ? ` ✓ Updated the chat's Home: ${s.changed.join(', ')}.` : " The chat's Home as it stands:",
647
+ '',
648
+ ` Logo: ${pic(h.logo)}. Agent picture: ${pic(h.botAvatar)}.`,
649
+ ` Typing intro: ${onOff(h.typingIntro)}. Team faces: ${onOff(h.showFaces)}.`,
650
+ ];
651
+ for (const [i, f] of (h.faces || []).entries())
652
+ out.push(` face-${i}: ${f.name}${f.photo ? ` (photo ${pic(f.photo)}, photoId ${f.photo.id})` : ' (no photo)'}`);
653
+ if (h.ink?.contrast) {
654
+ const c = h.ink.contrast;
655
+ out.push(` Contrast from the brand color: words on it ${c.onBrand}:1, as text ${c.onLight}:1 light, ${c.onDark}:1 dark.`);
656
+ }
657
+ if (h.allowedHosts?.length) out.push(` Picture addresses allowed: ${h.allowedHosts.join(', ')}.`);
658
+ out.push('');
659
+ return out;
660
+ }