@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,310 @@
1
+ // Walter AI, Support's AI agent, from a terminal: `workover support walter get|set|publish|discard|
2
+ // preview|changelog` and the MCP server's `workover_support_walter*` tools (WO-1752, S57).
3
+ //
4
+ // THE SAME FILE ships in @workover/cli (apps/cli/support-walter.mjs) and @workover/mcp
5
+ // (apps/mcp/support-walter.mjs), because the two packages are published separately and neither
6
+ // may depend on the other. `apps/mcp/support-walter.test.mjs` fails when the copies differ.
7
+ //
8
+ // Walter's Train pages keep one draft: Guidance Basics (a tone and an answer length) and new guidance
9
+ // lines. Nothing reaches visitors until it is set live; the preview answers with it. `get` also
10
+ // reads the Deploy > Messenger checklist, five rows each done or to do, so an agent can check what is
11
+ // left. Every step is safe to repeat and answers the state, so an agent can check its result: after
12
+ // `publish`, `dirty` is false and `basics` holds the new values.
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 TONES = ['friendly', 'neutral', 'matter_of_fact', 'professional', 'humorous'];
21
+ export const LENGTHS = ['concise', 'standard', 'thorough'];
22
+
23
+ /** The Messenger Walter answers in: Support has to exist first. */
24
+ async function messengerOf(call, workspace) {
25
+ const ws = await resolveWorkspace(call, workspace);
26
+ const status = await call(`/messenger/agent-setup?organizationId=${encodeURIComponent(ws.id)}`);
27
+ const id = status?.messenger?.id;
28
+ if (!id) throw apiError(404, 'Support is not set up in this workspace yet. Run `workover support setup` first.');
29
+ return { ws, messengerId: id };
30
+ }
31
+
32
+ const base = (messengerId) => `/messenger/${encodeURIComponent(messengerId)}/walter`;
33
+
34
+ /**
35
+ * A draft change, checked before anything is sent: `tone` and `answerLength` (a value, or null for
36
+ * no line) and `guidance` (the whole list of new lines, each a string or `{ text, kind, audience }`).
37
+ * Anything else is refused by name, so a typo is never silently dropped.
38
+ */
39
+ export function pickDraft(changes) {
40
+ if (!changes || typeof changes !== 'object' || Array.isArray(changes))
41
+ throw apiError(400, 'Give the draft change as an object, such as {"tone":"friendly"}.');
42
+ const out = {};
43
+ for (const [k, v] of Object.entries(changes)) {
44
+ if (v === undefined) continue;
45
+ if (k === 'tone') {
46
+ if (v !== null && !TONES.includes(v)) throw apiError(400, `The tone is one of: ${TONES.join(', ')}, or null. Nothing was changed.`);
47
+ out.tone = v;
48
+ } else if (k === 'answerLength') {
49
+ if (v !== null && !LENGTHS.includes(v)) throw apiError(400, `The answer length is one of: ${LENGTHS.join(', ')}, or null. Nothing was changed.`);
50
+ out.answerLength = v;
51
+ } else if (k === 'guidance') {
52
+ if (!Array.isArray(v)) throw apiError(400, 'guidance is a list of lines. Nothing was changed.');
53
+ out.guidance = v.map((g) => (typeof g === 'string' ? { text: g } : g));
54
+ } else {
55
+ throw apiError(400, `"${k}" is not part of Walter's draft. Use tone, answerLength or guidance. Nothing was changed.`);
56
+ }
57
+ }
58
+ if (!Object.keys(out).length) throw apiError(400, 'Nothing to change: give a tone, an answer length or guidance.');
59
+ return out;
60
+ }
61
+
62
+ /** Basics, the draft and the Deploy checklist. */
63
+ export async function walterGet(call, { workspace } = {}) {
64
+ const { ws, messengerId } = await messengerOf(call, workspace);
65
+ const state = await call(base(messengerId));
66
+ // Walter's sources, guidance lines and snippets wait in a second draft, the one the Train and Test
67
+ // pages' "Set live" bar counts. Read it too, so this agrees with the page (journey "Visitor gets an
68
+ // answer" r2, M5: the page said 6 changes while this said "No draft."). An api without it, or one
69
+ // that refuses, leaves it out rather than failing the read.
70
+ let releaseChanges;
71
+ try {
72
+ const rel = await call(`/messenger/${messengerId}/agent-releases`);
73
+ if (Array.isArray(rel?.changes)) releaseChanges = rel.changes;
74
+ } catch {
75
+ releaseChanges = undefined;
76
+ }
77
+ return { workspace: ws, ...state, ...(releaseChanges ? { releaseChanges } : {}) };
78
+ }
79
+
80
+ /**
81
+ * Lay a change over the draft. `addGuidance` appends lines to the ones already staged (the API takes
82
+ * the whole list, so they are read first). With `publish: true` the draft is set live straight after.
83
+ */
84
+ export async function walterSet(call, { workspace, changes = {}, addGuidance, publish = false } = {}) {
85
+ const add = addGuidance === undefined ? [] : Array.isArray(addGuidance) ? addGuidance : [addGuidance];
86
+ const body = pickDraft({ ...changes, ...(add.length ? { guidance: changes.guidance ?? [] } : {}) });
87
+ const { ws, messengerId } = await messengerOf(call, workspace);
88
+ if (add.length) {
89
+ // Given `guidance` replaces the staged lines; otherwise the new ones join what is staged.
90
+ let kept = body.guidance;
91
+ if (changes.guidance === undefined) {
92
+ const now = await call(base(messengerId));
93
+ kept = (now?.draft?.guidance ?? []).map(({ text, kind, audience }) => ({ text, kind, audience }));
94
+ }
95
+ body.guidance = [...kept, ...add.map((g) => (typeof g === 'string' ? { text: g } : g))];
96
+ }
97
+ const state = await call(`${base(messengerId)}/draft`, { method: 'PUT', body });
98
+ if (!publish) return { workspace: ws, published: null, ...state };
99
+ const res = await call(`${base(messengerId)}/draft/publish`, { method: 'POST' });
100
+ return { workspace: ws, published: res.published, ...res.state };
101
+ }
102
+
103
+ /** Set the draft live in one change. With nothing pending it changes nothing (`published: []`). */
104
+ export async function walterPublish(call, { workspace } = {}) {
105
+ const { ws, messengerId } = await messengerOf(call, workspace);
106
+ const res = await call(`${base(messengerId)}/draft/publish`, { method: 'POST' });
107
+ return { workspace: ws, published: res.published, ...res.state };
108
+ }
109
+
110
+ /** Throw the draft away. Visitors keep the live Basics and guidance. */
111
+ export async function walterDiscard(call, { workspace } = {}) {
112
+ const { ws, messengerId } = await messengerOf(call, workspace);
113
+ return { workspace: ws, ...(await call(`${base(messengerId)}/draft`, { method: 'DELETE' })) };
114
+ }
115
+
116
+ /** Ask the draft a question as an anonymous visitor. Nothing is stored; it spends the AI allowance. */
117
+ export async function walterPreview(call, { workspace, question } = {}) {
118
+ if (typeof question !== 'string' || question.trim().length < 3) throw apiError(400, 'Ask a question of three characters or more.');
119
+ const { ws, messengerId } = await messengerOf(call, workspace);
120
+ const res = await call(`${base(messengerId)}/preview`, { method: 'POST', body: { question: question.trim() } });
121
+ return { workspace: ws, question: question.trim(), ...res };
122
+ }
123
+
124
+ /** Who changed Walter, and when, newest first. */
125
+ export async function walterChangelog(call, { workspace, cursor } = {}) {
126
+ const { ws, messengerId } = await messengerOf(call, workspace);
127
+ const q = cursor ? `?cursor=${encodeURIComponent(cursor)}` : '';
128
+ return { workspace: ws, ...(await call(`${base(messengerId)}/changelog${q}`)) };
129
+ }
130
+
131
+ // ------------------------------------------------------------------ rendering
132
+
133
+ /** A tone or a length as the page names it: "Default" when unset, "Matter of fact" (r2, M5). */
134
+ const label = (v) => {
135
+ if (v === null || v === undefined || v === '') return 'Default';
136
+ const words = String(v).replace(/_/g, ' ');
137
+ return words.charAt(0).toUpperCase() + words.slice(1);
138
+ };
139
+
140
+ const AREA_WORD = {
141
+ guidance: 'Guidance',
142
+ snippets: 'Snippet',
143
+ sources: 'Source',
144
+ small_talk: 'Small talk',
145
+ known_links: 'Known link',
146
+ };
147
+
148
+ /** "Source removed: refund.pdf", as the Train pages' Set live bar lists a change. */
149
+ const changeLine = (c) =>
150
+ `${AREA_WORD[c.area] ?? c.area} ${c.change}${c.label ? `: ${c.label}` : ''}`;
151
+
152
+ /** Basics, what is pending, and the Deploy checklist. */
153
+ export function renderWalter(res) {
154
+ const where = res.workspace?.name ?? 'this workspace';
155
+ const out = [''];
156
+ if (Array.isArray(res.published)) {
157
+ out.push(
158
+ res.published.length
159
+ ? ` ✓ Set live in ${where}: ${res.published.join(', ')}. The next answer uses it.`
160
+ : ` ✓ Nothing was pending in ${where}; nothing changed.`,
161
+ );
162
+ }
163
+ out.push(` Walter AI in ${where}`);
164
+ out.push(` Tone: ${label(res.basics?.tone)} Answer length: ${label(res.basics?.answerLength)}`);
165
+ if (res.dirty) {
166
+ out.push('', ' Draft (visitors do not see it yet; the preview does):');
167
+ if ((res.fields || []).includes('tone')) out.push(` tone: ${label(res.basics?.tone)} → ${label(res.draft?.tone)}`);
168
+ if ((res.fields || []).includes('answerLength'))
169
+ out.push(` answer length: ${label(res.basics?.answerLength)} → ${label(res.draft?.answerLength)}`);
170
+ for (const g of res.draft?.guidance || []) out.push(` + ${g.kind === 'tone' ? 'Tone' : 'Rule'}: ${g.text}`);
171
+ out.push('', ' `workover support walter publish` sets it live; `discard` throws it away.');
172
+ }
173
+ const pending = res.releaseChanges || [];
174
+ if (pending.length) {
175
+ out.push(
176
+ '',
177
+ ` Sources and guidance waiting to be set live (${pending.length} ${pending.length === 1 ? 'change' : 'changes'}):`,
178
+ );
179
+ for (const c of pending) out.push(` ${changeLine(c)}`);
180
+ out.push('', ' `workover support releases set-live` sets them live.');
181
+ }
182
+ if (!res.dirty && !pending.length) out.push(' No draft.');
183
+ const d = res.deploy;
184
+ if (d) {
185
+ out.push('', ` Deploy to the Messenger: ${d.enabled ? 'on' : 'off'}, ${d.done} of ${d.rows.length} done`);
186
+ for (const r of d.rows) out.push(` ${r.done ? '✓' : '○'} ${r.label}: ${r.summary}`);
187
+ }
188
+ out.push('');
189
+ return out;
190
+ }
191
+
192
+ /** The preview's answer, its confidence and what it cited. */
193
+ export function renderPreview(res) {
194
+ const out = ['', ` Q: ${res.question}`];
195
+ if (res.answer) out.push(` Walter: ${res.answer}`);
196
+ else out.push(` Walter would not answer${res.failed ? ` (${res.failed})` : ''}; a person would take it.`);
197
+ if (res.confidence !== null && res.confidence !== undefined)
198
+ out.push(` Confidence: ${Math.round(res.confidence * 100)}%${res.handoff ? ', hands over' : ''}`);
199
+ for (const c of res.citations || []) out.push(` Source: ${c.title} ${c.url}`);
200
+ const pending = [...(res.draft?.walter || []), ...(res.draft?.messenger || [])];
201
+ if (pending.length) out.push(` Answered with the draft: ${pending.join(', ')}`);
202
+ out.push(' Nothing was stored.', '');
203
+ return out;
204
+ }
205
+
206
+ /** The changelog, one entry a line. */
207
+ export function renderChangelog(res) {
208
+ const out = [''];
209
+ if (!res.entries?.length) out.push(' No changes to Walter yet.');
210
+ for (const e of res.entries || []) {
211
+ const who = [e.actor?.name || 'Someone', e.actor?.agentName ? `via ${e.actor.agentName}` : null].filter(Boolean).join(' ');
212
+ out.push(` ${e.at.slice(0, 16).replace('T', ' ')} ${who}: ${e.summary}`);
213
+ // The settings' own words where the api gives them (r2, M6), never "first" or "away".
214
+ for (const f of e.fields || []) {
215
+ if (f.beforeText === undefined && f.afterText === undefined) continue;
216
+ const before = f.beforeText ?? (f.before == null ? 'None' : String(f.before));
217
+ const after = f.afterText ?? (f.after == null ? 'None' : String(f.after));
218
+ out.push(` ${f.label}: ${before} → ${after}`);
219
+ }
220
+ }
221
+ if (res.nextCursor) out.push('', ` More: --cursor ${res.nextCursor}`);
222
+ out.push('');
223
+ return out;
224
+ }
225
+
226
+ // ------------------------------------------------------------------ MCP tools
227
+
228
+ const WORKSPACE = {
229
+ type: ['string', 'number'],
230
+ description: 'The workspace, by slug or id. Needed only when the account has more than one.',
231
+ };
232
+ const SCOPE =
233
+ ' Needs a token from `workover login --support`; without it this returns a permission error naming that command.';
234
+
235
+ /** The MCP server's Walter AI tools, listed with the other Support tools (index.mjs). */
236
+ export const WALTER_TOOL_DEFS = [
237
+ {
238
+ name: 'workover_support_walter',
239
+ description:
240
+ "Walter AI, Support's AI agent: its Guidance Basics (tone and answer length), the draft waiting to be set live, and the Deploy > Messenger checklist (five rows, each done or to do). Without changes it reads. With `tone`, `answerLength`, `guidance` (replaces the staged lines) or `addGuidance` (appends lines) it changes the draft; visitors see nothing until it is published (pass `publish: true`, or call workover_support_walter_publish). Safe to repeat." +
241
+ SCOPE,
242
+ inputSchema: {
243
+ type: 'object',
244
+ properties: {
245
+ workspace: WORKSPACE,
246
+ tone: { type: ['string', 'null'], enum: [...TONES, null], description: 'How Walter writes; null for no tone line.' },
247
+ answerLength: { type: ['string', 'null'], enum: [...LENGTHS, null], description: 'How long its answers are; null for no length line.' },
248
+ guidance: {
249
+ type: 'array',
250
+ description: 'The whole list of new guidance lines waiting to be set live: strings, or { text, kind: tone|rule, audience: everyone|signed_in|anonymous }.',
251
+ items: { type: ['string', 'object'] },
252
+ },
253
+ addGuidance: {
254
+ type: 'array',
255
+ description: 'Lines to add to the ones already staged, such as ["Always end with \'Anything else?\'"].',
256
+ items: { type: ['string', 'object'] },
257
+ },
258
+ publish: { type: 'boolean', description: 'Set the draft live straight after the change.' },
259
+ },
260
+ },
261
+ },
262
+ {
263
+ name: 'workover_support_walter_preview',
264
+ description:
265
+ 'Ask Walter a question the way an anonymous visitor would, answered with the draft (Basics and staged guidance) and the Messenger editor’s pending name and confidence. Shows the answer, its confidence and what it cited. Nothing is stored and no conversation is made; it spends the workspace’s AI allowance.' +
266
+ SCOPE,
267
+ inputSchema: {
268
+ type: 'object',
269
+ required: ['question'],
270
+ properties: { workspace: WORKSPACE, question: { type: 'string', description: 'The visitor’s question.' } },
271
+ },
272
+ },
273
+ {
274
+ name: 'workover_support_walter_publish',
275
+ description:
276
+ "Set Walter's draft live in one change: Basics, and each staged line becomes a guidance line. With nothing pending it changes nothing. Ask the person first: the next answer on their live site uses it." +
277
+ SCOPE,
278
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
279
+ },
280
+ {
281
+ name: 'workover_support_walter_discard',
282
+ description: "Throw Walter's draft away; visitors keep the live Basics and guidance. Safe to repeat." + SCOPE,
283
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE } },
284
+ },
285
+ {
286
+ name: 'workover_support_walter_changelog',
287
+ description: "Who changed Walter's configuration and when, newest first (switch, name, confidence, limits, docs, sources, drafts set live)." + SCOPE,
288
+ inputSchema: { type: 'object', properties: { workspace: WORKSPACE, cursor: { type: 'string' } } },
289
+ },
290
+ ];
291
+
292
+ export const WALTER_TOOLS = new Set(WALTER_TOOL_DEFS.map((t) => t.name));
293
+
294
+ /** Runs one of WALTER_TOOLS and answers its lines. Throws what the api threw. */
295
+ export async function walterTool(call, name, args = {}) {
296
+ const workspace = args.workspace === undefined || args.workspace === null ? undefined : String(args.workspace);
297
+ if (name === 'workover_support_walter') {
298
+ const changes = {};
299
+ for (const k of ['tone', 'answerLength', 'guidance']) if (args[k] !== undefined) changes[k] = args[k];
300
+ if (!Object.keys(changes).length && args.addGuidance === undefined) return renderWalter(await walterGet(call, { workspace }));
301
+ if (args.publish !== undefined && typeof args.publish !== 'boolean') throw apiError(400, 'publish is true or false. Nothing was changed.');
302
+ return renderWalter(await walterSet(call, { workspace, changes, addGuidance: args.addGuidance, publish: args.publish === true }));
303
+ }
304
+ if (name === 'workover_support_walter_preview') return renderPreview(await walterPreview(call, { workspace, question: args.question }));
305
+ if (name === 'workover_support_walter_publish') return renderWalter(await walterPublish(call, { workspace }));
306
+ if (name === 'workover_support_walter_discard') return renderWalter(await walterDiscard(call, { workspace }));
307
+ if (name === 'workover_support_walter_changelog')
308
+ return renderChangelog(await walterChangelog(call, { workspace, cursor: typeof args.cursor === 'string' ? args.cursor : undefined }));
309
+ throw apiError(400, `Unknown tool: ${name}`);
310
+ }