@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,424 @@
1
+ // Walter AI's batch test and releases from a terminal: `workover support tests ...`,
2
+ // `workover support releases ...`, and the MCP server's `workover_support_agent_*` tools
3
+ // (WO-1752, S06c).
4
+ //
5
+ // THE SAME FILE ships in @workover/cli (apps/cli/support-agent-tests.mjs) and @workover/mcp
6
+ // (apps/mcp/support-agent-tests.mjs), because the two packages are published separately and neither
7
+ // may depend on the other. `apps/mcp/support-agent-tests.test.mjs` fails when the copies differ.
8
+ //
9
+ // The guidance, snippets and sources an owner edits are a DRAFT. Visitors are answered from the live
10
+ // version, which Set live writes from the draft; a rollback makes an older version live again, as a
11
+ // new version. A batch test asks Walter up to 50 questions against the draft or the live version and
12
+ // sends nothing to anyone. Every call goes to a route opened to tokens holding the `support` scope
13
+ // (`workover login --support`). Each write is safe to repeat: Set live with nothing to change, a
14
+ // rollback to the live version, and a question already in the set all answer `created: false`.
15
+ //
16
+ // `call(path, { method, body })` does the requests and resolves the parsed JSON, or throws an Error
17
+ // whose `.status` is the HTTP status and whose message is the API's own sentence. The renderers
18
+ // return lines, for a terminal or an MCP text result alike.
19
+
20
+ import { apiError, resolveWorkspace } from './site-setup.mjs';
21
+
22
+ export const TARGETS = ['draft', 'live'];
23
+ export const RATINGS = ['good', 'bad'];
24
+ /** How long `runTests` waits for a run by default, and the longest it waits. */
25
+ export const WAIT_MS = 120_000;
26
+ export const MAX_WAIT_MS = 600_000;
27
+ const POLL_MS = 2_000;
28
+
29
+ /** The Messenger these belong to: Support has to exist first. */
30
+ async function messengerOf(call, workspace) {
31
+ const ws = await resolveWorkspace(call, workspace);
32
+ const status = await call(`/messenger/agent-setup?organizationId=${encodeURIComponent(ws.id)}`);
33
+ const id = status?.messenger?.id;
34
+ if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
35
+ return { ws, messengerId: id };
36
+ }
37
+
38
+ const releasesPath = (m) => `/messenger/${m}/agent-releases`;
39
+ const testsPath = (m) => `/messenger/${m}/agent-tests`;
40
+
41
+ function idOf(raw, what, hint) {
42
+ const n = Number(raw);
43
+ if (!Number.isInteger(n) || n <= 0) throw apiError(400, `"${raw ?? ''}" is not a ${what}. ${hint}`);
44
+ return n;
45
+ }
46
+
47
+ function targetOf(raw) {
48
+ if (raw === undefined || raw === null || raw === '') return 'draft';
49
+ const t = String(raw).trim().toLowerCase();
50
+ if (!TARGETS.includes(t)) throw apiError(400, 'Run against draft or live.');
51
+ return t;
52
+ }
53
+
54
+ // ------------------------------------------------------------------ releases
55
+
56
+ /** The live version, what Set live would change, and the newest versions. */
57
+ export async function listReleases(call, { workspace } = {}) {
58
+ const { ws, messengerId } = await messengerOf(call, workspace);
59
+ return { workspace: ws, ...(await call(releasesPath(messengerId))) };
60
+ }
61
+
62
+ /** Make the draft the next live version. Nothing to change answers `created: false`. */
63
+ export async function setLive(call, { workspace, note } = {}) {
64
+ const body = {};
65
+ if (typeof note === 'string' && note.trim()) body.note = note.trim();
66
+ const { ws, messengerId } = await messengerOf(call, workspace);
67
+ return { workspace: ws, ...(await call(releasesPath(messengerId), { method: 'POST', body })) };
68
+ }
69
+
70
+ /** Make an older version live again, as a new version. The draft stays as it is. */
71
+ export async function rollback(call, { workspace, version }) {
72
+ const v = idOf(version, 'version', '`workover support releases` lists them.');
73
+ const { ws, messengerId } = await messengerOf(call, workspace);
74
+ return { workspace: ws, ...(await call(`${releasesPath(messengerId)}/${v}/rollback`, { method: 'POST' })) };
75
+ }
76
+
77
+ // ------------------------------------------------------------------ the batch test
78
+
79
+ /** The questions, the newest run with its answers, and the earlier runs. */
80
+ export async function listTests(call, { workspace } = {}) {
81
+ const { ws, messengerId } = await messengerOf(call, workspace);
82
+ return { workspace: ws, ...(await call(testsPath(messengerId))) };
83
+ }
84
+
85
+ /**
86
+ * Add questions: one (`question`, optional `expect`, words the answer must contain), several
87
+ * (`questions: [{ question, expect }]`), or a file's text (`text`, one per line, or a CSV with a
88
+ * `question,expect` header). A question already in the set is skipped.
89
+ */
90
+ export async function addTests(call, { workspace, question, expect, questions, text }) {
91
+ let body;
92
+ if (typeof text === 'string') {
93
+ if (!text.trim()) throw apiError(400, 'That file has no questions.');
94
+ body = { text, csv: /^\s*"?question"?\s*(,|$)/i.test(text) };
95
+ } else if (Array.isArray(questions)) {
96
+ if (!questions.length) throw apiError(400, 'Give at least one question.');
97
+ body = {
98
+ questions: questions.map((q) =>
99
+ typeof q === 'string' ? { question: q } : { question: q?.question, expect: q?.expect ?? null },
100
+ ),
101
+ };
102
+ } else {
103
+ if (typeof question !== 'string' || question.trim().length < 3) throw apiError(400, 'Give the question to ask.');
104
+ body = { question: question.trim(), expect: typeof expect === 'string' && expect.trim() ? expect.trim() : null };
105
+ }
106
+ const { ws, messengerId } = await messengerOf(call, workspace);
107
+ return { workspace: ws, ...(await call(testsPath(messengerId), { method: 'POST', body })) };
108
+ }
109
+
110
+ /** Up to 50 questions from the first visitor message of recent conversations. */
111
+ export async function generateTests(call, { workspace } = {}) {
112
+ const { ws, messengerId } = await messengerOf(call, workspace);
113
+ return { workspace: ws, ...(await call(`${testsPath(messengerId)}/generate`, { method: 'POST' })) };
114
+ }
115
+
116
+ /** Remove a question. Removing it again answers `removed: false`. */
117
+ export async function removeTest(call, { workspace, testId }) {
118
+ const id = idOf(testId, 'question id', '`workover support tests` lists them.');
119
+ const { ws, messengerId } = await messengerOf(call, workspace);
120
+ return { workspace: ws, ...(await call(`${testsPath(messengerId)}/questions/${id}`, { method: 'DELETE' })) };
121
+ }
122
+
123
+ /** One run with every answer. */
124
+ export async function getRun(call, { workspace, runId }) {
125
+ const id = idOf(runId, 'run id', '`workover support tests` shows the newest.');
126
+ const { ws, messengerId } = await messengerOf(call, workspace);
127
+ return { workspace: ws, run: await call(`${testsPath(messengerId)}/runs/${id}`) };
128
+ }
129
+
130
+ /**
131
+ * Start a run against the draft (default) or the live version, and with `wait` follow it until it
132
+ * is done or `waitMs` passes. A run already going is followed rather than refused.
133
+ * `sleep` and `now` are there for the tests.
134
+ */
135
+ export async function runTests(
136
+ call,
137
+ { workspace, target, wait = false, waitMs = WAIT_MS, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now },
138
+ ) {
139
+ const t = targetOf(target);
140
+ const { ws, messengerId } = await messengerOf(call, workspace);
141
+ let run;
142
+ let started = true;
143
+ try {
144
+ run = await call(`${testsPath(messengerId)}/runs`, { method: 'POST', body: { target: t } });
145
+ } catch (e) {
146
+ // A run already going (409): follow that one. The CLI's and the MCP server's callers carry the
147
+ // status differently, so the API's sentence is matched too.
148
+ if (e?.status !== 409 && !/already running/i.test(String(e?.message ?? ''))) throw e;
149
+ const latest = (await call(testsPath(messengerId)))?.latest;
150
+ if (!latest || latest.status !== 'running') throw e;
151
+ run = await call(`${testsPath(messengerId)}/runs/${latest.id}`);
152
+ started = false;
153
+ }
154
+ if (wait) {
155
+ const until = now() + Math.min(Math.max(Number(waitMs) || 0, 0), MAX_WAIT_MS);
156
+ while (run.status === 'running' && now() < until) {
157
+ await sleep(POLL_MS);
158
+ run = await call(`${testsPath(messengerId)}/runs/${run.id}`);
159
+ }
160
+ }
161
+ return { workspace: ws, started, run };
162
+ }
163
+
164
+ /** Rate one answer good or bad (null clears it), with an optional note. */
165
+ export async function rateResult(call, { workspace, resultId, rating, note }) {
166
+ const id = idOf(resultId, 'result id', 'Each answer in `workover support tests show <run>` has one.');
167
+ const body = {};
168
+ if (rating !== undefined) {
169
+ const r = rating === null || rating === 'clear' || rating === 'none' ? null : String(rating).trim().toLowerCase();
170
+ if (r !== null && !RATINGS.includes(r)) throw apiError(400, 'Rate an answer good or bad, or clear the rating.');
171
+ body.rating = r;
172
+ }
173
+ if (note !== undefined) body.note = note === null ? null : String(note);
174
+ if (!Object.keys(body).length) throw apiError(400, 'Nothing to change: give a rating or a note.');
175
+ const { ws, messengerId } = await messengerOf(call, workspace);
176
+ return { workspace: ws, ...(await call(`${testsPath(messengerId)}/results/${id}`, { method: 'PATCH', body })) };
177
+ }
178
+
179
+ // ------------------------------------------------------------------ rendering
180
+
181
+ const AREA = { guidance: 'Guidance', snippets: 'Snippet', sources: 'Source', small_talk: 'Small talk', known_links: 'Known link' };
182
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
183
+
184
+ function versionLine(r) {
185
+ const how =
186
+ r.kind === 'baseline' ? 'what Walter answered with before releases' : r.note || (r.kind === 'rollback' ? 'rolled back' : 'set live');
187
+ const who = r.createdBy?.name ? ` · ${r.createdBy.name}` : '';
188
+ return ` v${r.version}${r.live ? ' LIVE' : ''} ${how} · ${r.createdAt}${who}`;
189
+ }
190
+
191
+ export function renderReleases(res) {
192
+ const out = ['', ` Walter AI in ${res.workspace?.name ?? 'this workspace'}`, ''];
193
+ if (!res.live) out.push(' No version yet: visitors get what is in the guidance and sources now.');
194
+ else out.push(` Live: version ${res.live.version}.`);
195
+ const changes = res.changes ?? [];
196
+ if (changes.length) {
197
+ out.push(` The draft has ${plural(changes.length, 'change')} visitors do not get yet:`);
198
+ for (const c of changes) out.push(` ${AREA[c.area] ?? c.area} ${c.change}: ${c.label}`);
199
+ out.push('', ' Test them with `workover support tests run`, then `workover support releases set-live`.');
200
+ } else if (res.live) out.push(' The draft is what visitors get.');
201
+ if (res.releases?.length) {
202
+ out.push('', ' Versions:');
203
+ for (const r of res.releases) out.push(versionLine(r));
204
+ }
205
+ out.push('');
206
+ return out;
207
+ }
208
+
209
+ export function renderSetLive(res) {
210
+ if (!res.created) return ['', ` ✓ Nothing to set live: version ${res.version ?? res.live?.version} is what visitors get.`, ''];
211
+ return ['', ` ✓ Version ${res.version} is live. Visitors get it from their next message.`, ''];
212
+ }
213
+
214
+ export function renderRollback(res) {
215
+ if (!res.created) return ['', ` ✓ That version is already live; nothing changed.`, ''];
216
+ return ['', ` ✓ Rolled back. Version ${res.version} is live, holding what that older version did. The draft is unchanged.`, ''];
217
+ }
218
+
219
+ const STATE = { answered: 'answered', handed_over: 'handed over', failed: 'not answered', pending: 'waiting' };
220
+
221
+ function runHead(run) {
222
+ const against = run.target === 'live' ? `live${run.version ? ` (version ${run.version})` : ''}` : 'the draft';
223
+ const checked = run.passed + run.failed;
224
+ const bits = [
225
+ `${run.completed} of ${run.total} done`,
226
+ `${run.answered} answered`,
227
+ `${run.handedOver} handed over`,
228
+ ];
229
+ if (checked) bits.push(`${run.passed} of ${checked} passed`);
230
+ if (run.rated?.good || run.rated?.bad) bits.push(`${run.rated.good} good, ${run.rated.bad} bad`);
231
+ return ` Run #${run.id} against ${against}, ${run.status}: ${bits.join(' · ')}`;
232
+ }
233
+
234
+ export function renderRun(run) {
235
+ const out = [runHead(run)];
236
+ if (run.status === 'failed') out.push(' This run stopped before it finished. Run it again.');
237
+ for (const r of run.results ?? []) {
238
+ const check = r.pass === null ? '' : r.pass ? ' · PASSED' : ' · FAILED';
239
+ const rated = r.rating ? ` · rated ${r.rating}` : '';
240
+ out.push('', ` [${r.id}] ${r.question}`, ` ${STATE[r.state] ?? r.state}${check}${rated}`);
241
+ if (r.expect) out.push(` must contain: ${r.expect}`);
242
+ if (r.answer) for (const line of String(r.answer).split('\n')) out.push(` > ${line}`);
243
+ if (r.state === 'handed_over' && r.reason) out.push(` handed over: ${r.reason}`);
244
+ }
245
+ return out;
246
+ }
247
+
248
+ export function renderTests(res) {
249
+ const out = ['', ` Walter AI's batch test in ${res.workspace?.name ?? 'this workspace'}`, ''];
250
+ if (!res.questions?.length) out.push(' No questions yet. Add some with `workover support tests add` or `tests generate`.');
251
+ else {
252
+ out.push(` ${res.questions.length} of ${res.limit} questions:`);
253
+ for (const q of res.questions) out.push(` #${q.id} ${q.question}${q.expect ? ` (must contain: ${q.expect})` : ''}`);
254
+ }
255
+ if (res.latest) out.push('', ...renderRun(res.latest));
256
+ out.push('');
257
+ return out;
258
+ }
259
+
260
+ export function renderAdded(res) {
261
+ const head =
262
+ res.created > 0
263
+ ? ` ✓ Added ${plural(res.created, 'question')}.${res.skipped ? ` ${res.skipped} already in the set.` : ''}`
264
+ : ` ✓ ${res.skipped ? 'Already in the set' : 'Nothing to add'}; nothing changed.`;
265
+ return ['', head, ` ${res.questions?.length ?? 0} of ${res.limit ?? 50} questions now.`, ''];
266
+ }
267
+
268
+ export function renderRemoved(res) {
269
+ return ['', res.removed ? ' ✓ Removed.' : ' ✓ That question was already gone; nothing changed.', ''];
270
+ }
271
+
272
+ export function renderRunStarted(res) {
273
+ const lead = res.started ? '' : ' A run was already going; showing it.';
274
+ const tail =
275
+ res.run.status === 'running'
276
+ ? [` Still running. \`workover support tests show ${res.run.id}\` shows it as it goes.`]
277
+ : [];
278
+ return ['', ...(lead ? [lead] : []), ...renderRun(res.run), ...(tail.length ? ['', ...tail] : []), ''];
279
+ }
280
+
281
+ export function renderRated(res) {
282
+ const r = res.result;
283
+ return ['', r.rating ? ` ✓ Rated ${r.rating}.` : ' ✓ Rating cleared.', ''];
284
+ }
285
+
286
+ // ------------------------------------------------------------------ MCP tool definitions
287
+
288
+ const WORKSPACE = {
289
+ type: ['string', 'number'],
290
+ description: 'The workspace, by slug or id. Needed only when the account has more than one.',
291
+ };
292
+ const SCOPE =
293
+ ' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
294
+
295
+ /** The MCP server's batch test and release tools, listed with the other Support tools (index.mjs). */
296
+ export const AGENT_TEST_TOOL_DEFS = [
297
+ {
298
+ name: 'workover_support_agent_releases',
299
+ description:
300
+ "Which version of Support's AI agent (Walter AI) visitors are answered from, what the draft (the guidance, snippets and sources as edited) would change if set live, and the newest versions." +
301
+ SCOPE,
302
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
303
+ },
304
+ {
305
+ name: 'workover_support_agent_set_live',
306
+ description:
307
+ 'Make the draft the next live version: visitors get it from their next message. Run workover_support_agent_run_tests against the draft first, and ask the person before setting live. Safe to repeat: with nothing to change it says so.' +
308
+ SCOPE,
309
+ inputSchema: {
310
+ type: 'object',
311
+ properties: { workspace: WORKSPACE, note: { type: 'string', description: 'What changed, for the version list. Default: a summary of the changes.' } },
312
+ },
313
+ },
314
+ {
315
+ name: 'workover_support_agent_rollback',
316
+ description:
317
+ 'Make an older version live again, written as a new version. The draft is not changed. Ask the person first. Rolling back to the live version changes nothing.' +
318
+ SCOPE,
319
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, version: { type: 'number' } }, required: ['version'] },
320
+ },
321
+ {
322
+ name: 'workover_support_agent_tests',
323
+ description:
324
+ "The AI agent's batch test: the questions (each with its id and the words its answer must contain), and the newest run with every answer, its check and its rating." +
325
+ SCOPE,
326
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
327
+ },
328
+ {
329
+ name: 'workover_support_agent_add_tests',
330
+ description:
331
+ 'Add questions to the batch test (up to 50 in all): one (question, expect), several (questions), or a list as text, one per line or a CSV with a question,expect header. expect is words the answer must contain to pass. Safe to repeat: a question already in the set is skipped.' +
332
+ SCOPE,
333
+ inputSchema: {
334
+ type: 'object',
335
+ properties: {
336
+ workspace: WORKSPACE,
337
+ question: { type: 'string' },
338
+ expect: { type: 'string', description: 'Words the answer must contain to pass (optional).' },
339
+ questions: {
340
+ type: 'array',
341
+ items: { type: 'object', properties: { question: { type: 'string' }, expect: { type: 'string' } }, required: ['question'] },
342
+ },
343
+ text: { type: 'string', description: 'One question per line, or a CSV with a question,expect header.' },
344
+ },
345
+ },
346
+ },
347
+ {
348
+ name: 'workover_support_agent_generate_tests',
349
+ description:
350
+ "Fill the batch test from the inbox: the first visitor message of recent conversations, up to 50 questions. Questions already in the set are skipped." +
351
+ SCOPE,
352
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
353
+ },
354
+ {
355
+ name: 'workover_support_agent_remove_test',
356
+ description: 'Remove a question from the batch test. Safe to repeat.' + SCOPE,
357
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, testId: { type: 'number' } }, required: ['testId'] },
358
+ },
359
+ {
360
+ name: 'workover_support_agent_run_tests',
361
+ description:
362
+ 'Ask the AI agent every question in the batch test, against the draft (default) or the live version. Nothing is sent to anyone and no conversation is created; each question uses one answer from the day\'s allowance. With wait (default true) it follows the run for up to two minutes; otherwise, or if still running, read it with workover_support_agent_test_run. A run already going is shown rather than started again.' +
363
+ SCOPE,
364
+ inputSchema: {
365
+ type: 'object',
366
+ properties: {
367
+ workspace: WORKSPACE,
368
+ target: { type: 'string', enum: TARGETS },
369
+ wait: { type: 'boolean', description: 'Follow the run until it is done (up to two minutes). Default true.' },
370
+ },
371
+ },
372
+ },
373
+ {
374
+ name: 'workover_support_agent_test_run',
375
+ description: 'One batch test run: its status, counts, and every answer with its id, check and rating.' + SCOPE,
376
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, runId: { type: 'number' } }, required: ['runId'] },
377
+ },
378
+ {
379
+ name: 'workover_support_agent_rate_result',
380
+ description: 'Rate one batch test answer good or bad (null clears it), with an optional note.' + SCOPE,
381
+ inputSchema: {
382
+ type: 'object',
383
+ properties: {
384
+ workspace: WORKSPACE,
385
+ resultId: { type: 'number' },
386
+ rating: { type: ['string', 'null'], enum: ['good', 'bad', null] },
387
+ note: { type: ['string', 'null'] },
388
+ },
389
+ required: ['resultId'],
390
+ },
391
+ },
392
+ ];
393
+
394
+ /** Every tool name above, for the dispatcher. */
395
+ export const AGENT_TEST_TOOLS = new Set(AGENT_TEST_TOOL_DEFS.map((t) => t.name));
396
+
397
+ /** Run one of the tools above; resolves the lines of its answer. */
398
+ export async function runAgentTestTool(call, name, args = {}, { sleep, now } = {}) {
399
+ const workspace = args.workspace === undefined || args.workspace === null ? undefined : String(args.workspace);
400
+ if (name === 'workover_support_agent_releases') return renderReleases(await listReleases(call, { workspace }));
401
+ if (name === 'workover_support_agent_set_live') return renderSetLive(await setLive(call, { workspace, note: args.note }));
402
+ if (name === 'workover_support_agent_rollback') return renderRollback(await rollback(call, { workspace, version: args.version }));
403
+ if (name === 'workover_support_agent_tests') return renderTests(await listTests(call, { workspace }));
404
+ if (name === 'workover_support_agent_add_tests')
405
+ return renderAdded(
406
+ await addTests(call, { workspace, question: args.question, expect: args.expect, questions: args.questions, text: args.text }),
407
+ );
408
+ if (name === 'workover_support_agent_generate_tests') return renderAdded(await generateTests(call, { workspace }));
409
+ if (name === 'workover_support_agent_remove_test') return renderRemoved(await removeTest(call, { workspace, testId: args.testId }));
410
+ if (name === 'workover_support_agent_run_tests')
411
+ return renderRunStarted(
412
+ await runTests(call, {
413
+ workspace,
414
+ target: args.target,
415
+ wait: args.wait !== false,
416
+ ...(sleep ? { sleep } : {}),
417
+ ...(now ? { now } : {}),
418
+ }),
419
+ );
420
+ if (name === 'workover_support_agent_test_run') return ['', ...renderRun((await getRun(call, { workspace, runId: args.runId })).run), ''];
421
+ if (name === 'workover_support_agent_rate_result')
422
+ return renderRated(await rateResult(call, { workspace, resultId: args.resultId, rating: args.rating, note: args.note }));
423
+ throw apiError(400, `Unknown tool: ${name}`);
424
+ }