@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,156 @@
1
+ // Support's email signatures from a terminal: `workover support signatures ...` and the MCP
2
+ // server's `workover_support_*signature*` tools (WO-1752, S10b, Support settings > Email).
3
+ //
4
+ // THE SAME FILE ships in @workover/cli (apps/cli/support-signatures.mjs) and @workover/mcp
5
+ // (apps/mcp/support-signatures.mjs), because the two packages are published separately and neither
6
+ // may depend on the other. `apps/mcp/support-signatures.test.mjs` fails when the copies differ.
7
+ //
8
+ // The brand's signature (everyone's replies end with it, unless they set their own; the workspace
9
+ // owner's or an admin's to change) and the signed-in person's own. Every call goes to a route
10
+ // opened to tokens holding the `support` scope (`workover login --support`). Setting the same
11
+ // signature again changes nothing, and an empty one removes it.
12
+ //
13
+ // `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
14
+ // whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
15
+ // return lines, for a terminal or an MCP text result alike.
16
+
17
+ import { apiError, resolveWorkspace } from './site-setup.mjs';
18
+
19
+ /** The Messenger whose signatures these are: Support has to exist first. */
20
+ async function messengerOf(call, workspace) {
21
+ const ws = await resolveWorkspace(call, workspace);
22
+ const status = await call(`/messenger/agent-setup?organizationId=${encodeURIComponent(ws.id)}`);
23
+ const id = status?.messenger?.id;
24
+ if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
25
+ return { ws, messengerId: id };
26
+ }
27
+
28
+ /** The brand's signature, the caller's own, the variables, and what the caller's replies end with. */
29
+ export async function getSignatures(call, { workspace } = {}) {
30
+ const { ws, messengerId } = await messengerOf(call, workspace);
31
+ const res = await call(`/messenger/${messengerId}/email/signatures`);
32
+ return { workspace: ws, ...res };
33
+ }
34
+
35
+ /**
36
+ * Set the brand's signature (`which: 'brand'`) or the caller's own (`which: 'mine'`), as text (one
37
+ * line per line) or HTML. An empty one removes it. Safe to repeat.
38
+ */
39
+ export async function setSignature(call, { workspace, which, html }) {
40
+ if (which !== 'brand' && which !== 'mine') throw apiError(400, 'Say which signature: brand or mine.');
41
+ if (html === undefined || html === null) throw apiError(400, 'Give the signature, as text or HTML ("" removes it).');
42
+ const { ws, messengerId } = await messengerOf(call, workspace);
43
+ const res = await call(`/messenger/${messengerId}/email/signatures/${which}`, {
44
+ method: 'PUT',
45
+ body: { html: String(html) },
46
+ });
47
+ return { workspace: ws, which, ...res };
48
+ }
49
+
50
+ /** A signature as it would arrive from the caller, filled, without saving it. */
51
+ export async function previewSignature(call, { workspace, html }) {
52
+ const { ws, messengerId } = await messengerOf(call, workspace);
53
+ const res = await call(`/messenger/${messengerId}/email/signatures/preview`, {
54
+ method: 'POST',
55
+ body: { html: String(html ?? '') },
56
+ });
57
+ return { workspace: ws, ...res };
58
+ }
59
+
60
+ const indent = (text) =>
61
+ String(text)
62
+ .split('\n')
63
+ .map((l) => ` ${l}`);
64
+
65
+ const SOURCE = {
66
+ mine: 'your own signature',
67
+ brand: 'the brand signature',
68
+ none: 'your name and the brand (no signature set)',
69
+ };
70
+
71
+ export function renderSignatures(res) {
72
+ const out = ['', ` Email signatures for ${res.brandName}:`, ''];
73
+ out.push(' Brand signature (everyone, unless they set their own):');
74
+ out.push(...(res.brand?.html ? indent(res.brand.html) : [' (none)']));
75
+ out.push('', ' Your signature:');
76
+ out.push(...(res.mine?.html ? indent(res.mine.html) : [' (none: the brand signature applies)']));
77
+ out.push('', ` Your replies end with ${SOURCE[res.effective?.source] ?? 'the plain sign-off'}:`);
78
+ out.push(...indent(res.effective?.text ?? ''));
79
+ if (res.variables?.length)
80
+ out.push('', ` Variables: ${res.variables.map((v) => `{{${v.key}}}`).join(', ')} (add a fallback: {{agent.lastName|Support}})`);
81
+ if (res.canEditBrand === false) out.push('', ' Only workspace owners and admins can change the brand signature.');
82
+ out.push('');
83
+ return out;
84
+ }
85
+
86
+ export function renderSignatureSaved(res) {
87
+ const kept = res.which === 'brand' ? res.brand : res.mine;
88
+ const label = res.which === 'brand' ? 'Brand signature' : 'Your signature';
89
+ return kept?.html
90
+ ? ['', ` ✓ ${label} saved. Your replies now end with:`, ...indent(res.effective?.text ?? ''), '']
91
+ : ['', ` ✓ ${label} removed. Your replies now end with ${SOURCE[res.effective?.source] ?? 'the plain sign-off'}.`, ''];
92
+ }
93
+
94
+ export function renderSignaturePreview(res) {
95
+ return res.html
96
+ ? ['', ' As it would arrive from you:', ...indent(res.text), '']
97
+ : ['', ' Empty: replies end with the brand signature, or your name and the brand.', ''];
98
+ }
99
+
100
+ const WORKSPACE = {
101
+ type: 'string',
102
+ description: 'The workspace, by slug or id. Needed only when the account has more than one.',
103
+ };
104
+ const SCOPE =
105
+ ' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
106
+
107
+ /** The MCP server's signature tools, listed with the other Support tools (index.mjs). */
108
+ export const SIGNATURE_TOOL_DEFS = [
109
+ {
110
+ name: 'workover_support_signatures',
111
+ description:
112
+ "Support's email signatures: the brand's (every teammate's replies in Support emails end with it unless they set their own), the signed-in person's own, the {{variables}} a signature may use, and what their replies end with today." +
113
+ SCOPE,
114
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
115
+ },
116
+ {
117
+ name: 'workover_support_set_signature',
118
+ description:
119
+ "Set an email signature for Support: `which: 'brand'` (owners and admins) or `which: 'mine'` (the signed-in person's own). Text (one line per line) or HTML (formatting, links, https pictures, tables; anything else is removed). Variables: {{agent.name}}, {{agent.firstName}}, {{agent.lastName}}, {{agent.email}}, {{brand.name}}, each with an optional fallback like {{agent.lastName|Support}}. An empty html removes it. Safe to repeat." +
120
+ SCOPE,
121
+ inputSchema: {
122
+ type: 'object',
123
+ properties: {
124
+ workspace: WORKSPACE,
125
+ which: { type: 'string', enum: ['brand', 'mine'] },
126
+ html: { type: 'string', description: 'The signature as text or HTML; "" removes it.' },
127
+ },
128
+ required: ['which', 'html'],
129
+ },
130
+ },
131
+ {
132
+ name: 'workover_support_preview_signature',
133
+ description:
134
+ 'Shows a signature as it would arrive from the signed-in person (cleaned, variables filled), without saving it. An unknown variable is refused with the list of the ones there are.' +
135
+ SCOPE,
136
+ inputSchema: {
137
+ type: 'object',
138
+ properties: { workspace: WORKSPACE, html: { type: 'string' } },
139
+ required: ['html'],
140
+ },
141
+ },
142
+ ];
143
+
144
+ /** The signature tools' names, for the MCP dispatcher. */
145
+ export const SIGNATURE_TOOLS = new Set(SIGNATURE_TOOL_DEFS.map((t) => t.name));
146
+
147
+ /** One signature tool, run: the lines to answer with. Throws as `call` does. */
148
+ export async function runSignatureTool(call, name, args = {}) {
149
+ const workspace = args.workspace === undefined || args.workspace === null ? undefined : String(args.workspace);
150
+ if (name === 'workover_support_signatures') return renderSignatures(await getSignatures(call, { workspace }));
151
+ if (name === 'workover_support_set_signature')
152
+ return renderSignatureSaved(await setSignature(call, { workspace, which: args.which, html: args.html }));
153
+ if (name === 'workover_support_preview_signature')
154
+ return renderSignaturePreview(await previewSignature(call, { workspace, html: args.html }));
155
+ throw apiError(400, `Unknown tool: ${name}`);
156
+ }
@@ -0,0 +1,233 @@
1
+ // Walter AI's sources from a terminal: `workover support sources ...` and the MCP server's
2
+ // `workover_support_*source*` tools (WO-1752, S06b).
3
+ //
4
+ // THE SAME FILE ships in @workover/cli (apps/cli/support-sources.mjs) and @workover/mcp
5
+ // (apps/mcp/support-sources.mjs), because the two packages are published separately and neither
6
+ // may depend on the other. `apps/mcp/support-sources.test.mjs` fails when the copies differ.
7
+ //
8
+ // What Support's AI agent answers from beyond the linked docs: a private docs project, a web page,
9
+ // a sitemap or a PDF. Pages and files become hidden docs (never on the Help tab or the public site),
10
+ // and web sources resync on a schedule. Every call goes to a route opened to tokens holding the
11
+ // `support` scope (`workover login --support`). Each write is safe to repeat: adding a source again
12
+ // answers `created: false` with the one already there, and removing one again `removed: false`.
13
+ //
14
+ // `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
15
+ // whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
16
+ // return lines, for a terminal or an MCP text result alike.
17
+
18
+ import { apiError, resolveWorkspace } from './site-setup.mjs';
19
+
20
+ export const SOURCE_KINDS = ['url', 'sitemap', 'project', 'pdf'];
21
+ /** How often a web source may resync, in hours. 0 is never. */
22
+ export const RESYNC_HOURS = [0, 6, 24, 168];
23
+ /** The largest PDF the JSON route takes (base64 grows it by a third). The app takes 20 MB. */
24
+ export const MAX_PDF_JSON_BYTES = 3_500_000;
25
+
26
+ /** The Messenger whose sources these are: Support has to exist first. */
27
+ async function messengerOf(call, workspace) {
28
+ const ws = await resolveWorkspace(call, workspace);
29
+ const status = await call(`/messenger/agent-setup?organizationId=${encodeURIComponent(ws.id)}`);
30
+ const id = status?.messenger?.id;
31
+ if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
32
+ return { ws, messengerId: id };
33
+ }
34
+
35
+ const base = (messengerId) => `/messenger/${messengerId}/sources`;
36
+
37
+ function sourceIdOf(raw) {
38
+ const n = Number(raw);
39
+ if (!Number.isInteger(n) || n <= 0) throw apiError(400, `"${raw}" is not a source id. \`workover support sources\` lists them.`);
40
+ return n;
41
+ }
42
+
43
+ function hoursOf(raw) {
44
+ if (raw === undefined || raw === null || raw === '') return undefined;
45
+ const n = Number(raw);
46
+ if (!RESYNC_HOURS.includes(n)) throw apiError(400, `Resync every ${RESYNC_HOURS.filter(Boolean).join(', ')} hours, or 0 for never.`);
47
+ return n;
48
+ }
49
+
50
+ /** Every source with its status, doc count and last sync, and the private projects that could be added. */
51
+ export async function listSources(call, { workspace } = {}) {
52
+ const { ws, messengerId } = await messengerOf(call, workspace);
53
+ const res = await call(base(messengerId));
54
+ return { workspace: ws, ...res };
55
+ }
56
+
57
+ /**
58
+ * Add a web page, a sitemap or a private project. A web source is read in the background: list the
59
+ * sources again for `ready` or `failed`.
60
+ */
61
+ export async function addSource(call, { workspace, kind, url, projectId, resyncHours }) {
62
+ const k = String(kind ?? '').trim().toLowerCase();
63
+ if (!['url', 'sitemap', 'project'].includes(k))
64
+ throw apiError(400, 'Add a source of kind url, sitemap or project. A PDF goes through addPdf.');
65
+ const body = { kind: k };
66
+ if (k === 'project') {
67
+ const id = Number(projectId);
68
+ if (!Number.isInteger(id) || id <= 0) throw apiError(400, 'Give the project to add by its id (`workover projects` lists them).');
69
+ body.projectId = id;
70
+ } else {
71
+ if (typeof url !== 'string' || !url.trim()) throw apiError(400, 'Give the https address to read.');
72
+ body.url = url.trim();
73
+ const h = hoursOf(resyncHours);
74
+ if (h !== undefined) body.resyncHours = h;
75
+ }
76
+ const { ws, messengerId } = await messengerOf(call, workspace);
77
+ const res = await call(base(messengerId), { method: 'POST', body });
78
+ return { workspace: ws, ...res };
79
+ }
80
+
81
+ /** Upload a PDF the agent answers from and cites by its file name. `bytes` is a Buffer or Uint8Array. */
82
+ export async function addPdf(call, { workspace, name, bytes }) {
83
+ if (!bytes || !bytes.length) throw apiError(400, 'That file is empty.');
84
+ if (bytes.length > MAX_PDF_JSON_BYTES)
85
+ throw apiError(400, `That PDF is ${Math.round(bytes.length / 1e5) / 10} MB. Files up to 3.5 MB upload from here; larger ones (up to 20 MB) upload in the app, under Support, AI answers, Sources.`);
86
+ const { ws, messengerId } = await messengerOf(call, workspace);
87
+ const base64 = Buffer.from(bytes).toString('base64');
88
+ const res = await call(`${base(messengerId)}/pdf`, { method: 'POST', body: { name: String(name || 'Document.pdf'), base64 } });
89
+ return { workspace: ws, ...res };
90
+ }
91
+
92
+ /** Switch a source on or off, or change how often a web source resyncs. Fields left out stay. */
93
+ export async function updateSource(call, { workspace, sourceId, enabled, resyncHours }) {
94
+ const id = sourceIdOf(sourceId);
95
+ const body = {};
96
+ if (enabled !== undefined) body.enabled = !!enabled;
97
+ const h = hoursOf(resyncHours);
98
+ if (h !== undefined) body.resyncHours = h;
99
+ if (!Object.keys(body).length) throw apiError(400, 'Nothing to change: give enabled or resyncHours.');
100
+ const { ws, messengerId } = await messengerOf(call, workspace);
101
+ const source = await call(`${base(messengerId)}/${id}`, { method: 'PATCH', body });
102
+ return { workspace: ws, source };
103
+ }
104
+
105
+ /** Remove a source. Its hidden docs go to the trash, except any someone edited. */
106
+ export async function removeSource(call, { workspace, sourceId }) {
107
+ const id = sourceIdOf(sourceId);
108
+ const { ws, messengerId } = await messengerOf(call, workspace);
109
+ const res = await call(`${base(messengerId)}/${id}`, { method: 'DELETE' });
110
+ return { workspace: ws, ...res };
111
+ }
112
+
113
+ /** Read a web page or sitemap source again now. */
114
+ export async function syncSource(call, { workspace, sourceId }) {
115
+ const id = sourceIdOf(sourceId);
116
+ const { ws, messengerId } = await messengerOf(call, workspace);
117
+ const source = await call(`${base(messengerId)}/${id}/sync`, { method: 'POST' });
118
+ return { workspace: ws, source };
119
+ }
120
+
121
+ // ------------------------------------------------------------------ rendering
122
+
123
+ const KIND = { url: 'web page', sitemap: 'sitemap', project: 'private project', pdf: 'PDF' };
124
+ const RESYNC = { 0: 'never resyncs', 6: 'resyncs every 6 hours', 24: 'resyncs daily', 168: 'resyncs weekly' };
125
+
126
+ /** One line per source: id, name, kind, status, docs, last sync. */
127
+ export function renderSourceLine(s) {
128
+ const bits = [KIND[s.kind] || s.kind, s.status];
129
+ if (s.kind !== 'project') bits.push(`${s.pageCount} ${s.pageCount === 1 ? 'doc' : 'docs'}`);
130
+ if (s.editedCount) bits.push(`${s.editedCount} edited`);
131
+ if (s.kind === 'url' || s.kind === 'sitemap') {
132
+ bits.push(s.lastSyncedAt ? `synced ${s.lastSyncedAt}` : 'not synced yet');
133
+ bits.push(RESYNC[s.resyncHours] || `resyncs every ${s.resyncHours} hours`);
134
+ }
135
+ if (!s.enabled) bits.push('switched off');
136
+ const lines = [` #${s.id} ${s.name}${s.url ? ` (${s.url})` : ''}`, ` ${bits.join(' · ')}`];
137
+ if (s.status === 'failed' && s.error) lines.push(` ${s.error}`);
138
+ return lines;
139
+ }
140
+
141
+ export function renderSources(res) {
142
+ const out = ['', ` Walter AI's sources in ${res.workspace?.name ?? 'this workspace'}`, ''];
143
+ if (!res.sources?.length) out.push(' None yet: the agent answers from the published docs only.');
144
+ for (const s of res.sources || []) out.push(...renderSourceLine(s));
145
+ const open = (res.projectOptions || []).filter((p) => !p.added);
146
+ if (open.length) {
147
+ out.push('', ' Private projects you could add:');
148
+ for (const p of open) out.push(` ${p.projectId} ${p.name}`);
149
+ }
150
+ if (res.library) out.push('', ` Hidden docs live in the project "${res.library.name}" (#${res.library.projectId}).`);
151
+ out.push('');
152
+ return out;
153
+ }
154
+
155
+ export function renderSourceAdded(res) {
156
+ const s = res.source;
157
+ const head = res.created ? ` ✓ Added ${s.name}.` : ` ✓ ${s.name} was already a source; nothing changed.`;
158
+ const tail =
159
+ s.status === 'syncing' || s.status === 'pending'
160
+ ? ['', ' Reading it now. Run `workover support sources` again for ready or failed.']
161
+ : [];
162
+ return ['', head, ...renderSourceLine(s), ...tail, ''];
163
+ }
164
+
165
+ export function renderSourceRemoved(res) {
166
+ if (!res.removed) return ['', ' ✓ That source was already gone; nothing changed.', ''];
167
+ const kept = res.kept ? ` ${res.kept} edited ${res.kept === 1 ? 'doc stays' : 'docs stay'} as ordinary docs.` : '';
168
+ return ['', ` ✓ Removed. ${res.trashed} hidden ${res.trashed === 1 ? 'doc went' : 'docs went'} to the trash.${kept}`, ''];
169
+ }
170
+
171
+ // ------------------------------------------------------------------ MCP tool definitions
172
+
173
+ const WORKSPACE = {
174
+ type: ['string', 'number'],
175
+ description: 'The workspace, by slug or id. Needed only when the account has more than one.',
176
+ };
177
+ const SCOPE =
178
+ ' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
179
+
180
+ /** The MCP server's source tools, listed with the other Support tools (index.mjs). */
181
+ export const SOURCE_TOOL_DEFS = [
182
+ {
183
+ name: 'workover_support_sources',
184
+ description:
185
+ "What Support's AI agent (Walter AI) answers from beyond the linked docs: private projects, web pages, sitemaps and PDFs, each with its id, status, doc count and last sync, and the private projects that could be added." +
186
+ SCOPE,
187
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
188
+ },
189
+ {
190
+ name: 'workover_support_add_source',
191
+ description:
192
+ 'Add a source for the AI agent: a web page (kind url) or sitemap, read into hidden docs that never appear on the Help tab or the public site and resync on schedule; a private docs project (kind project, projectId); or a PDF (kind pdf, file: an absolute path, up to 3.5 MB), cited by its file name. Safe to repeat: the same source again answers that it was already there.' +
193
+ SCOPE,
194
+ inputSchema: {
195
+ type: 'object',
196
+ properties: {
197
+ workspace: WORKSPACE,
198
+ kind: { type: 'string', enum: SOURCE_KINDS },
199
+ url: { type: 'string', description: 'The https address of the page or sitemap.' },
200
+ projectId: { type: 'number', description: 'The private project to answer from (workover_list_projects).' },
201
+ file: { type: 'string', description: 'The PDF on disk, as an absolute path.' },
202
+ resyncHours: { type: 'number', enum: RESYNC_HOURS, description: 'How often a web source is read again. Default 24; 0 never.' },
203
+ },
204
+ required: ['kind'],
205
+ },
206
+ },
207
+ {
208
+ name: 'workover_support_update_source',
209
+ description: 'Switch a source on or off, or change how often a web source resyncs. Fields left out stay.' + SCOPE,
210
+ inputSchema: {
211
+ type: 'object',
212
+ properties: {
213
+ workspace: WORKSPACE,
214
+ sourceId: { type: 'number' },
215
+ enabled: { type: 'boolean' },
216
+ resyncHours: { type: 'number', enum: RESYNC_HOURS },
217
+ },
218
+ required: ['sourceId'],
219
+ },
220
+ },
221
+ {
222
+ name: 'workover_support_sync_source',
223
+ description: 'Read a web page or sitemap source again now. Call workover_support_sources afterwards for ready or failed.' + SCOPE,
224
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, sourceId: { type: 'number' } }, required: ['sourceId'] },
225
+ },
226
+ {
227
+ name: 'workover_support_remove_source',
228
+ description:
229
+ 'Remove a source. Its hidden docs go to the trash, except any someone edited, which stay as ordinary docs. Ask the person first. Safe to repeat.' +
230
+ SCOPE,
231
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, sourceId: { type: 'number' } }, required: ['sourceId'] },
232
+ },
233
+ ];