@workover/mcp 0.20.0 → 0.23.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/contacts.mjs ADDED
@@ -0,0 +1,1561 @@
1
+ // Stored contacts from a terminal (Contacts CRM step 1, WO-1752): `workover contacts ...` and the
2
+ // MCP server's `workover_contacts_*` tools.
3
+ //
4
+ // THE SAME FILE ships in @workover/cli (apps/cli/contacts.mjs) and @workover/mcp
5
+ // (apps/mcp/contacts.mjs), because the two packages are published separately and neither may depend
6
+ // on the other. `apps/mcp/contacts.test.mjs` fails when the copies differ.
7
+ //
8
+ // Contacts are people a workspace keeps, by their external id (the customer's own user id) and their
9
+ // email, with typed attributes. Every call goes to a route opened to tokens holding the `contacts`
10
+ // scope (`workover login --contacts`). Reading is any teammate's; identifying, defining attributes
11
+ // and managing the workspace's server API keys are the owners' and admins'. Each write is safe to
12
+ // repeat: identifying the same contact again answers `changed: false`, defining an attribute again
13
+ // `created: false`, revoking a revoked key `revoked: false`.
14
+ //
15
+ // A customer's own servers identify contacts with a workspace API key (`wsk_...`) at
16
+ // POST /v1/contacts/identify; `workover contacts keys create` makes one.
17
+ //
18
+ // Events (Contacts CRM step 2): what a person did, such as `order.completed`, about a contact named
19
+ // by externalId or email, or an anonymousId for someone not yet known. An event for someone who is
20
+ // not a contact yet is kept anonymous for 30 days and attached when they are identified. A server
21
+ // sends them to POST /v1/events with the same key; `workover contacts track` sends them as a person.
22
+ //
23
+ // Segments (Contacts CRM step 3): saved groups of contacts. A dynamic segment is a definition, rules
24
+ // on attributes, built-in fields, events and other segments (DEFINITION_HELP below), whose members
25
+ // Workover keeps current; a manual one is a list people add to. Preview a definition before saving
26
+ // it: the count is what the segment will hold. Exports are CSV, for owners and admins.
27
+ //
28
+ // Topics (Contacts CRM step 4): what a workspace emails about, such as "newsletter". Each is opt_in
29
+ // (only after a yes) or opt_out (subscribed until they say no); a contact's own choice beats the
30
+ // default, and "unsubscribe from all" beats every topic. Every change is kept in an append-only
31
+ // consent log. A preference link is a signed URL to the contact's own preference page: a
32
+ // credential, for that person only. Nothing here sends email.
33
+ //
34
+ // `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
35
+ // whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
36
+ // return lines, for a terminal or an MCP text result alike.
37
+
38
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
39
+
40
+ import { apiError, resolveWorkspace } from './site-setup.mjs';
41
+
42
+ export const CONTACTS_LOGIN = 'workover login --contacts';
43
+ export const ATTRIBUTE_TYPES = ['string', 'number', 'boolean', 'date'];
44
+ /** The most contacts one batch call takes; a longer list is sent in batches of this size. */
45
+ export const BATCH_SIZE = 100;
46
+
47
+ /** The sentence an agent needs when a Contacts route refuses the token. */
48
+ export const contactsScopeHelp = (message) =>
49
+ /"contacts" scope|--contacts/.test(String(message || ''))
50
+ ? `This sign-in cannot reach Contacts. Run \`${CONTACTS_LOGIN}\` and ask the person to approve it in the browser.`
51
+ : null;
52
+
53
+ const base = (ws) => `/workspace/${encodeURIComponent(ws.id)}`;
54
+ /** The MCP server says so (`?via=mcp`), so its changes are logged as mcp rather than cli. */
55
+ const viaQuery = (via) => (via === 'mcp' ? '?via=mcp' : '');
56
+
57
+ // ── Reading a file of contacts ─────────────────────────────────────────────────────────────────────
58
+
59
+ /** RFC 4180 rows: quoted fields, doubled quotes, commas and newlines inside quotes. */
60
+ export function parseCsv(text) {
61
+ const rows = [];
62
+ let row = [];
63
+ let field = '';
64
+ let quoted = false;
65
+ const s = String(text ?? '').replace(/^/, '');
66
+ for (let i = 0; i < s.length; i++) {
67
+ const c = s[i];
68
+ if (quoted) {
69
+ if (c === '"' && s[i + 1] === '"') {
70
+ field += '"';
71
+ i++;
72
+ } else if (c === '"') quoted = false;
73
+ else field += c;
74
+ } else if (c === '"' && field === '') quoted = true;
75
+ else if (c === ',') {
76
+ row.push(field);
77
+ field = '';
78
+ } else if (c === '\n' || c === '\r') {
79
+ if (c === '\r' && s[i + 1] === '\n') i++;
80
+ row.push(field);
81
+ rows.push(row);
82
+ row = [];
83
+ field = '';
84
+ } else field += c;
85
+ }
86
+ if (field !== '' || row.length) {
87
+ row.push(field);
88
+ rows.push(row);
89
+ }
90
+ return rows.filter((r) => r.some((x) => x.trim() !== ''));
91
+ }
92
+
93
+ const TOP = {
94
+ externalid: 'externalId',
95
+ external_id: 'externalId',
96
+ user_id: 'externalId',
97
+ id: 'externalId',
98
+ email: 'email',
99
+ name: 'name',
100
+ };
101
+
102
+ /**
103
+ * A CSV cell as the value an identify sends. A column's cells read as true/false or a number are
104
+ * sent as such, so `seats` is a number attribute; everything else is text (a date in ISO form is
105
+ * recognised by the api). An empty cell sends nothing.
106
+ */
107
+ function cellValue(raw) {
108
+ const v = String(raw).trim();
109
+ if (v === '') return undefined;
110
+ if (/^(true|false)$/i.test(v)) return v.toLowerCase() === 'true';
111
+ if (/^-?\d+(\.\d+)?$/.test(v) && !/^-?0\d/.test(v) && Number.isFinite(Number(v))) return Number(v);
112
+ return v;
113
+ }
114
+
115
+ /**
116
+ * Contacts from a file's text: JSON (a list, `{ "contacts": [...] }`, or one contact) or CSV with a
117
+ * header row. In a CSV, `external_id` (or `externalId`, `user_id`, `id`), `email` and `name` are the
118
+ * contact's own fields and every other column is an attribute, its header the key.
119
+ */
120
+ export function contactsFromText(text, filename = '') {
121
+ const s = String(text ?? '').trim();
122
+ if (!s) throw apiError(400, 'The file is empty.');
123
+ const json = /\.json$/i.test(filename) || s.startsWith('[') || s.startsWith('{');
124
+ if (json) {
125
+ let parsed;
126
+ try {
127
+ parsed = JSON.parse(s);
128
+ } catch (e) {
129
+ throw apiError(400, `The file is not valid JSON: ${e.message}`);
130
+ }
131
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.contacts) ? parsed.contacts : [parsed];
132
+ if (!list.length) throw apiError(400, 'The file holds no contacts.');
133
+ return list;
134
+ }
135
+ const rows = parseCsv(s);
136
+ if (rows.length < 2) throw apiError(400, 'A CSV needs a header row and at least one contact.');
137
+ const header = rows[0].map((h) => h.trim());
138
+ const keys = header.map((h) => TOP[h.toLowerCase()] ?? null);
139
+ return rows.slice(1).map((r) => {
140
+ const c = {};
141
+ const attributes = {};
142
+ header.forEach((h, i) => {
143
+ const value = cellValue(r[i] ?? '');
144
+ if (value === undefined || !h) return;
145
+ if (keys[i]) c[keys[i]] = keys[i] === 'name' || keys[i] === 'email' ? String(r[i]).trim() : String(value);
146
+ else attributes[h] = value;
147
+ });
148
+ if (Object.keys(attributes).length) c.attributes = attributes;
149
+ return c;
150
+ });
151
+ }
152
+
153
+ /** Contacts from a file on disk. */
154
+ export function contactsFromFile(path) {
155
+ let text;
156
+ try {
157
+ text = readFileSync(path, 'utf8');
158
+ } catch (e) {
159
+ throw apiError(400, `Couldn't read ${path}: ${e.code === 'ENOENT' ? 'no such file' : e.message}.`);
160
+ }
161
+ return contactsFromText(text, path);
162
+ }
163
+
164
+ // ── Reading a file of events ───────────────────────────────────────────────────────────────────────
165
+
166
+ const EVENT_TOP = {
167
+ name: 'name',
168
+ event: 'name',
169
+ externalid: 'externalId',
170
+ external_id: 'externalId',
171
+ user_id: 'externalId',
172
+ email: 'email',
173
+ anonymousid: 'anonymousId',
174
+ anonymous_id: 'anonymousId',
175
+ timestamp: 'timestamp',
176
+ occurred_at: 'timestamp',
177
+ id: 'id',
178
+ event_id: 'id',
179
+ };
180
+
181
+ /**
182
+ * Events from a file's text: JSON (a list, `{ "events": [...] }`, or one event) or CSV with a header
183
+ * row. In a CSV, `name` (or `event`), `external_id`, `email`, `anonymous_id`, `timestamp` and `id`
184
+ * (the event's own id, so sending the file twice records nothing twice) are the event's fields, and
185
+ * every other column is a property, its header the key.
186
+ */
187
+ export function eventsFromText(text, filename = '') {
188
+ const s = String(text ?? '').trim();
189
+ if (!s) throw apiError(400, 'The file is empty.');
190
+ const json = /\.json$/i.test(filename) || s.startsWith('[') || s.startsWith('{');
191
+ if (json) {
192
+ let parsed;
193
+ try {
194
+ parsed = JSON.parse(s);
195
+ } catch (e) {
196
+ throw apiError(400, `The file is not valid JSON: ${e.message}`);
197
+ }
198
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.events) ? parsed.events : [parsed];
199
+ if (!list.length) throw apiError(400, 'The file holds no events.');
200
+ return list;
201
+ }
202
+ const rows = parseCsv(s);
203
+ if (rows.length < 2) throw apiError(400, 'A CSV needs a header row and at least one event.');
204
+ const header = rows[0].map((h) => h.trim());
205
+ const keys = header.map((h) => EVENT_TOP[h.toLowerCase()] ?? null);
206
+ if (!keys.includes('name')) throw apiError(400, 'A CSV of events needs a name (or event) column.');
207
+ return rows.slice(1).map((r) => {
208
+ const e = {};
209
+ const properties = {};
210
+ header.forEach((h, i) => {
211
+ const raw = String(r[i] ?? '').trim();
212
+ if (raw === '' || !h) return;
213
+ if (keys[i]) e[keys[i]] = raw;
214
+ else properties[h] = cellValue(raw);
215
+ });
216
+ if (Object.keys(properties).length) e.properties = properties;
217
+ return e;
218
+ });
219
+ }
220
+
221
+ /** Events from a file on disk. */
222
+ export function eventsFromFile(path) {
223
+ let text;
224
+ try {
225
+ text = readFileSync(path, 'utf8');
226
+ } catch (e) {
227
+ throw apiError(400, `Couldn't read ${path}: ${e.code === 'ENOENT' ? 'no such file' : e.message}.`);
228
+ }
229
+ return eventsFromText(text, path);
230
+ }
231
+
232
+ // ── Contacts ──────────────────────────────────────────────────────────────────────────────────────
233
+
234
+ /**
235
+ * Newest seen first, 50 a page. `q` matches a name, an email or an external id; `segment` (an id or
236
+ * a name) keeps that segment's members.
237
+ */
238
+ export async function listContacts(call, { workspace, q, offset, limit, segment } = {}) {
239
+ const ws = await resolveWorkspace(call, workspace);
240
+ const qs = new URLSearchParams();
241
+ if (q) qs.set('q', String(q));
242
+ if (segment !== undefined && segment !== null && segment !== '')
243
+ qs.set('segment', String(await resolveSegment(call, ws, segment)));
244
+ if (offset) qs.set('offset', String(offset));
245
+ if (limit) qs.set('limit', String(limit));
246
+ const res = await call(`${base(ws)}/contacts${qs.size ? `?${qs}` : ''}`);
247
+ return { workspace: ws, ...res };
248
+ }
249
+
250
+ /** One contact by its id, e:<email>, c:<id>, x:<externalId>, or an email. */
251
+ export async function getContact(call, { workspace, contact }) {
252
+ const ref = String(contact ?? '').trim();
253
+ if (!ref) throw apiError(400, 'Name the contact: its id, its email, or x:<external id>.');
254
+ const ws = await resolveWorkspace(call, workspace);
255
+ const res = await call(`${base(ws)}/contacts/${encodeURIComponent(ref)}`);
256
+ return { workspace: ws, ...res };
257
+ }
258
+
259
+ /**
260
+ * Identify one contact or many. One goes to `contacts/identify`; more go to `contacts/identify/batch`
261
+ * in batches of 100, each item its own upsert, and the outcomes are added up with each item's index
262
+ * in the whole list.
263
+ */
264
+ export async function identifyContacts(call, { workspace, contacts, via }) {
265
+ const list = Array.isArray(contacts) ? contacts : contacts ? [contacts] : [];
266
+ if (!list.length) throw apiError(400, 'Give at least one contact: {"email": "ada@example.com"}.');
267
+ const ws = await resolveWorkspace(call, workspace);
268
+ if (list.length === 1) {
269
+ const res = await call(`${base(ws)}/contacts/identify${viaQuery(via)}`, { method: 'POST', body: list[0] });
270
+ return {
271
+ workspace: ws,
272
+ results: [{ index: 0, ok: true, ...res }],
273
+ created: res.created ? 1 : 0,
274
+ updated: !res.created && res.changed ? 1 : 0,
275
+ unchanged: res.changed ? 0 : 1,
276
+ failed: 0,
277
+ };
278
+ }
279
+ const out = { workspace: ws, results: [], created: 0, updated: 0, unchanged: 0, failed: 0 };
280
+ for (let at = 0; at < list.length; at += BATCH_SIZE) {
281
+ const chunk = list.slice(at, at + BATCH_SIZE);
282
+ const res = await call(`${base(ws)}/contacts/identify/batch${viaQuery(via)}`, {
283
+ method: 'POST',
284
+ body: { contacts: chunk },
285
+ });
286
+ for (const r of res.results ?? [])
287
+ out.results.push({
288
+ ...r,
289
+ index: r.index + at,
290
+ // The api names the field within this batch; say where it is in the whole list.
291
+ ...(r.field ? { field: r.field.replace(/^contacts\[(\d+)\]/, (_, i) => `contacts[${Number(i) + at}]`) } : {}),
292
+ ...(r.message
293
+ ? { message: r.message.replace(/^contacts\[(\d+)\]/, (_, i) => `contacts[${Number(i) + at}]`) }
294
+ : {}),
295
+ });
296
+ out.created += res.created ?? 0;
297
+ out.updated += res.updated ?? 0;
298
+ out.unchanged += res.unchanged ?? 0;
299
+ out.failed += res.failed ?? 0;
300
+ }
301
+ return out;
302
+ }
303
+
304
+ // ── Attributes ────────────────────────────────────────────────────────────────────────────────────
305
+
306
+ export async function listAttributes(call, { workspace } = {}) {
307
+ const ws = await resolveWorkspace(call, workspace);
308
+ const res = await call(`${base(ws)}/contact-attributes`);
309
+ return { workspace: ws, ...res };
310
+ }
311
+
312
+ /** Define an attribute. Safe to repeat with the same type. */
313
+ export async function defineAttribute(call, { workspace, key, type, label }) {
314
+ const k = String(key ?? '').trim();
315
+ if (!k) throw apiError(400, 'Give the attribute a key: lower-case letters, digits and underscores.');
316
+ const t = String(type ?? '').trim().toLowerCase();
317
+ if (!ATTRIBUTE_TYPES.includes(t)) throw apiError(400, `type is one of ${ATTRIBUTE_TYPES.join(', ')}.`);
318
+ const ws = await resolveWorkspace(call, workspace);
319
+ const body = { key: k, type: t };
320
+ if (label !== undefined && label !== null && label !== '') body.label = String(label);
321
+ const res = await call(`${base(ws)}/contact-attributes`, { method: 'POST', body });
322
+ return { workspace: ws, ...res };
323
+ }
324
+
325
+ /** Rename an attribute's label, or archive or restore it. */
326
+ export async function updateAttribute(call, { workspace, key, label, archived }) {
327
+ const k = String(key ?? '').trim();
328
+ if (!k) throw apiError(400, 'Name the attribute by its key.');
329
+ const body = {};
330
+ if (label !== undefined && label !== null && label !== '') body.label = String(label);
331
+ if (archived !== undefined && archived !== null) body.archived = archived === true || archived === 'true';
332
+ if (!Object.keys(body).length) throw apiError(400, 'Give a new --label, or --archive or --restore.');
333
+ const ws = await resolveWorkspace(call, workspace);
334
+ const res = await call(`${base(ws)}/contact-attributes/${encodeURIComponent(k)}`, { method: 'PATCH', body });
335
+ return { workspace: ws, ...res };
336
+ }
337
+
338
+ // ── Events ────────────────────────────────────────────────────────────────────────────────────────
339
+
340
+ /**
341
+ * Send one event or many. One goes to `contacts/track`; more go to `contacts/track/batch` in batches
342
+ * of 100, each recorded on its own, and the outcomes are added up with each event's index in the
343
+ * whole list.
344
+ */
345
+ export async function trackEvents(call, { workspace, events }) {
346
+ const list = Array.isArray(events) ? events : events ? [events] : [];
347
+ if (!list.length) throw apiError(400, 'Give at least one event: {"name": "signed_up", "externalId": "u_1"}.');
348
+ const ws = await resolveWorkspace(call, workspace);
349
+ if (list.length === 1) {
350
+ const res = await call(`${base(ws)}/contacts/track`, { method: 'POST', body: list[0] });
351
+ return {
352
+ workspace: ws,
353
+ results: [{ index: 0, ok: true, ...res }],
354
+ recorded: res.duplicate ? 0 : 1,
355
+ anonymous: !res.duplicate && res.anonymous ? 1 : 0,
356
+ duplicates: res.duplicate ? 1 : 0,
357
+ failed: 0,
358
+ };
359
+ }
360
+ const out = { workspace: ws, results: [], recorded: 0, anonymous: 0, duplicates: 0, failed: 0 };
361
+ const shift = (s, at) => s.replace(/^events\[(\d+)\]/, (_, i) => `events[${Number(i) + at}]`);
362
+ for (let at = 0; at < list.length; at += BATCH_SIZE) {
363
+ const chunk = list.slice(at, at + BATCH_SIZE);
364
+ const res = await call(`${base(ws)}/contacts/track/batch`, { method: 'POST', body: { events: chunk } });
365
+ for (const r of res.results ?? [])
366
+ out.results.push({
367
+ ...r,
368
+ index: r.index + at,
369
+ ...(r.field ? { field: shift(r.field, at) } : {}),
370
+ ...(r.message ? { message: shift(r.message, at) } : {}),
371
+ });
372
+ out.recorded += res.recorded ?? 0;
373
+ out.anonymous += res.anonymous ?? 0;
374
+ out.duplicates += res.duplicates ?? 0;
375
+ out.failed += res.failed ?? 0;
376
+ }
377
+ return out;
378
+ }
379
+
380
+ /** A contact's counts by event name and its latest events (`name` narrows them to one). */
381
+ export async function contactEvents(call, { workspace, contact, name, offset, limit }) {
382
+ const ref = String(contact ?? '').trim();
383
+ if (!ref) throw apiError(400, 'Name the contact: its id, its email, or x:<external id>.');
384
+ const ws = await resolveWorkspace(call, workspace);
385
+ const qs = new URLSearchParams();
386
+ if (name) qs.set('name', String(name));
387
+ if (offset) qs.set('offset', String(offset));
388
+ if (limit) qs.set('limit', String(limit));
389
+ const res = await call(`${base(ws)}/contacts/${encodeURIComponent(ref)}/events${qs.size ? `?${qs}` : ''}`);
390
+ return { workspace: ws, ...res };
391
+ }
392
+
393
+ export async function listEventNames(call, { workspace } = {}) {
394
+ const ws = await resolveWorkspace(call, workspace);
395
+ const res = await call(`${base(ws)}/contact-event-names`);
396
+ return { workspace: ws, ...res };
397
+ }
398
+
399
+ /** Rename an event name's label, or archive or restore it. */
400
+ export async function updateEventName(call, { workspace, name, label, archived }) {
401
+ const n = String(name ?? '').trim();
402
+ if (!n) throw apiError(400, 'Name the event, such as order.completed.');
403
+ const body = {};
404
+ if (label !== undefined && label !== null && label !== '') body.label = String(label);
405
+ if (archived !== undefined && archived !== null) body.archived = archived === true || archived === 'true';
406
+ if (!Object.keys(body).length) throw apiError(400, 'Give a new label, or archive or restore it.');
407
+ const ws = await resolveWorkspace(call, workspace);
408
+ const res = await call(`${base(ws)}/contact-event-names/${encodeURIComponent(n)}`, { method: 'PATCH', body });
409
+ return { workspace: ws, ...res };
410
+ }
411
+
412
+ // ── API keys ──────────────────────────────────────────────────────────────────────────────────────
413
+
414
+ export async function listKeys(call, { workspace } = {}) {
415
+ const ws = await resolveWorkspace(call, workspace);
416
+ const res = await call(`${base(ws)}/api-keys`);
417
+ return { workspace: ws, ...res };
418
+ }
419
+
420
+ /** A new server key. Its secret is in this answer only. */
421
+ export async function createKey(call, { workspace, name }) {
422
+ const n = String(name ?? '').trim();
423
+ if (!n) throw apiError(400, 'Name the key for where it is used, such as "Production server".');
424
+ const ws = await resolveWorkspace(call, workspace);
425
+ const res = await call(`${base(ws)}/api-keys`, { method: 'POST', body: { name: n } });
426
+ return { workspace: ws, ...res };
427
+ }
428
+
429
+ /** Revoke a key, by its id, its prefix (wsk_AbCdEf) or its name. */
430
+ export async function revokeKey(call, { workspace, key }) {
431
+ const ref = String(key ?? '').trim();
432
+ if (!ref) throw apiError(400, 'Name the key: its id, its prefix (wsk_...) or its name.');
433
+ const ws = await resolveWorkspace(call, workspace);
434
+ const { keys = [] } = await call(`${base(ws)}/api-keys`);
435
+ const live = keys.filter((k) => !k.revokedAt);
436
+ const hits = [
437
+ ...keys.filter((k) => String(k.id) === ref),
438
+ ...live.filter((k) => k.prefix === ref || ref.startsWith(k.prefix)),
439
+ ...live.filter((k) => k.name.toLowerCase() === ref.toLowerCase()),
440
+ ];
441
+ const unique = [...new Map(hits.map((k) => [k.id, k])).values()];
442
+ if (!unique.length) throw apiError(404, `There is no API key "${ref}". \`workover contacts keys\` lists them.`);
443
+ if (unique.length > 1)
444
+ throw apiError(400, `"${ref}" names ${unique.length} keys; revoke one by its id: ${unique.map((k) => k.id).join(', ')}.`);
445
+ const res = await call(`${base(ws)}/api-keys/${unique[0].id}`, { method: 'DELETE' });
446
+ return { workspace: ws, ...res };
447
+ }
448
+
449
+ // ── Segments ──────────────────────────────────────────────────────────────────────────────────────
450
+
451
+ /** The most contacts one add or remove call takes; a longer list is sent in calls of this size. */
452
+ export const MEMBER_BATCH = 1000;
453
+
454
+ /** The definition language, for an agent building a segment (and the MCP tools' descriptions). */
455
+ export const DEFINITION_HELP =
456
+ 'A definition is {"match": "all"|"any", "filters": [...], "groups": [{"match", "filters"}]}: one level of groups, ' +
457
+ 'at most 10 filters in a group and 20 in all; no filters matches everyone. Filters: ' +
458
+ '{"type":"attribute","key":"plan","op":"is","value":"pro"} (text ops: is, is_not, contains, not_contains, starts_with, is_set, not_set; ' +
459
+ 'number: eq, neq, gt, lt, between [min,max], is_set, not_set; boolean: is_true, is_false, is_set, not_set; ' +
460
+ 'date: before, after, on "YYYY-MM-DD", in_last_days, more_than_days_ago, in_next_days N, is_set, not_set); ' +
461
+ '{"type":"field","field":"email"|"name"|"externalId"|"createdAt"|"lastSeenAt"|"hasEmail","op":...} (createdAt is first seen; hasEmail takes is_true or is_false); ' +
462
+ '{"type":"event","name":"order.completed","op":"did"|"did_not"|"at_least"|"at_most"|"exactly","count":3,"withinDays":30} (withinDays left out is ever); ' +
463
+ '{"type":"segment","segmentId":12,"op":"in"|"not_in"}; ' +
464
+ '{"type":"topic","key":"newsletter","op":"subscribed"|"not_subscribed"} (subscribed means an address, not unsubscribed from all, a live topic, and their choice or else the topic default; the field "unsubscribedAll" takes is_true or is_false). Text compares ignore case; is_not, not_contains and neq also match people without the value. ' +
465
+ 'Attribute keys and event names must exist (workover_contacts_attributes, workover_contacts_event_names) and not be archived.';
466
+
467
+ /** A definition, or `{name, kind, definition}`, from a JSON file. */
468
+ export function definitionFromFile(path) {
469
+ let text;
470
+ try {
471
+ text = readFileSync(path, 'utf8');
472
+ } catch (e) {
473
+ throw apiError(400, `Could not read ${path}: ${e.message}`);
474
+ }
475
+ try {
476
+ return JSON.parse(text);
477
+ } catch {
478
+ throw apiError(400, `${path} is not valid JSON.`);
479
+ }
480
+ }
481
+
482
+ /** A segment by its id or its name (any case); archived ones are found too. */
483
+ export async function resolveSegment(call, ws, ref) {
484
+ const r = String(ref ?? '').trim();
485
+ if (!r) throw apiError(400, 'Name the segment: its id or its name.');
486
+ if (/^\d+$/.test(r)) return Number(r);
487
+ const { segments = [] } = await call(`${base(ws)}/contact-segments?archived=true`);
488
+ const hits = segments.filter((s) => s.name.toLowerCase() === r.toLowerCase());
489
+ const live = hits.filter((s) => !s.archived);
490
+ const pick = live.length ? live : hits;
491
+ if (!pick.length) throw apiError(404, `There is no segment "${r}". \`workover contacts segments\` lists them.`);
492
+ if (pick.length > 1)
493
+ throw apiError(400, `"${r}" names ${pick.length} segments; use its id: ${pick.map((s) => s.id).join(', ')}.`);
494
+ return pick[0].id;
495
+ }
496
+
497
+ export async function listSegments(call, { workspace, archived } = {}) {
498
+ const ws = await resolveWorkspace(call, workspace);
499
+ const res = await call(`${base(ws)}/contact-segments${archived ? '?archived=true' : ''}`);
500
+ return { workspace: ws, ...res };
501
+ }
502
+
503
+ export async function getSegment(call, { workspace, segment }) {
504
+ const ws = await resolveWorkspace(call, workspace);
505
+ const id = await resolveSegment(call, ws, segment);
506
+ const res = await call(`${base(ws)}/contact-segments/${id}`);
507
+ return { workspace: ws, ...res };
508
+ }
509
+
510
+ /** A new segment: dynamic with a definition, or manual. Owners and admins. */
511
+ export async function createSegment(call, { workspace, name, kind, definition }) {
512
+ const n = String(name ?? '').trim();
513
+ if (!n) throw apiError(400, 'Name the segment, such as "Pro users".');
514
+ const k = kind ? String(kind).trim().toLowerCase() : definition ? 'dynamic' : 'manual';
515
+ if (!['dynamic', 'manual'].includes(k)) throw apiError(400, 'kind is dynamic or manual.');
516
+ if (k === 'dynamic' && !definition) throw apiError(400, 'A dynamic segment needs a definition (--file def.json).');
517
+ const ws = await resolveWorkspace(call, workspace);
518
+ const body = { name: n, kind: k, ...(k === 'dynamic' ? { definition } : {}) };
519
+ const res = await call(`${base(ws)}/contact-segments`, { method: 'POST', body });
520
+ return { workspace: ws, ...res };
521
+ }
522
+
523
+ /** Rename, change the rules, or archive or restore. Owners and admins. */
524
+ export async function updateSegment(call, { workspace, segment, name, definition, archived }) {
525
+ const body = {};
526
+ if (name !== undefined && name !== null && name !== '') body.name = String(name);
527
+ if (definition !== undefined && definition !== null) body.definition = definition;
528
+ if (archived !== undefined && archived !== null) body.archived = archived === true || archived === 'true';
529
+ if (!Object.keys(body).length) throw apiError(400, 'Give a new --name, a --file with the rules, or archive or restore it.');
530
+ const ws = await resolveWorkspace(call, workspace);
531
+ const id = await resolveSegment(call, ws, segment);
532
+ const res = await call(`${base(ws)}/contact-segments/${id}`, { method: 'PATCH', body });
533
+ return { workspace: ws, ...res };
534
+ }
535
+
536
+ /** Who a definition matches, without saving it: the count and the first 20. */
537
+ export async function previewSegment(call, { workspace, definition, segment }) {
538
+ if (!definition || typeof definition !== 'object') throw apiError(400, 'Give a definition to preview.');
539
+ const ws = await resolveWorkspace(call, workspace);
540
+ const body = { definition };
541
+ if (segment !== undefined && segment !== null && segment !== '') body.segmentId = await resolveSegment(call, ws, segment);
542
+ const res = await call(`${base(ws)}/contact-segments/preview`, { method: 'POST', body });
543
+ return { workspace: ws, ...res };
544
+ }
545
+
546
+ export async function segmentMembers(call, { workspace, segment, offset, limit }) {
547
+ const ws = await resolveWorkspace(call, workspace);
548
+ const id = await resolveSegment(call, ws, segment);
549
+ const qs = new URLSearchParams();
550
+ if (offset) qs.set('offset', String(offset));
551
+ if (limit) qs.set('limit', String(limit));
552
+ const res = await call(`${base(ws)}/contact-segments/${id}/members${qs.size ? `?${qs}` : ''}`);
553
+ return { workspace: ws, ...res };
554
+ }
555
+
556
+ /**
557
+ * Add contacts to a manual segment or take them out, 1,000 a call. Safe to repeat: someone already
558
+ * in (or out) is not counted.
559
+ */
560
+ export async function changeSegmentMembers(call, { workspace, segment, contacts, remove = false }) {
561
+ const list = (Array.isArray(contacts) ? contacts : contacts ? [contacts] : [])
562
+ .map((c) => String(c).trim())
563
+ .filter(Boolean);
564
+ if (!list.length) throw apiError(400, 'Name at least one contact: an id, an email, or x:<external id>.');
565
+ const ws = await resolveWorkspace(call, workspace);
566
+ const id = await resolveSegment(call, ws, segment);
567
+ const out = { workspace: ws, segmentId: id, removed: remove, changed: 0, notFound: [], memberCount: 0 };
568
+ for (let at = 0; at < list.length; at += MEMBER_BATCH) {
569
+ const res = await call(`${base(ws)}/contact-segments/${id}/members${remove ? '/remove' : ''}`, {
570
+ method: 'POST',
571
+ body: { contacts: list.slice(at, at + MEMBER_BATCH) },
572
+ });
573
+ out.changed += res.changed ?? 0;
574
+ out.notFound.push(...(res.notFound ?? []));
575
+ out.memberCount = res.memberCount ?? out.memberCount;
576
+ }
577
+ return out;
578
+ }
579
+
580
+ /**
581
+ * Contacts as CSV: a segment's members, or everyone. `out`: a new .csv file to write it to (an
582
+ * existing file is never overwritten); without it the CSV comes back as `csv`. Owners and admins.
583
+ */
584
+ export async function exportContacts(call, { workspace, segment, out } = {}) {
585
+ const ws = await resolveWorkspace(call, workspace);
586
+ const id = segment === undefined || segment === null || segment === '' ? null : await resolveSegment(call, ws, segment);
587
+ if (out) {
588
+ if (!/\.csv$/i.test(String(out))) throw apiError(400, 'Write the export to a .csv file.');
589
+ if (existsSync(out)) throw apiError(400, `${out} already exists; choose a new file name.`);
590
+ }
591
+ const csv = await call(id === null ? `${base(ws)}/contacts-export` : `${base(ws)}/contact-segments/${id}/export`, {
592
+ raw: true,
593
+ });
594
+ const text = typeof csv === 'string' ? csv : '';
595
+ const rows = Math.max(0, text.split('\r\n').filter(Boolean).length - 1);
596
+ if (out) writeFileSync(out, text, { flag: 'wx' });
597
+ return { workspace: ws, segmentId: id, rows, ...(out ? { file: String(out) } : { csv: text }) };
598
+ }
599
+
600
+ // ── Topics, subscriptions and consent ─────────────────────────────────────────────────────────────
601
+
602
+ export const TOPIC_DEFAULTS = ['opt_in', 'opt_out'];
603
+
604
+ const contactRef = (contact) => {
605
+ const ref = String(contact ?? '').trim();
606
+ if (!ref) throw apiError(400, 'Name the contact: its id, its email, or x:<external id>.');
607
+ return encodeURIComponent(ref);
608
+ };
609
+
610
+ export async function listTopics(call, { workspace } = {}) {
611
+ const ws = await resolveWorkspace(call, workspace);
612
+ const res = await call(`${base(ws)}/contact-topics`);
613
+ return { workspace: ws, ...res };
614
+ }
615
+
616
+ /** A new topic. Owners and admins. */
617
+ export async function createTopic(call, { workspace, key, name, description, default: dflt }) {
618
+ if (!key) throw apiError(400, 'Give the topic a key, such as newsletter.');
619
+ if (!TOPIC_DEFAULTS.includes(dflt))
620
+ throw apiError(400, 'default is opt_in (only after a yes) or opt_out (subscribed until they say no).');
621
+ const ws = await resolveWorkspace(call, workspace);
622
+ const body = { key: String(key), name: String(name ?? '').trim() || String(key), default: dflt };
623
+ if (description) body.description = String(description);
624
+ const res = await call(`${base(ws)}/contact-topics`, { method: 'POST', body });
625
+ return { workspace: ws, created: true, ...res };
626
+ }
627
+
628
+ /** Rename, describe, change the default, or archive or restore. Owners and admins. */
629
+ export async function updateTopic(call, { workspace, key, name, description, default: dflt, archived }) {
630
+ if (!key) throw apiError(400, 'Name the topic by its key.');
631
+ const body = {};
632
+ if (name !== undefined && name !== null && name !== '') body.name = String(name);
633
+ if (description !== undefined && description !== null) body.description = String(description);
634
+ if (dflt !== undefined && dflt !== null && dflt !== '') {
635
+ if (!TOPIC_DEFAULTS.includes(dflt)) throw apiError(400, 'default is opt_in or opt_out.');
636
+ body.default = dflt;
637
+ }
638
+ if (archived !== undefined && archived !== null) body.archived = archived === true || archived === 'true';
639
+ if (!Object.keys(body).length) throw apiError(400, 'Give a new --name, --description or --default, or archive or restore it.');
640
+ const ws = await resolveWorkspace(call, workspace);
641
+ const res = await call(`${base(ws)}/contact-topics/${encodeURIComponent(String(key))}`, { method: 'PATCH', body });
642
+ return { workspace: ws, ...res };
643
+ }
644
+
645
+ /** Every live topic's key once, in the new order. */
646
+ export async function reorderTopics(call, { workspace, keys }) {
647
+ const list = (Array.isArray(keys) ? keys : []).map((k) => String(k).trim()).filter(Boolean);
648
+ if (!list.length) throw apiError(400, 'Give every live topic key in the order you want.');
649
+ const ws = await resolveWorkspace(call, workspace);
650
+ const res = await call(`${base(ws)}/contact-topics/reorder`, { method: 'POST', body: { keys: list } });
651
+ return { workspace: ws, ...res };
652
+ }
653
+
654
+ /** Replace the workspace's link secret: every preference and unsubscribe link already sent stops working. */
655
+ export async function resetPreferenceLinks(call, { workspace } = {}) {
656
+ const ws = await resolveWorkspace(call, workspace);
657
+ const res = await call(`${base(ws)}/contact-topics/reset-links`, { method: 'POST', body: {} });
658
+ return { workspace: ws, ...res };
659
+ }
660
+
661
+ export async function getSubscriptions(call, { workspace, contact }) {
662
+ const ref = contactRef(contact);
663
+ const ws = await resolveWorkspace(call, workspace);
664
+ const res = await call(`${base(ws)}/contacts/${ref}/subscriptions`);
665
+ return { workspace: ws, ...res };
666
+ }
667
+
668
+ /**
669
+ * `topics` is {key: true|false}; `unsubscribedAll` true or false. Each change is logged with the
670
+ * person as the actor. Owners and admins.
671
+ */
672
+ export async function setSubscriptions(call, { workspace, contact, topics, unsubscribedAll, consent, via }) {
673
+ const ref = contactRef(contact);
674
+ const body = {};
675
+ if (topics && Object.keys(topics).length) body.topics = topics;
676
+ if (unsubscribedAll === true || unsubscribedAll === false) body.unsubscribedAll = unsubscribedAll;
677
+ if (consent && typeof consent === 'object') body.consent = consent;
678
+ if (!body.topics && body.unsubscribedAll === undefined)
679
+ throw apiError(400, 'Give at least one --set key=on|off, or --unsubscribe-all or --resubscribe-all.');
680
+ const ws = await resolveWorkspace(call, workspace);
681
+ const res = await call(`${base(ws)}/contacts/${ref}/subscriptions${viaQuery(via)}`, { method: 'PUT', body });
682
+ return { workspace: ws, ...res };
683
+ }
684
+
685
+ /** `key=on|off` pairs as {key: true|false}. */
686
+ export function topicChoices(pairs) {
687
+ const out = {};
688
+ for (const raw of pairs ?? []) {
689
+ const m = /^([a-z][a-z0-9_]{0,49})=(on|off|true|false|yes|no)$/i.exec(String(raw).trim());
690
+ if (!m) throw apiError(400, `--set takes key=on or key=off, such as newsletter=on; got "${raw}".`);
691
+ out[m[1]] = /^(on|true|yes)$/i.test(m[2]);
692
+ }
693
+ return out;
694
+ }
695
+
696
+ export async function contactConsent(call, { workspace, contact, offset, limit }) {
697
+ const ref = contactRef(contact);
698
+ const ws = await resolveWorkspace(call, workspace);
699
+ const qs = new URLSearchParams();
700
+ if (offset) qs.set('offset', String(offset));
701
+ if (limit) qs.set('limit', String(limit));
702
+ const res = await call(`${base(ws)}/contacts/${ref}/consent${qs.size ? `?${qs}` : ''}`);
703
+ return { workspace: ws, ...res };
704
+ }
705
+
706
+ /** The contact's signed preference link (and one-click link for a topic), for support. Owners and admins. */
707
+ export async function preferencesLink(call, { workspace, contact, topic }) {
708
+ const ref = contactRef(contact);
709
+ const ws = await resolveWorkspace(call, workspace);
710
+ const qs = topic ? `?topic=${encodeURIComponent(String(topic))}` : '';
711
+ const res = await call(`${base(ws)}/contacts/${ref}/preferences-link${qs}`);
712
+ return { workspace: ws, ...res };
713
+ }
714
+
715
+ // ── Renderers ─────────────────────────────────────────────────────────────────────────────────────
716
+
717
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
718
+ const show = (v) => (typeof v === 'string' ? v : JSON.stringify(v));
719
+
720
+ export function renderContactLine(c) {
721
+ const who = c.name ? `${c.name} ` : '';
722
+ const ids = [c.email, c.externalId ? `x:${c.externalId}` : null].filter(Boolean).join(' ');
723
+ return ` ${c.id} ${who}${ids}`;
724
+ }
725
+
726
+ export function renderContacts(res) {
727
+ const out = [''];
728
+ const list = res.contacts ?? [];
729
+ if (!list.length) out.push(' No contacts yet.');
730
+ else out.push(` Contacts (${list.length} of ${res.total}):`, ...list.map(renderContactLine));
731
+ if (res.nextOffset !== null && res.nextOffset !== undefined) out.push('', ` More: --offset ${res.nextOffset}`);
732
+ out.push('');
733
+ return out;
734
+ }
735
+
736
+ export function renderContact(res) {
737
+ const c = res.contact;
738
+ const out = ['', ` ${c.name ?? c.email ?? c.externalId} (id ${c.id}, ${c.key})`];
739
+ if (c.email) out.push(` Email: ${c.email}`);
740
+ if (c.externalId) out.push(` External id: ${c.externalId}`);
741
+ out.push(` First seen: ${c.firstSeenAt} Last seen: ${c.lastSeenAt}`);
742
+ const attrs = res.attributes ?? [];
743
+ if (attrs.length) {
744
+ out.push(' Attributes:');
745
+ for (const a of attrs) out.push(` ${a.label} (${a.key}, ${a.type}): ${show(a.value)}`);
746
+ }
747
+ if (res.linkedVisitors) out.push(` Messenger visitors: ${res.linkedVisitors}`);
748
+ out.push('');
749
+ return out;
750
+ }
751
+
752
+ export function renderIdentified(res) {
753
+ const out = [
754
+ '',
755
+ ` ✓ ${plural(res.created, 'created', 'created')}, ${res.updated} updated, ${res.unchanged} unchanged${res.failed ? `, ${res.failed} failed` : ''}.`,
756
+ ];
757
+ const ok = (res.results ?? []).filter((r) => r.ok);
758
+ if (ok.length === 1 && res.results.length === 1) out.push(renderContactLine(ok[0].contact));
759
+ for (const r of (res.results ?? []).filter((x) => !x.ok)) out.push(` ✗ ${r.message}`);
760
+ out.push('');
761
+ return out;
762
+ }
763
+
764
+ export function renderAttributeLine(a) {
765
+ return ` ${a.key} ${a.label} (${a.type}; ${plural(a.used ?? 0, 'contact', 'contacts')}${a.archived ? '; archived' : ''})`;
766
+ }
767
+
768
+ export function renderAttributes(res) {
769
+ const out = [''];
770
+ const list = res.attributes ?? [];
771
+ if (!list.length) out.push(' No contact attributes yet. Identifying a contact with attributes defines them.');
772
+ else out.push(` Contact attributes (${list.length} of ${res.max ?? 1000}):`, ...list.map(renderAttributeLine));
773
+ if (res.canManage === false) out.push('', ' Only workspace owners and admins change contact attributes.');
774
+ out.push('');
775
+ return out;
776
+ }
777
+
778
+ export function renderAttributeSaved(res) {
779
+ const verb = res.created ? 'Defined' : res.changed ? 'Saved' : 'Already so';
780
+ return ['', ` ✓ ${verb}:`, renderAttributeLine(res.attribute), ''];
781
+ }
782
+
783
+ export function renderKeyLine(k) {
784
+ const state = k.revokedAt ? 'revoked' : k.lastUsedAt ? `last used ${k.lastUsedAt}` : 'never used';
785
+ return ` ${k.id} ${k.prefix}... ${k.name} (${state})`;
786
+ }
787
+
788
+ export function renderKeys(res) {
789
+ const out = [''];
790
+ const list = res.keys ?? [];
791
+ if (!list.length) out.push(' No API keys yet. `workover contacts keys create --name "Production server"` makes one.');
792
+ else out.push(' API keys:', ...list.map(renderKeyLine));
793
+ out.push('');
794
+ return out;
795
+ }
796
+
797
+ export function renderKeyCreated(res) {
798
+ return [
799
+ '',
800
+ ` ✓ Created ${res.key.name}. Its secret, shown this once:`,
801
+ '',
802
+ ` ${res.secret}`,
803
+ '',
804
+ ' Store it in your server’s environment now. Send it as `Authorization: Bearer <key>` to',
805
+ ' POST /v1/contacts/identify. Revoke it with `workover contacts keys revoke ' + res.key.id + '`.',
806
+ '',
807
+ ];
808
+ }
809
+
810
+ export function renderKeyRevoked(res) {
811
+ return ['', res.revoked ? ` ✓ Revoked ${res.key.name}. It stops working at once.` : ` ${res.key.name} was already revoked.`, ''];
812
+ }
813
+
814
+ export function renderTracked(res) {
815
+ const out = [
816
+ '',
817
+ ` ✓ ${res.recorded} recorded${res.anonymous ? ` (${res.anonymous} anonymous, attached when identified)` : ''}, ${res.duplicates} already sent${res.failed ? `, ${res.failed} failed` : ''}.`,
818
+ ];
819
+ for (const r of (res.results ?? []).filter((x) => !x.ok)) out.push(` ✗ ${r.message}`);
820
+ out.push('');
821
+ return out;
822
+ }
823
+
824
+ const props = (p) => (p && Object.keys(p).length ? ` ${JSON.stringify(p)}` : '');
825
+
826
+ export function renderContactEvents(res) {
827
+ const out = ['', ` Events of contact ${res.contact?.id} (${res.contact?.key}):`];
828
+ const names = res.names ?? [];
829
+ if (!names.length) out.push(' None yet.');
830
+ for (const n of names)
831
+ out.push(` ${n.name} ${n.label} ${plural(n.count, 'time', 'times')}, first ${n.firstAt}, last ${n.lastAt}${n.archived ? ' (archived)' : ''}`);
832
+ const events = res.events ?? [];
833
+ if (events.length) {
834
+ out.push('', ` Latest (${events.length} of ${res.total}):`);
835
+ for (const e of events)
836
+ out.push(` ${e.occurredAt} ${e.name}${e.source === 'browser' ? ' (browser)' : ''}${props(e.properties)}`);
837
+ }
838
+ if (res.nextOffset !== null && res.nextOffset !== undefined) out.push('', ` More: --offset ${res.nextOffset}`);
839
+ out.push('');
840
+ return out;
841
+ }
842
+
843
+ export function renderEventNameLine(n) {
844
+ return ` ${n.name} ${n.label} (${plural(n.count ?? 0, 'event', 'events')}${n.lastAt ? `, last ${n.lastAt}` : ''}${n.archived ? '; archived' : ''})`;
845
+ }
846
+
847
+ export function renderEventNames(res) {
848
+ const out = [''];
849
+ const list = res.names ?? [];
850
+ if (!list.length) out.push(' No events yet. `workover contacts track` or POST /v1/events sends one.');
851
+ else out.push(` Event names (${list.length} of ${res.max ?? 1000}):`, ...list.map(renderEventNameLine));
852
+ if (res.canManage === false) out.push('', ' Only workspace owners and admins change event names.');
853
+ out.push('');
854
+ return out;
855
+ }
856
+
857
+ export function renderEventNameSaved(res) {
858
+ return ['', ` ✓ ${res.changed ? 'Saved' : 'Already so'}:`, renderEventNameLine(res.eventName), ''];
859
+ }
860
+
861
+ // Segments
862
+
863
+ const filterText = (f) => {
864
+ if (!f || typeof f !== 'object') return show(f);
865
+ const v = f.value === undefined ? '' : ` ${show(f.value)}`;
866
+ if (f.type === 'attribute') return `${f.key} ${f.op}${v}`;
867
+ if (f.type === 'field') return `${f.field} ${f.op}${v}`;
868
+ if (f.type === 'event')
869
+ return `${f.op} ${f.name}${f.count !== undefined ? ` ${f.count}` : ''}${f.withinDays ? ` in the last ${f.withinDays} days` : ' ever'}`;
870
+ if (f.type === 'segment') return `${f.op === 'in' ? 'in' : 'not in'} segment ${f.segmentId}`;
871
+ if (f.type === 'topic') return `${f.op === 'subscribed' ? 'subscribed to' : 'not subscribed to'} ${f.key}`;
872
+ return show(f);
873
+ };
874
+
875
+ export function renderSegmentLine(s) {
876
+ const tag = [s.kind, s.archived ? 'archived' : null].filter(Boolean).join(', ');
877
+ return ` ${s.id} ${s.name} ${plural(s.memberCount ?? 0, 'person', 'people')} (${tag})`;
878
+ }
879
+
880
+ export function renderSegments(res) {
881
+ const out = [''];
882
+ const list = res.segments ?? [];
883
+ if (!list.length) out.push(' No segments yet. `workover contacts segments create` makes one.');
884
+ else out.push(` Segments (${list.length} of ${res.max ?? 100}):`, ...list.map(renderSegmentLine));
885
+ if (res.canManage === false) out.push('', ' Only workspace owners and admins change segments.');
886
+ out.push('');
887
+ return out;
888
+ }
889
+
890
+ export function renderSegment(res) {
891
+ const s = res.segment;
892
+ const out = ['', renderSegmentLine(s).trimStart()];
893
+ const d = s.definition;
894
+ if (d) {
895
+ out.push(` Match ${d.match === 'any' ? 'any' : 'all'} of:`);
896
+ for (const f of d.filters ?? []) out.push(` ${filterText(f)}`);
897
+ for (const g of d.groups ?? []) {
898
+ out.push(` ${g.match === 'any' ? 'any' : 'all'} of:`);
899
+ for (const f of g.filters ?? []) out.push(` ${filterText(f)}`);
900
+ }
901
+ if (!(d.filters ?? []).length && !(d.groups ?? []).length) out.push(' everyone');
902
+ }
903
+ for (const w of s.warnings ?? []) out.push(` ! ${w}`);
904
+ out.push('');
905
+ return out;
906
+ }
907
+
908
+ export function renderSegmentSaved(res) {
909
+ const t = res.transitions;
910
+ const moved = t ? ` ${t.entered} entered, ${t.left} left.` : '';
911
+ return ['', ` ✓ ${res.changed === false ? 'Already so' : 'Saved'}.${moved}`, ...renderSegment(res).slice(1)];
912
+ }
913
+
914
+ export function renderSegmentPreview(res) {
915
+ const out = ['', ` ${plural(res.count ?? 0, 'person matches', 'people match')}.`];
916
+ for (const c of res.contacts ?? []) out.push(renderContactLine(c));
917
+ if ((res.count ?? 0) > (res.contacts ?? []).length) out.push(` ...and ${res.count - res.contacts.length} more.`);
918
+ out.push('');
919
+ return out;
920
+ }
921
+
922
+ export function renderSegmentMembers(res) {
923
+ const out = ['', ` ${res.segment?.name ?? 'Segment'} (${plural(res.total ?? 0, 'person', 'people')}):`];
924
+ for (const c of res.contacts ?? []) out.push(renderContactLine(c));
925
+ if (res.nextOffset !== null && res.nextOffset !== undefined) out.push('', ` More: --offset ${res.nextOffset}`);
926
+ out.push('');
927
+ return out;
928
+ }
929
+
930
+ export function renderSegmentMembersChanged(res) {
931
+ const out = [
932
+ '',
933
+ ` ✓ ${res.changed} ${res.removed ? 'removed' : 'added'}; the segment has ${plural(res.memberCount, 'person', 'people')}.`,
934
+ ];
935
+ if (res.notFound?.length) out.push(` Not found: ${res.notFound.join(', ')}`);
936
+ out.push('');
937
+ return out;
938
+ }
939
+
940
+ export function renderExported(res) {
941
+ if (res.file) return ['', ` ✓ ${plural(res.rows, 'contact', 'contacts')} written to ${res.file}.`, ''];
942
+ return [res.csv ?? ''];
943
+ }
944
+
945
+ // Topics
946
+
947
+ const DEFAULT_LABEL = { opt_in: 'opt-in', opt_out: 'opt-out' };
948
+
949
+ export function renderTopicLine(t) {
950
+ const tag = [DEFAULT_LABEL[t.default] ?? t.default, t.archived ? 'archived' : null].filter(Boolean).join(', ');
951
+ return ` ${t.key} ${t.name} ${plural(t.subscribed ?? 0, 'subscribed', 'subscribed')} (${tag})`;
952
+ }
953
+
954
+ export function renderTopics(res) {
955
+ const out = [''];
956
+ const list = res.topics ?? [];
957
+ if (!list.length) out.push(' No topics yet. `workover contacts topics create newsletter --name "Newsletter" --default opt_in` makes one.');
958
+ else out.push(` Topics (${list.length} of ${res.max ?? 50}):`, ...list.map(renderTopicLine));
959
+ if (res.canManage === false) out.push('', ' Only workspace owners and admins change topics.');
960
+ out.push('');
961
+ return out;
962
+ }
963
+
964
+ export function renderTopicSaved(res) {
965
+ const verb = res.created ? 'Created' : res.changed === false ? 'Already so' : 'Saved';
966
+ return ['', ` ✓ ${verb}:`, renderTopicLine(res.topic), ''];
967
+ }
968
+
969
+ export function renderSubscriptions(res) {
970
+ const c = res.contact ?? {};
971
+ const out = ['', ` ${c.email ?? `Contact ${c.id}`}${c.unsubscribedAll ? ' (unsubscribed from all)' : ''}`];
972
+ if (res.changed !== undefined) out.splice(1, 0, ` ✓ ${plural(res.changed, 'change', 'changes')} saved and logged.`);
973
+ for (const t of res.topics ?? [])
974
+ out.push(
975
+ ` ${t.key} ${t.state}${t.isDefault ? ' (default)' : ''}${t.archived ? ', archived' : ''} ${t.canEmail ? 'can email' : `cannot email: ${t.blockedBy}`}`,
976
+ );
977
+ if (!(res.topics ?? []).length) out.push(' No topics yet.');
978
+ out.push('');
979
+ return out;
980
+ }
981
+
982
+ const ACTOR = (a) => (!a ? 'the contact' : a.type === 'key' ? `key ${a.name ?? a.id}` : (a.name ?? `user ${a.id}`));
983
+
984
+ export function renderConsent(res) {
985
+ const out = ['', ` Consent log (${res.total ?? 0}):`];
986
+ for (const e of res.entries ?? []) {
987
+ out.push(` ${e.at} ${e.topic ?? 'all topics'} ${e.from} -> ${e.to} via ${e.source}, by ${ACTOR(e.actor)}`);
988
+ if (e.consent) out.push(` consent: ${[e.consent.at, e.consent.source, e.consent.text].filter(Boolean).join(' · ')}`);
989
+ }
990
+ if (!(res.entries ?? []).length) out.push(' No changes yet.');
991
+ if (res.nextOffset !== null && res.nextOffset !== undefined) out.push('', ` More: --offset ${res.nextOffset}`);
992
+ out.push('');
993
+ return out;
994
+ }
995
+
996
+ export function renderPreferencesLink(res) {
997
+ return [
998
+ '',
999
+ ' Preference page (send it only to this person; it is their credential):',
1000
+ ` ${res.manageUrl}`,
1001
+ ` One-click unsubscribe${res.topic ? ` from ${res.topic}` : ' from all'}:`,
1002
+ ` ${res.unsubscribeUrl}`,
1003
+ ' Headers an email to them carries:',
1004
+ ...Object.entries(res.headers ?? {}).map(([k, v]) => ` ${k}: ${v}`),
1005
+ '',
1006
+ ];
1007
+ }
1008
+
1009
+ export function renderLinksReset(res) {
1010
+ return ['', ` ✓ Links reset${res.at ? ` at ${res.at}` : ''}. Every preference and unsubscribe link already sent stops working.`, ''];
1011
+ }
1012
+
1013
+ // ── MCP tools ─────────────────────────────────────────────────────────────────────────────────────
1014
+
1015
+ const WORKSPACE = {
1016
+ type: 'string',
1017
+ description: 'The workspace, by slug or id. Needed only when the account has more than one.',
1018
+ };
1019
+ const SCOPE =
1020
+ ' Needs a token from `workover login --contacts`; without it this returns a permission error naming that command.';
1021
+ const CONTACT = {
1022
+ type: 'object',
1023
+ description:
1024
+ 'One contact: externalId and/or email (at least one), name, and attributes (key to value: a text, a number, true/false, an ISO date, or null to remove one).',
1025
+ };
1026
+
1027
+ const EVENT = {
1028
+ type: 'object',
1029
+ description:
1030
+ 'One event: name (lower-case, such as order.completed), the person by externalId, email or anonymousId, properties (an object), timestamp (ISO 8601 or Unix time) and id (optional, for idempotency).',
1031
+ };
1032
+
1033
+ const SEGMENT = { type: 'string', description: 'The segment: its id, or its name.' };
1034
+ const DEFINITION = { type: 'object', description: 'A segment definition. ' + DEFINITION_HELP };
1035
+
1036
+ /** The MCP server's contacts tools (index.mjs lists them). */
1037
+ export const CONTACTS_TOOL_DEFS = [
1038
+ {
1039
+ name: 'workover_contacts_list',
1040
+ description:
1041
+ "The workspace's stored contacts, newest seen first, 50 a page. `q` matches a name, an email or an external id; `segment` (id or name) keeps one segment's members." +
1042
+ SCOPE,
1043
+ inputSchema: {
1044
+ type: 'object',
1045
+ properties: {
1046
+ workspace: WORKSPACE,
1047
+ q: { type: 'string' },
1048
+ segment: SEGMENT,
1049
+ offset: { type: 'number' },
1050
+ limit: { type: 'number', description: 'Up to 200.' },
1051
+ },
1052
+ },
1053
+ },
1054
+ {
1055
+ name: 'workover_contacts_get',
1056
+ description:
1057
+ 'One contact with its attributes typed by their definitions. By its id, its email, e:<email>, c:<id> or x:<external id>.' +
1058
+ SCOPE,
1059
+ inputSchema: {
1060
+ type: 'object',
1061
+ properties: { workspace: WORKSPACE, contact: { type: 'string' } },
1062
+ required: ['contact'],
1063
+ },
1064
+ },
1065
+ {
1066
+ name: 'workover_contacts_identify',
1067
+ description:
1068
+ 'Create or update contacts by externalId or email: one, a list (sent 100 at a time), or a JSON or CSV file on this machine. A new attribute key is defined with the type its value shows. Strict: a bad item is reported with the field it is about, and the rest still go in. Owners and admins. Safe to repeat.' +
1069
+ SCOPE,
1070
+ inputSchema: {
1071
+ type: 'object',
1072
+ properties: {
1073
+ workspace: WORKSPACE,
1074
+ contacts: { type: 'array', items: CONTACT },
1075
+ file: {
1076
+ type: 'string',
1077
+ description:
1078
+ 'A path to a .json (a list of contacts) or .csv (a header row: external_id, email, name, then one column per attribute).',
1079
+ },
1080
+ },
1081
+ },
1082
+ },
1083
+ {
1084
+ name: 'workover_contacts_attributes',
1085
+ description:
1086
+ 'Every attribute contacts may carry: key, label, type (string, number, boolean, date), whether archived, and how many contacts hold one.' +
1087
+ SCOPE,
1088
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
1089
+ },
1090
+ {
1091
+ name: 'workover_contacts_define_attribute',
1092
+ description:
1093
+ 'Define a contact attribute before any contact carries it. Its key and type never change. Owners and admins. Safe to repeat with the same type.' +
1094
+ SCOPE,
1095
+ inputSchema: {
1096
+ type: 'object',
1097
+ properties: {
1098
+ workspace: WORKSPACE,
1099
+ key: { type: 'string', description: 'Lower-case letters, digits and underscores, starting with a letter.' },
1100
+ type: { type: 'string', enum: ATTRIBUTE_TYPES },
1101
+ label: { type: 'string', description: 'What the team sees. Optional: made from the key.' },
1102
+ },
1103
+ required: ['key', 'type'],
1104
+ },
1105
+ },
1106
+ {
1107
+ name: 'workover_contacts_update_attribute',
1108
+ description:
1109
+ 'Rename an attribute’s label, or archive it (hidden, and refused as a new value; stored values are kept) or restore it. Owners and admins.' +
1110
+ SCOPE,
1111
+ inputSchema: {
1112
+ type: 'object',
1113
+ properties: {
1114
+ workspace: WORKSPACE,
1115
+ key: { type: 'string' },
1116
+ label: { type: 'string' },
1117
+ archived: { type: 'boolean' },
1118
+ },
1119
+ required: ['key'],
1120
+ },
1121
+ },
1122
+ {
1123
+ name: 'workover_contacts_track',
1124
+ description:
1125
+ "Send events about contacts: one, a list (sent 100 at a time), or a JSON or CSV file on this machine. Each names the person by externalId, email or anonymousId (someone not yet known), with a name such as order.completed, properties (up to 20 keys, 4 KB), an optional timestamp (up to 365 days back; an event that arrived more than 72 hours after it happened never starts a journey) and an optional id that makes a repeat record nothing. An event for someone not yet a contact is kept anonymous for 30 days and attached when they are identified. Owners and admins." +
1126
+ SCOPE,
1127
+ inputSchema: {
1128
+ type: 'object',
1129
+ properties: {
1130
+ workspace: WORKSPACE,
1131
+ events: { type: 'array', items: EVENT },
1132
+ file: {
1133
+ type: 'string',
1134
+ description:
1135
+ 'A path to a .json (a list of events) or .csv (a header row: name, external_id, email, anonymous_id, timestamp, id, then one column per property).',
1136
+ },
1137
+ },
1138
+ },
1139
+ },
1140
+ {
1141
+ name: 'workover_contacts_events',
1142
+ description:
1143
+ "One contact's events: each name with its count and first and last time, and the latest events with their properties, 20 a page. By its id, its email, e:<email>, c:<id> or x:<external id>." +
1144
+ SCOPE,
1145
+ inputSchema: {
1146
+ type: 'object',
1147
+ properties: {
1148
+ workspace: WORKSPACE,
1149
+ contact: { type: 'string' },
1150
+ name: { type: 'string', description: 'Only events of this name.' },
1151
+ offset: { type: 'number' },
1152
+ limit: { type: 'number', description: 'Up to 100.' },
1153
+ },
1154
+ required: ['contact'],
1155
+ },
1156
+ },
1157
+ {
1158
+ name: 'workover_contacts_event_names',
1159
+ description:
1160
+ 'Every event name the workspace has seen: its label, how many arrived (anonymous ones included), the last time, and whether it is archived.' +
1161
+ SCOPE,
1162
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
1163
+ },
1164
+ {
1165
+ name: 'workover_contacts_update_event_name',
1166
+ description:
1167
+ 'Rename an event name’s label, or archive it (new events of it are refused; those kept stay) or restore it. Owners and admins.' +
1168
+ SCOPE,
1169
+ inputSchema: {
1170
+ type: 'object',
1171
+ properties: {
1172
+ workspace: WORKSPACE,
1173
+ name: { type: 'string', description: 'The event name, such as order.completed.' },
1174
+ label: { type: 'string' },
1175
+ archived: { type: 'boolean' },
1176
+ },
1177
+ required: ['name'],
1178
+ },
1179
+ },
1180
+ {
1181
+ name: 'workover_contacts_keys',
1182
+ description:
1183
+ "The workspace's server API keys (wsk_...): name, prefix, who made it, last use, revoked or not. Never a secret. Owners and admins." +
1184
+ SCOPE,
1185
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
1186
+ },
1187
+ {
1188
+ name: 'workover_contacts_create_key',
1189
+ description:
1190
+ "Create a server API key for POST /v1/contacts/identify from the customer's own servers. The secret is in this answer only: hand it to the person to store in their server's environment, and never write it into a file in the repository. Owners and admins." +
1191
+ SCOPE,
1192
+ inputSchema: {
1193
+ type: 'object',
1194
+ properties: { workspace: WORKSPACE, name: { type: 'string', description: 'Where it is used, such as "Production server".' } },
1195
+ required: ['name'],
1196
+ },
1197
+ },
1198
+ {
1199
+ name: 'workover_contacts_revoke_key',
1200
+ description:
1201
+ 'Revoke a server API key by its id, prefix or name: it stops working at once. Ask the person first. Owners and admins. Safe to repeat.' +
1202
+ SCOPE,
1203
+ inputSchema: {
1204
+ type: 'object',
1205
+ properties: { workspace: WORKSPACE, key: { type: 'string' } },
1206
+ required: ['key'],
1207
+ },
1208
+ },
1209
+ {
1210
+ name: 'workover_contacts_segments',
1211
+ description:
1212
+ "The workspace's segments: id, name, kind (dynamic or manual), member count, and whether archived. `archived: true` lists archived ones too." +
1213
+ SCOPE,
1214
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, archived: { type: 'boolean' } } },
1215
+ },
1216
+ {
1217
+ name: 'workover_contacts_segment',
1218
+ description: 'One segment, by id or name: its rules, member count and warnings about archived things it uses.' + SCOPE,
1219
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, segment: SEGMENT }, required: ['segment'] },
1220
+ },
1221
+ {
1222
+ name: 'workover_contacts_segment_preview',
1223
+ description:
1224
+ 'Who a definition matches, WITHOUT saving it: the count and the first 20 people. Run this before creating or changing a segment and tell the person the count. ' +
1225
+ DEFINITION_HELP +
1226
+ SCOPE,
1227
+ inputSchema: {
1228
+ type: 'object',
1229
+ properties: {
1230
+ workspace: WORKSPACE,
1231
+ definition: DEFINITION,
1232
+ segment: { ...SEGMENT, description: 'When editing a saved segment: its id or name.' },
1233
+ },
1234
+ required: ['definition'],
1235
+ },
1236
+ },
1237
+ {
1238
+ name: 'workover_contacts_segment_create',
1239
+ description:
1240
+ 'Create a segment: dynamic (kind "dynamic" with a definition; Workover keeps its members current) or manual (kind "manual", a list people add to). Preview a dynamic one first. Owners and admins.' +
1241
+ SCOPE,
1242
+ inputSchema: {
1243
+ type: 'object',
1244
+ properties: {
1245
+ workspace: WORKSPACE,
1246
+ name: { type: 'string' },
1247
+ kind: { type: 'string', enum: ['dynamic', 'manual'] },
1248
+ definition: DEFINITION,
1249
+ },
1250
+ required: ['name'],
1251
+ },
1252
+ },
1253
+ {
1254
+ name: 'workover_contacts_segment_update',
1255
+ description:
1256
+ 'Rename a segment, change a dynamic one’s definition (preview it first), or archive (archived: true) or restore it. Archiving keeps its members as they are and stops updating them. Owners and admins.' +
1257
+ SCOPE,
1258
+ inputSchema: {
1259
+ type: 'object',
1260
+ properties: {
1261
+ workspace: WORKSPACE,
1262
+ segment: SEGMENT,
1263
+ name: { type: 'string' },
1264
+ definition: DEFINITION,
1265
+ archived: { type: 'boolean' },
1266
+ },
1267
+ required: ['segment'],
1268
+ },
1269
+ },
1270
+ {
1271
+ name: 'workover_contacts_segment_members',
1272
+ description: "A segment's members, newest seen first, 50 a page." + SCOPE,
1273
+ inputSchema: {
1274
+ type: 'object',
1275
+ properties: {
1276
+ workspace: WORKSPACE,
1277
+ segment: SEGMENT,
1278
+ offset: { type: 'number' },
1279
+ limit: { type: 'number', description: 'Up to 200.' },
1280
+ },
1281
+ required: ['segment'],
1282
+ },
1283
+ },
1284
+ {
1285
+ name: 'workover_contacts_segment_add',
1286
+ description:
1287
+ 'Add contacts to a MANUAL segment by id, email or x:<external id> (1,000 a call; more are sent in turn). Safe to repeat. Answers how many were added and the references that named nobody. Owners and admins.' +
1288
+ SCOPE,
1289
+ inputSchema: {
1290
+ type: 'object',
1291
+ properties: { workspace: WORKSPACE, segment: SEGMENT, contacts: { type: 'array', items: { type: 'string' } } },
1292
+ required: ['segment', 'contacts'],
1293
+ },
1294
+ },
1295
+ {
1296
+ name: 'workover_contacts_segment_remove',
1297
+ description: 'Take contacts out of a MANUAL segment by id, email or x:<external id>. Safe to repeat. Owners and admins.' + SCOPE,
1298
+ inputSchema: {
1299
+ type: 'object',
1300
+ properties: { workspace: WORKSPACE, segment: SEGMENT, contacts: { type: 'array', items: { type: 'string' } } },
1301
+ required: ['segment', 'contacts'],
1302
+ },
1303
+ },
1304
+ {
1305
+ name: 'workover_contacts_export',
1306
+ description:
1307
+ "Export contacts as CSV to a NEW .csv file on this machine: a segment's members, or everyone without `segment`. Columns: email, name, external_id, one per attribute, created_at, last_seen_at. It holds people's personal data: write it only where the person asked, never into a repository. Owners and admins." +
1308
+ SCOPE,
1309
+ inputSchema: {
1310
+ type: 'object',
1311
+ properties: {
1312
+ workspace: WORKSPACE,
1313
+ segment: SEGMENT,
1314
+ out: { type: 'string', description: 'The path of a new .csv file to write.' },
1315
+ },
1316
+ required: ['out'],
1317
+ },
1318
+ },
1319
+ {
1320
+ name: 'workover_contacts_topics',
1321
+ description:
1322
+ "The workspace's email topics: key, name, default (opt_in: only after a yes; opt_out: subscribed until they say no), archived, and how many contacts may be emailed on each now." +
1323
+ SCOPE,
1324
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
1325
+ },
1326
+ {
1327
+ name: 'workover_contacts_topic_create',
1328
+ description:
1329
+ 'Create an email topic. The key never changes. Use opt_in for anything people must ask for (a newsletter), opt_out for mail tied to their account. Owners and admins.' +
1330
+ SCOPE,
1331
+ inputSchema: {
1332
+ type: 'object',
1333
+ properties: {
1334
+ workspace: WORKSPACE,
1335
+ key: { type: 'string', description: 'Lower-case letters, digits and underscores, starting with a letter, up to 50.' },
1336
+ name: { type: 'string' },
1337
+ description: { type: 'string', description: 'One line the contact sees on their preference page.' },
1338
+ default: { type: 'string', enum: TOPIC_DEFAULTS },
1339
+ },
1340
+ required: ['key', 'name', 'default'],
1341
+ },
1342
+ },
1343
+ {
1344
+ name: 'workover_contacts_topic_update',
1345
+ description:
1346
+ 'Rename or describe a topic, change its default, or archive it (archived: true; hidden from the preference page and nothing is sent on it; choices are kept) or restore it. A new default moves everyone without a choice of their own. Owners and admins.' +
1347
+ SCOPE,
1348
+ inputSchema: {
1349
+ type: 'object',
1350
+ properties: {
1351
+ workspace: WORKSPACE,
1352
+ key: { type: 'string' },
1353
+ name: { type: 'string' },
1354
+ description: { type: 'string' },
1355
+ default: { type: 'string', enum: TOPIC_DEFAULTS },
1356
+ archived: { type: 'boolean' },
1357
+ },
1358
+ required: ['key'],
1359
+ },
1360
+ },
1361
+ {
1362
+ name: 'workover_contacts_topics_reorder',
1363
+ description: 'Put the live topics in a new order (the preference page shows them so): every live key once. Owners and admins.' + SCOPE,
1364
+ inputSchema: {
1365
+ type: 'object',
1366
+ properties: { workspace: WORKSPACE, keys: { type: 'array', items: { type: 'string' } } },
1367
+ required: ['keys'],
1368
+ },
1369
+ },
1370
+ {
1371
+ name: 'workover_contacts_subscriptions',
1372
+ description:
1373
+ "One contact's topics: their state (their own choice, or the default), whether a message on it may go to them now and why not, and whether they unsubscribed from all." +
1374
+ SCOPE,
1375
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, contact: { type: 'string' } }, required: ['contact'] },
1376
+ },
1377
+ {
1378
+ name: 'workover_contacts_set_subscriptions',
1379
+ description:
1380
+ "Change one contact's subscriptions: topics {key: true|false} and/or unsubscribedAll. Do this only when the person asked for it (a support request), and say what you changed. Each change is kept in the consent log with you as the actor. Owners and admins." +
1381
+ SCOPE,
1382
+ inputSchema: {
1383
+ type: 'object',
1384
+ properties: {
1385
+ workspace: WORKSPACE,
1386
+ contact: { type: 'string' },
1387
+ topics: { type: 'object', description: 'Topic key to true (subscribed) or false.' },
1388
+ unsubscribedAll: { type: 'boolean' },
1389
+ consent: {
1390
+ type: 'object',
1391
+ description: 'For a yes: {"at": ISO time, "source": "where they said it", "text": "the words they agreed to"}.',
1392
+ },
1393
+ },
1394
+ required: ['contact'],
1395
+ },
1396
+ },
1397
+ {
1398
+ name: 'workover_contacts_consent',
1399
+ description:
1400
+ "One contact's consent log, newest first: every opt-in and opt-out with its topic, from and to, source (preference_page, one_click, api, admin, import, cli, mcp), who, and any consent given." +
1401
+ SCOPE,
1402
+ inputSchema: {
1403
+ type: 'object',
1404
+ properties: {
1405
+ workspace: WORKSPACE,
1406
+ contact: { type: 'string' },
1407
+ offset: { type: 'number' },
1408
+ limit: { type: 'number', description: 'Up to 200.' },
1409
+ },
1410
+ required: ['contact'],
1411
+ },
1412
+ },
1413
+ {
1414
+ name: 'workover_contacts_preferences_link',
1415
+ description:
1416
+ "A contact's signed preference page link, their one-click unsubscribe link (for a topic, else all) and the List-Unsubscribe headers an email to them carries. The link is that person's credential: give it only to them. Owners and admins." +
1417
+ SCOPE,
1418
+ inputSchema: {
1419
+ type: 'object',
1420
+ properties: { workspace: WORKSPACE, contact: { type: 'string' }, topic: { type: 'string' } },
1421
+ required: ['contact'],
1422
+ },
1423
+ },
1424
+ {
1425
+ name: 'workover_contacts_reset_preference_links',
1426
+ description:
1427
+ 'Reset the workspace’s preference links: every preference and unsubscribe link already sent stops working at once. Only when a link has leaked; ask the person first. Owners and admins.' +
1428
+ SCOPE,
1429
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
1430
+ },
1431
+ ];
1432
+
1433
+ /** The contacts tools' names, for the MCP dispatcher. */
1434
+ export const CONTACTS_TOOLS = new Set(CONTACTS_TOOL_DEFS.map((t) => t.name));
1435
+
1436
+ /** One contacts tool, run: the lines to answer with. Throws as `call` does. */
1437
+ export async function runContactsTool(call, name, args = {}) {
1438
+ const workspace = args.workspace === undefined || args.workspace === null ? undefined : String(args.workspace);
1439
+ if (name === 'workover_contacts_list')
1440
+ return renderContacts(
1441
+ await listContacts(call, { workspace, q: args.q, offset: args.offset, limit: args.limit, segment: args.segment }),
1442
+ );
1443
+ if (name === 'workover_contacts_get') return renderContact(await getContact(call, { workspace, contact: args.contact }));
1444
+ if (name === 'workover_contacts_identify') {
1445
+ const contacts = args.file ? contactsFromFile(String(args.file)) : args.contacts;
1446
+ return renderIdentified(await identifyContacts(call, { workspace, contacts, via: 'mcp' }));
1447
+ }
1448
+ if (name === 'workover_contacts_attributes') return renderAttributes(await listAttributes(call, { workspace }));
1449
+ if (name === 'workover_contacts_define_attribute')
1450
+ return renderAttributeSaved(
1451
+ await defineAttribute(call, { workspace, key: args.key, type: args.type, label: args.label }),
1452
+ );
1453
+ if (name === 'workover_contacts_update_attribute')
1454
+ return renderAttributeSaved(
1455
+ await updateAttribute(call, { workspace, key: args.key, label: args.label, archived: args.archived }),
1456
+ );
1457
+ if (name === 'workover_contacts_track') {
1458
+ const events = args.file ? eventsFromFile(String(args.file)) : args.events;
1459
+ return renderTracked(await trackEvents(call, { workspace, events }));
1460
+ }
1461
+ if (name === 'workover_contacts_events')
1462
+ return renderContactEvents(
1463
+ await contactEvents(call, {
1464
+ workspace,
1465
+ contact: args.contact,
1466
+ name: args.name,
1467
+ offset: args.offset,
1468
+ limit: args.limit,
1469
+ }),
1470
+ );
1471
+ if (name === 'workover_contacts_event_names') return renderEventNames(await listEventNames(call, { workspace }));
1472
+ if (name === 'workover_contacts_update_event_name')
1473
+ return renderEventNameSaved(
1474
+ await updateEventName(call, { workspace, name: args.name, label: args.label, archived: args.archived }),
1475
+ );
1476
+ if (name === 'workover_contacts_keys') return renderKeys(await listKeys(call, { workspace }));
1477
+ if (name === 'workover_contacts_create_key') return renderKeyCreated(await createKey(call, { workspace, name: args.name }));
1478
+ if (name === 'workover_contacts_revoke_key') return renderKeyRevoked(await revokeKey(call, { workspace, key: args.key }));
1479
+ if (name === 'workover_contacts_segments')
1480
+ return renderSegments(await listSegments(call, { workspace, archived: args.archived === true }));
1481
+ if (name === 'workover_contacts_segment') return renderSegment(await getSegment(call, { workspace, segment: args.segment }));
1482
+ if (name === 'workover_contacts_segment_preview')
1483
+ return renderSegmentPreview(
1484
+ await previewSegment(call, { workspace, definition: args.definition, segment: args.segment }),
1485
+ );
1486
+ if (name === 'workover_contacts_segment_create')
1487
+ return renderSegmentSaved(
1488
+ await createSegment(call, { workspace, name: args.name, kind: args.kind, definition: args.definition }),
1489
+ );
1490
+ if (name === 'workover_contacts_segment_update')
1491
+ return renderSegmentSaved(
1492
+ await updateSegment(call, {
1493
+ workspace,
1494
+ segment: args.segment,
1495
+ name: args.name,
1496
+ definition: args.definition,
1497
+ archived: args.archived,
1498
+ }),
1499
+ );
1500
+ if (name === 'workover_contacts_segment_members')
1501
+ return renderSegmentMembers(
1502
+ await segmentMembers(call, { workspace, segment: args.segment, offset: args.offset, limit: args.limit }),
1503
+ );
1504
+ if (name === 'workover_contacts_segment_add' || name === 'workover_contacts_segment_remove')
1505
+ return renderSegmentMembersChanged(
1506
+ await changeSegmentMembers(call, {
1507
+ workspace,
1508
+ segment: args.segment,
1509
+ contacts: args.contacts,
1510
+ remove: name === 'workover_contacts_segment_remove',
1511
+ }),
1512
+ );
1513
+ if (name === 'workover_contacts_export') {
1514
+ if (!args.out) throw apiError(400, 'Give `out`, the path of a new .csv file to write.');
1515
+ return renderExported(await exportContacts(call, { workspace, segment: args.segment, out: String(args.out) }));
1516
+ }
1517
+ if (name === 'workover_contacts_topics') return renderTopics(await listTopics(call, { workspace }));
1518
+ if (name === 'workover_contacts_topic_create')
1519
+ return renderTopicSaved(
1520
+ await createTopic(call, {
1521
+ workspace,
1522
+ key: args.key,
1523
+ name: args.name,
1524
+ description: args.description,
1525
+ default: args.default,
1526
+ }),
1527
+ );
1528
+ if (name === 'workover_contacts_topic_update')
1529
+ return renderTopicSaved(
1530
+ await updateTopic(call, {
1531
+ workspace,
1532
+ key: args.key,
1533
+ name: args.name,
1534
+ description: args.description,
1535
+ default: args.default,
1536
+ archived: args.archived,
1537
+ }),
1538
+ );
1539
+ if (name === 'workover_contacts_topics_reorder') return renderTopics(await reorderTopics(call, { workspace, keys: args.keys }));
1540
+ if (name === 'workover_contacts_subscriptions')
1541
+ return renderSubscriptions(await getSubscriptions(call, { workspace, contact: args.contact }));
1542
+ if (name === 'workover_contacts_set_subscriptions')
1543
+ return renderSubscriptions(
1544
+ await setSubscriptions(call, {
1545
+ workspace,
1546
+ contact: args.contact,
1547
+ topics: args.topics,
1548
+ unsubscribedAll: args.unsubscribedAll,
1549
+ consent: args.consent,
1550
+ via: 'mcp',
1551
+ }),
1552
+ );
1553
+ if (name === 'workover_contacts_consent')
1554
+ return renderConsent(
1555
+ await contactConsent(call, { workspace, contact: args.contact, offset: args.offset, limit: args.limit }),
1556
+ );
1557
+ if (name === 'workover_contacts_preferences_link')
1558
+ return renderPreferencesLink(await preferencesLink(call, { workspace, contact: args.contact, topic: args.topic }));
1559
+ if (name === 'workover_contacts_reset_preference_links') return renderLinksReset(await resetPreferenceLinks(call, { workspace }));
1560
+ throw apiError(400, `Unknown tool: ${name}`);
1561
+ }