qualiloop 0.0.0-stage → 0.2.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/LICENSE +202 -0
- package/README.md +258 -3
- package/dist/api.js +165 -0
- package/dist/auth.js +73 -0
- package/dist/catalog.js +24 -0
- package/dist/catalog.json +7943 -0
- package/dist/cli.js +2777 -0
- package/dist/config.js +76 -0
- package/dist/connect.js +357 -0
- package/dist/export.js +114 -0
- package/dist/mcp/install.js +142 -0
- package/dist/mcp/server.js +523 -0
- package/dist/output.js +43 -0
- package/dist/workflows.js +147 -0
- package/package.json +47 -4
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2777 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { basename, resolve as resolvePath } from 'node:path';
|
|
4
|
+
import { createInterface } from 'node:readline/promises';
|
|
5
|
+
import { Command, CommanderError, Help, Option } from 'commander';
|
|
6
|
+
import { ApiError, EXIT, QualiloopClient, VERSION } from './api.js';
|
|
7
|
+
import { login } from './auth.js';
|
|
8
|
+
import { bundledCatalog, bundledGuide, loadCatalog } from './catalog.js';
|
|
9
|
+
import { credentialsPath, forgetCredentials, resolveProject, setDefaultProject, storedCredentials, } from './config.js';
|
|
10
|
+
import * as connect from './connect.js';
|
|
11
|
+
import { EXPORT_FORMATS, dateOr, exportFormat, fetchCorrectedPairs } from './export.js';
|
|
12
|
+
import { CLIENTS, DEFAULT_CLIENTS, install, snippets } from './mcp/install.js';
|
|
13
|
+
import { serveStdio } from './mcp/server.js';
|
|
14
|
+
import { fields, output, table } from './output.js';
|
|
15
|
+
import { cancelGeneration, compareBatch, comparisonText, getGeneration, runsExitCode, startGateWithKey, startGeneration, waitForBatch, waitForGateRun, waitForGateRunWithKey, waitForGeneration, } from './workflows.js';
|
|
16
|
+
const program = new Command();
|
|
17
|
+
const USE_EACH = `
|
|
18
|
+
Short form:
|
|
19
|
+
ql is the same command: ql suites run core --wait
|
|
20
|
+
|
|
21
|
+
Start here:
|
|
22
|
+
qualiloop guide how to use these commands well: what to run, in what order
|
|
23
|
+
qualiloop connect connect the agent in this codebase: sign in, choose the
|
|
24
|
+
project, write its key into .env, print the steps
|
|
25
|
+
qualiloop connect guide the steps to connect an agent in this codebase to QualiLoop
|
|
26
|
+
|
|
27
|
+
CLI or MCP?
|
|
28
|
+
Both use the same sign-in and run the same actions, so either one does
|
|
29
|
+
everything. Pick one and use it for everything.
|
|
30
|
+
The CLI (qualiloop ...) suits a terminal, scripts, CI, and coding agents
|
|
31
|
+
that can run commands, such as Claude Code, Cursor or Codex.
|
|
32
|
+
The MCP server (qualiloop mcp) suits chat apps and agents that cannot run
|
|
33
|
+
commands, such as Claude Desktop. Set it up with: qualiloop mcp install
|
|
34
|
+
|
|
35
|
+
Exit codes:
|
|
36
|
+
0 done; with --wait, everything passed
|
|
37
|
+
1 what was checked failed: a gate said fail, a run found a major problem
|
|
38
|
+
2 the command or its arguments were wrong
|
|
39
|
+
3 not signed in, the sign-in ended, or your role cannot do this
|
|
40
|
+
4 not found
|
|
41
|
+
5 waited longer than --timeout
|
|
42
|
+
6 QualiLoop could not be reached or answered with an error
|
|
43
|
+
|
|
44
|
+
Environment:
|
|
45
|
+
QUALILOOP_URL the QualiLoop address (default https://app.qualiloop.com)
|
|
46
|
+
QUALILOOP_TOKEN a CLI sign-in token, for CI instead of qualiloop login
|
|
47
|
+
QUALILOOP_GATE_KEY a release gate's deploy key, for qualiloop gate run in CI
|
|
48
|
+
QUALILOOP_PROJECT the project to use when --project is not given
|
|
49
|
+
QUALILOOP_SETUP_TOKEN a project setup token for qualiloop connect; when set, it is
|
|
50
|
+
used instead of the sign-in, on the token's own project
|
|
51
|
+
`;
|
|
52
|
+
program
|
|
53
|
+
.name('qualiloop')
|
|
54
|
+
.description('QualiLoop from the terminal, scripts, CI and coding agents.')
|
|
55
|
+
.version(VERSION)
|
|
56
|
+
.option('--url <url>', 'the QualiLoop address (or QUALILOOP_URL)')
|
|
57
|
+
.option('--json', 'print the result as JSON, for scripts')
|
|
58
|
+
.option('-p, --project <project>', 'the project: its number or name (or QUALILOOP_PROJECT)')
|
|
59
|
+
.addHelpText('after', USE_EACH)
|
|
60
|
+
.showHelpAfterError('(add --help for usage)')
|
|
61
|
+
.exitOverride();
|
|
62
|
+
const run = (handler) => async (...args) => {
|
|
63
|
+
const command = args[args.length - 1];
|
|
64
|
+
const opts = command.optsWithGlobals();
|
|
65
|
+
const client = new QualiloopClient({ url: opts.url, kind: 'cli' });
|
|
66
|
+
const ctx = {
|
|
67
|
+
client,
|
|
68
|
+
out: output(Boolean(opts.json)),
|
|
69
|
+
project: resolveProject(client.url, opts.project),
|
|
70
|
+
opts,
|
|
71
|
+
command,
|
|
72
|
+
};
|
|
73
|
+
try {
|
|
74
|
+
const code = await handler(ctx, ...args.slice(0, -1));
|
|
75
|
+
process.exitCode = code ?? EXIT.ok;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
if (error instanceof ApiError) {
|
|
79
|
+
if (ctx.out.json) {
|
|
80
|
+
process.stdout.write(`${JSON.stringify({ error: error.message, status: error.status }, null, 2)}\n`);
|
|
81
|
+
}
|
|
82
|
+
else
|
|
83
|
+
process.stderr.write(`qualiloop: ${error.message}\n`);
|
|
84
|
+
process.exitCode = error.exitCode;
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
process.stderr.write(`qualiloop: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
88
|
+
process.exitCode = EXIT.server;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const intArg = (value) => {
|
|
92
|
+
const parsed = Number.parseInt(value.replace(/^#/, ''), 10);
|
|
93
|
+
if (!Number.isFinite(parsed))
|
|
94
|
+
throw new ApiError(`${value} is not a number.`, 400, EXIT.usage);
|
|
95
|
+
return parsed;
|
|
96
|
+
};
|
|
97
|
+
const readText = (file) => {
|
|
98
|
+
try {
|
|
99
|
+
return readFileSync(file === '-' ? 0 : file, 'utf8');
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
throw new ApiError(`Cannot read ${file}: ${error.message}`, 400, EXIT.usage);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const limitOption = (what, fallback, most) => new Option('--limit <n>', `most ${what} to show (up to ${most})`).default(fallback);
|
|
106
|
+
const limitOf = (opts, most) => {
|
|
107
|
+
const limit = intArg(String(opts.limit));
|
|
108
|
+
if (limit < 1 || limit > most)
|
|
109
|
+
throw new ApiError(`--limit takes 1 to ${most}.`, 400, EXIT.usage);
|
|
110
|
+
return limit;
|
|
111
|
+
};
|
|
112
|
+
const listed = (rendered, shown, total, empty) => {
|
|
113
|
+
if (!rendered)
|
|
114
|
+
return empty;
|
|
115
|
+
if (total === undefined || total <= shown)
|
|
116
|
+
return rendered;
|
|
117
|
+
return `${rendered}\n\n${shown} of ${total} shown. See more with --limit ${total}.`;
|
|
118
|
+
};
|
|
119
|
+
const projectFlag = (ctx) => {
|
|
120
|
+
const given = ctx.opts.project;
|
|
121
|
+
if (!given)
|
|
122
|
+
return '';
|
|
123
|
+
return ` -p ${/^[\w#.-]+$/.test(given) ? given : JSON.stringify(given)}`;
|
|
124
|
+
};
|
|
125
|
+
const confirm = async (question) => {
|
|
126
|
+
if (!process.stdin.isTTY) {
|
|
127
|
+
throw new ApiError(`${question} Add --yes to answer without a terminal.`, 400, EXIT.usage);
|
|
128
|
+
}
|
|
129
|
+
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
130
|
+
try {
|
|
131
|
+
return /^y(es)?$/i.test((await prompt.question(`${question} [y/N] `)).trim());
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
prompt.close();
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const failOnOption = () => new Option('--fail-on <severity>', 'with --wait, exit 1 when a run has a problem this bad')
|
|
138
|
+
.choices(['major', 'minor', 'none'])
|
|
139
|
+
.default('major');
|
|
140
|
+
const browserLogin = (client, out, browser) => login(client, {
|
|
141
|
+
browser,
|
|
142
|
+
onStarted: ({ url, code, opened, expiresIn }) => {
|
|
143
|
+
out.progress(`${opened ? 'Opened' : 'Open'} ${url}\n` +
|
|
144
|
+
`Check that the page shows ${code}, then approve. No account yet? Create one from that page.`);
|
|
145
|
+
const minutes = Math.max(1, Math.round(expiresIn / 60));
|
|
146
|
+
out.progress(`Waiting for approval, up to ${minutes} minutes. This carries on by itself once it is approved...`);
|
|
147
|
+
},
|
|
148
|
+
});
|
|
149
|
+
const signedInAs = (result) => `Signed in to ${result.url} as ${result.user?.email ?? 'you'}` +
|
|
150
|
+
(result.user?.organization_name ? ` (${result.user.organization_name})` : '') +
|
|
151
|
+
'.';
|
|
152
|
+
const viaNpx = () => process.env.npm_command === 'exec' || /[\\/]_npx[\\/]/.test(process.argv[1] ?? '');
|
|
153
|
+
const invocation = () => (viaNpx() ? 'npx qualiloop' : 'qualiloop');
|
|
154
|
+
program
|
|
155
|
+
.command('login')
|
|
156
|
+
.description('Sign in by approving the CLI in your browser.')
|
|
157
|
+
.option('--no-browser', 'print the link instead of opening it')
|
|
158
|
+
.action(run(async ({ client, out, opts }) => {
|
|
159
|
+
const result = await browserLogin(client, out, opts.browser !== false);
|
|
160
|
+
out.result(result, () => `${signedInAs(result)}\nThe sign-in is stored in ${credentialsPath()}.`);
|
|
161
|
+
}));
|
|
162
|
+
program
|
|
163
|
+
.command('logout')
|
|
164
|
+
.description('Sign out: revoke this sign-in and forget it.')
|
|
165
|
+
.action(run(async ({ client, out }) => {
|
|
166
|
+
if (storedCredentials(client.url)) {
|
|
167
|
+
try {
|
|
168
|
+
await client.request('DELETE', '/v1/cli/token');
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (!(error instanceof ApiError) || error.exitCode !== EXIT.auth)
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const forgot = forgetCredentials(client.url);
|
|
176
|
+
out.result({ signed_out: forgot, url: client.url }, () => forgot ? `Signed out of ${client.url}.` : `Not signed in to ${client.url}.`);
|
|
177
|
+
}));
|
|
178
|
+
program
|
|
179
|
+
.command('whoami')
|
|
180
|
+
.description('Who you are signed in as, where, and the default project.')
|
|
181
|
+
.action(run(async ({ client, out, project }) => {
|
|
182
|
+
const me = await client.request('GET', '/v1/auth/me');
|
|
183
|
+
const stored = storedCredentials(client.url);
|
|
184
|
+
const data = { url: client.url, ...me, organization: stored?.user?.organization_name, project };
|
|
185
|
+
out.result(data, () => fields([
|
|
186
|
+
['QualiLoop', client.url],
|
|
187
|
+
['Email', me.email],
|
|
188
|
+
['Role', me.role],
|
|
189
|
+
['Organization', stored?.user?.organization_name],
|
|
190
|
+
['Default project', project],
|
|
191
|
+
]));
|
|
192
|
+
}));
|
|
193
|
+
const tokens = program.command('tokens').description('Your CLI and MCP sign-ins.');
|
|
194
|
+
tokens
|
|
195
|
+
.command('list', { isDefault: true })
|
|
196
|
+
.description('List your CLI and MCP sign-ins.')
|
|
197
|
+
.action(run(async ({ client, out }) => {
|
|
198
|
+
const rows = await client.request('GET', '/v1/cli/tokens');
|
|
199
|
+
out.result(rows, () => table(rows, [
|
|
200
|
+
['id', 'ID'],
|
|
201
|
+
['name', 'Name', 40],
|
|
202
|
+
['current', 'This one'],
|
|
203
|
+
['last_used_at', 'Last used', 20],
|
|
204
|
+
['expires_at', 'Expires', 20],
|
|
205
|
+
]) || 'No sign-ins.');
|
|
206
|
+
}));
|
|
207
|
+
tokens
|
|
208
|
+
.command('revoke <id>')
|
|
209
|
+
.description('Revoke one sign-in; it stops working at once.')
|
|
210
|
+
.action(run(async ({ client, out }, id) => {
|
|
211
|
+
const revoked = await client.request('DELETE', `/v1/cli/tokens/${intArg(id)}`);
|
|
212
|
+
out.result(revoked, () => `Revoked ${revoked.name}.`);
|
|
213
|
+
}));
|
|
214
|
+
const projects = program.command('projects').description('Your projects.');
|
|
215
|
+
projects
|
|
216
|
+
.command('list', { isDefault: true })
|
|
217
|
+
.description('List the projects of your organization.')
|
|
218
|
+
.action(run(async ({ client, out, project }) => {
|
|
219
|
+
const result = await client.action('list_projects');
|
|
220
|
+
out.result(result, () => table(result.projects.map((row) => ({ ...row, default: String(row.number) === String(project) || row.name === project })), [
|
|
221
|
+
['number', '#'],
|
|
222
|
+
['name', 'Name', 50],
|
|
223
|
+
['live_data_enabled', 'Live'],
|
|
224
|
+
['default', 'Default'],
|
|
225
|
+
]) || 'No projects yet.');
|
|
226
|
+
}));
|
|
227
|
+
projects
|
|
228
|
+
.command('show [project]')
|
|
229
|
+
.description('A project at a glance: its agent and how its tests went.')
|
|
230
|
+
.option('--days <n>', 'days of results to count', '30')
|
|
231
|
+
.action(run(async ({ client, out, project, opts }, given) => {
|
|
232
|
+
const result = await client.action('get_project', {
|
|
233
|
+
project: given ?? project,
|
|
234
|
+
window_days: intArg(String(opts.days)),
|
|
235
|
+
});
|
|
236
|
+
out.result(result, () => fields([
|
|
237
|
+
['Project', `#${result.number} ${result.name}`],
|
|
238
|
+
['Agent', result.agent.connected ? result.agent.endpoint : 'not connected (qualiloop connect)'],
|
|
239
|
+
['Traces from', result.agent.traces_from],
|
|
240
|
+
['Live traffic', result.live_data_enabled],
|
|
241
|
+
[`Tests (${result.stats.window_days} days)`, `${result.stats.tests_passed}/${result.stats.tests_finished} passed (${result.stats.test_pass_rate_pct ?? '-'})`],
|
|
242
|
+
['Major problems', result.stats.major_problems],
|
|
243
|
+
['Minor problems', result.stats.minor_problems],
|
|
244
|
+
['Link', result.url],
|
|
245
|
+
]));
|
|
246
|
+
}));
|
|
247
|
+
projects
|
|
248
|
+
.command('use <project>')
|
|
249
|
+
.description('Make a project the default for this QualiLoop address.')
|
|
250
|
+
.action(run(async ({ client, out }, given) => {
|
|
251
|
+
const result = await client.action('get_project', { project: given });
|
|
252
|
+
setDefaultProject(client.url, String(result.number));
|
|
253
|
+
out.result({ project: result.number, name: result.name }, () => `Commands now use project #${result.number} ${result.name}.`);
|
|
254
|
+
}));
|
|
255
|
+
projects
|
|
256
|
+
.command('delete <project>')
|
|
257
|
+
.description('Delete a project with its tests, runs, conversations and results. Admins only.')
|
|
258
|
+
.option('--yes', 'delete without asking')
|
|
259
|
+
.action(run(async ({ client, out, opts }, given) => {
|
|
260
|
+
if (!opts.yes) {
|
|
261
|
+
const found = await client.action('get_project', { project: given });
|
|
262
|
+
if (!(await confirm(`Delete project #${found.number} ${found.name} with everything in it?`))) {
|
|
263
|
+
out.result({ deleted: false, project: found.number }, () => 'Not deleted.');
|
|
264
|
+
return EXIT.ok;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const result = await client.action('delete_project', { project: given });
|
|
268
|
+
out.result(result, () => `Deleted project #${result.project_number} ${result.name}.`);
|
|
269
|
+
}));
|
|
270
|
+
const uiTools = projects
|
|
271
|
+
.command('ui-tools')
|
|
272
|
+
.description("The agent's tools whose output the app shows as a component; their output is not checked as an answer.");
|
|
273
|
+
uiTools
|
|
274
|
+
.command('list [project]', { isDefault: true })
|
|
275
|
+
.description('The saved list, and the tools seen in recent traces.')
|
|
276
|
+
.action(run(async ({ client, out, project }, given) => {
|
|
277
|
+
const result = await client.action('get_ui_tools', {
|
|
278
|
+
project: given ?? project,
|
|
279
|
+
});
|
|
280
|
+
out.result(result, () => [
|
|
281
|
+
`Shown as UI: ${result.ui_tools.length ? result.ui_tools.join(', ') : 'none'}`,
|
|
282
|
+
result.discovered_tools.length
|
|
283
|
+
? table(result.discovered_tools, [
|
|
284
|
+
['name', 'Tool seen in traces', 40],
|
|
285
|
+
['calls', 'Calls'],
|
|
286
|
+
['suggested_ui', 'Looks like UI'],
|
|
287
|
+
['shown_as_ui', 'Shown as UI'],
|
|
288
|
+
])
|
|
289
|
+
: 'No tools seen in traces yet.',
|
|
290
|
+
].join('\n\n'));
|
|
291
|
+
}));
|
|
292
|
+
uiTools
|
|
293
|
+
.command('set <tools...>')
|
|
294
|
+
.description('Replace the list with these tool names.')
|
|
295
|
+
.action(run(async ({ client, out, project }, tools) => {
|
|
296
|
+
const result = await client.action('set_ui_tools', { project, tools });
|
|
297
|
+
out.result(result, () => `Shown as UI: ${result.ui_tools.join(', ') || 'none'}.`);
|
|
298
|
+
}));
|
|
299
|
+
uiTools
|
|
300
|
+
.command('clear')
|
|
301
|
+
.description('Empty the list: every tool output is checked as an answer.')
|
|
302
|
+
.action(run(async ({ client, out, project }) => {
|
|
303
|
+
const result = await client.action('set_ui_tools', { project, tools: [] });
|
|
304
|
+
out.result(result, () => 'No tool is shown as UI now.');
|
|
305
|
+
}));
|
|
306
|
+
program
|
|
307
|
+
.command('dashboard')
|
|
308
|
+
.description('The project dashboard for a period: verdicts, quality scores, tokens and cost, problem categories.')
|
|
309
|
+
.addOption(new Option('--period <period>', 'the period (default last_7_days; --from or --to make it custom)').choices([
|
|
310
|
+
'today',
|
|
311
|
+
'last_7_days',
|
|
312
|
+
'last_30_days',
|
|
313
|
+
'all_time',
|
|
314
|
+
'custom',
|
|
315
|
+
]))
|
|
316
|
+
.option('--from <date>', 'start of a custom period (YYYY-MM-DD or a time)')
|
|
317
|
+
.option('--to <date>', 'end of a custom period (YYYY-MM-DD, the whole day, or a time)')
|
|
318
|
+
.addOption(new Option('--source <source>', "tests for Test Lab runs, live for the agent's real traffic").choices(['tests', 'live']))
|
|
319
|
+
.option('--timezone <zone>', "the IANA time zone 'today' is counted in", 'UTC')
|
|
320
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
321
|
+
const result = await client.action('get_dashboard', {
|
|
322
|
+
project,
|
|
323
|
+
period: opts.period,
|
|
324
|
+
from: opts.from,
|
|
325
|
+
to: opts.to,
|
|
326
|
+
source: opts.source,
|
|
327
|
+
timezone: opts.timezone,
|
|
328
|
+
});
|
|
329
|
+
const scores = result.quality_scores.filter((item) => item.average !== null && item.average !== undefined);
|
|
330
|
+
out.result(result, () => [
|
|
331
|
+
fields([
|
|
332
|
+
['Project', `#${result.project_number} ${result.project}`],
|
|
333
|
+
['Period', `${result.period.label} (${result.source})`],
|
|
334
|
+
['Summary', result.summary.headline],
|
|
335
|
+
['Conversations', `${result.conversations.judged} judged, ${result.conversations.clean} clean, ${result.conversations.with_minor_problems} minor, ${result.conversations.with_major_problems} major`],
|
|
336
|
+
['Clean', result.conversations.clean_percent === null ? null : `${result.conversations.clean_percent}%`],
|
|
337
|
+
['Tests', `${result.tests.total} run, ${result.tests.clean} clean, ${result.tests.with_minor_problems} minor, ${result.tests.with_major_problems} major`],
|
|
338
|
+
['Turns', result.turns.total],
|
|
339
|
+
['Tokens per turn', result.turns.tokens_per_turn],
|
|
340
|
+
['Cost per turn (USD)', result.turns.cost_per_turn_usd],
|
|
341
|
+
['Cached input', result.turns.cached_input_tokens_percent === null ? null : `${result.turns.cached_input_tokens_percent}%`],
|
|
342
|
+
...scores.map((item) => [`Quality: ${item.label}`, item.average]),
|
|
343
|
+
['Link', result.url],
|
|
344
|
+
]),
|
|
345
|
+
...(result.summary.points ?? []).map((point) => `- ${point}`),
|
|
346
|
+
result.problem_categories.length
|
|
347
|
+
? `\n${table(result.problem_categories, [
|
|
348
|
+
['id', 'ID'],
|
|
349
|
+
['severity', 'Severity'],
|
|
350
|
+
['problems', 'Problems'],
|
|
351
|
+
['share_percent', '% conv.'],
|
|
352
|
+
['title', 'Problem category', 60],
|
|
353
|
+
])}`
|
|
354
|
+
: '',
|
|
355
|
+
]
|
|
356
|
+
.filter(Boolean)
|
|
357
|
+
.join('\n'));
|
|
358
|
+
}));
|
|
359
|
+
const knowledge = program
|
|
360
|
+
.command('knowledge')
|
|
361
|
+
.description('System knowledge: what QualiLoop knows of the agent, its coverage, and exploring it.');
|
|
362
|
+
const SUPER_ADMIN_KNOWLEDGE = {
|
|
363
|
+
show: 'get_knowledge_item',
|
|
364
|
+
edit: 'update_knowledge_item',
|
|
365
|
+
};
|
|
366
|
+
const knowledgeAdminShown = new Set();
|
|
367
|
+
knowledge.configureHelp({
|
|
368
|
+
visibleCommands(cmd) {
|
|
369
|
+
return Help.prototype.visibleCommands
|
|
370
|
+
.call(this, cmd)
|
|
371
|
+
.filter((sub) => !(sub.name() in SUPER_ADMIN_KNOWLEDGE) || knowledgeAdminShown.has(sub.name()));
|
|
372
|
+
},
|
|
373
|
+
});
|
|
374
|
+
knowledge
|
|
375
|
+
.command('summary', { isDefault: true })
|
|
376
|
+
.description('The agent at a glance: capabilities and test coverage.')
|
|
377
|
+
.action(run(async ({ client, out, project }) => {
|
|
378
|
+
const result = await client.action('get_knowledge', { project });
|
|
379
|
+
const sources = result.sources ?? [];
|
|
380
|
+
out.result(result, () => [
|
|
381
|
+
fields([
|
|
382
|
+
['Project', result.project],
|
|
383
|
+
['Coverage', result.coverage && result.coverage.percent != null ? `${result.coverage.percent}% (${result.coverage.covered}/${result.coverage.total})` : 'not measured yet'],
|
|
384
|
+
['Sources', sources.length ? sources.map((row) => row.name).join(', ') : 'none (qualiloop connect knowledge)'],
|
|
385
|
+
['Exploring now', result.exploring],
|
|
386
|
+
['Link', result.url],
|
|
387
|
+
]),
|
|
388
|
+
'',
|
|
389
|
+
table(result.capabilities, [
|
|
390
|
+
['name', 'Capability', 50],
|
|
391
|
+
['confirmed', 'Confirmed'],
|
|
392
|
+
]) || 'No capabilities known yet.',
|
|
393
|
+
].join('\n'));
|
|
394
|
+
}));
|
|
395
|
+
knowledge
|
|
396
|
+
.command('list')
|
|
397
|
+
.description('The items QualiLoop knows, by section, with their ids. Super admins see every section and status.')
|
|
398
|
+
.option('--section <section>', 'only one section: capability, entity_group, entity (super admins: also fact, component, state, action, transition)')
|
|
399
|
+
.addOption(limitOption('items', '100', 1000))
|
|
400
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
401
|
+
const result = await client.action('list_knowledge', {
|
|
402
|
+
project,
|
|
403
|
+
section: opts.section,
|
|
404
|
+
limit: limitOf(opts, 1000),
|
|
405
|
+
});
|
|
406
|
+
const columns = [
|
|
407
|
+
['id', 'ID'],
|
|
408
|
+
['section', 'Section'],
|
|
409
|
+
['name', 'Name', 45],
|
|
410
|
+
['confirmed', 'Confirmed'],
|
|
411
|
+
];
|
|
412
|
+
if (result.full)
|
|
413
|
+
columns.push(['intended', 'Intended'], ['observed', 'Observed'], ['reported', 'Reported'], ['projected', 'Projected']);
|
|
414
|
+
out.result(result, () => listed(table(result.items, columns), result.items.length, result.total, 'Nothing known yet.'));
|
|
415
|
+
}));
|
|
416
|
+
knowledge
|
|
417
|
+
.command('show <id>')
|
|
418
|
+
.description('One item in full: statuses, evidence and links (super admins).')
|
|
419
|
+
.action(run(async ({ client, out, project }, id) => {
|
|
420
|
+
const result = await client.action('get_knowledge_item', {
|
|
421
|
+
project,
|
|
422
|
+
item: intArg(id),
|
|
423
|
+
});
|
|
424
|
+
const node = result.node;
|
|
425
|
+
out.result(result, () => [
|
|
426
|
+
fields([
|
|
427
|
+
['Item', `${node.id} ${node.name}`],
|
|
428
|
+
['Section', node.kind ? `${node.section} (${node.kind})` : node.section],
|
|
429
|
+
['Description', node.description],
|
|
430
|
+
['Intended', node.intended],
|
|
431
|
+
['Observed', node.observed],
|
|
432
|
+
['Reported', node.reported],
|
|
433
|
+
['Projected', node.projected],
|
|
434
|
+
['Locked', node.locked],
|
|
435
|
+
]),
|
|
436
|
+
'',
|
|
437
|
+
table(result.evidence, [
|
|
438
|
+
['dimension', 'Status'],
|
|
439
|
+
['polarity', 'Says'],
|
|
440
|
+
['source', 'Source'],
|
|
441
|
+
['run_number', 'Run'],
|
|
442
|
+
['quote', 'Quote', 70],
|
|
443
|
+
]) || 'No evidence.',
|
|
444
|
+
].join('\n'));
|
|
445
|
+
}));
|
|
446
|
+
const markOption = (name) => new Option(`--${name} <mark>`, `manual ${name} evidence: yes, opposite, or clear to remove it`).choices(['yes', 'opposite', 'clear']);
|
|
447
|
+
knowledge
|
|
448
|
+
.command('edit <id>')
|
|
449
|
+
.description('Change an item by hand: its name, description, or a status as manual evidence (super admins).')
|
|
450
|
+
.option('--name <name>')
|
|
451
|
+
.option('--description <text>')
|
|
452
|
+
.option('--kind <kind>')
|
|
453
|
+
.addOption(new Option('--belongs-to <owner>').choices(['agent', 'system', 'world']))
|
|
454
|
+
.addOption(markOption('intended'))
|
|
455
|
+
.addOption(markOption('observed'))
|
|
456
|
+
.addOption(markOption('reported'))
|
|
457
|
+
.addOption(markOption('projected'))
|
|
458
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
459
|
+
const result = await client.action('update_knowledge_item', {
|
|
460
|
+
project,
|
|
461
|
+
item: intArg(id),
|
|
462
|
+
name: opts.name,
|
|
463
|
+
description: opts.description,
|
|
464
|
+
kind: opts.kind,
|
|
465
|
+
belongs_to: opts.belongsTo,
|
|
466
|
+
intended: opts.intended,
|
|
467
|
+
observed: opts.observed,
|
|
468
|
+
reported: opts.reported,
|
|
469
|
+
projected: opts.projected,
|
|
470
|
+
});
|
|
471
|
+
out.result(result, () => `Updated item ${id}: ${result.updated.join(', ')}.`);
|
|
472
|
+
}));
|
|
473
|
+
knowledge
|
|
474
|
+
.command('general')
|
|
475
|
+
.description("Change the agent's name, summary or description in System knowledge.")
|
|
476
|
+
.option('--name <name>')
|
|
477
|
+
.option('--summary <text>')
|
|
478
|
+
.option('--description <text>')
|
|
479
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
480
|
+
const result = await client.action('update_knowledge_general', {
|
|
481
|
+
project,
|
|
482
|
+
name: opts.name,
|
|
483
|
+
summary: opts.summary,
|
|
484
|
+
description: opts.description,
|
|
485
|
+
});
|
|
486
|
+
out.result(result, () => `Updated ${result.updated.join(', ')}.`);
|
|
487
|
+
}));
|
|
488
|
+
knowledge
|
|
489
|
+
.command('explore')
|
|
490
|
+
.description("Explore the agent: 3 rounds of up to 8 conversations, up to 24 conversation credits (the project's first exploration is free), not judged.")
|
|
491
|
+
.option('--note <text>', 'what to look at more closely')
|
|
492
|
+
.action(run(async (ctx) => {
|
|
493
|
+
const { client, out, project, opts } = ctx;
|
|
494
|
+
const result = await client.action('start_exploration', {
|
|
495
|
+
project,
|
|
496
|
+
note: opts.note,
|
|
497
|
+
});
|
|
498
|
+
const conversations = Number(result.exploration.rounds ?? 3) * Number(result.exploration.conversations_per_round ?? 8);
|
|
499
|
+
const cost = result.exploration.free
|
|
500
|
+
? `up to ${conversations} conversations, free as the project's first exploration`
|
|
501
|
+
: `up to ${result.most_credits} conversations, so up to ${result.most_credits} conversation credits`;
|
|
502
|
+
out.result(result, () => `Started exploration #${result.exploration.number ?? result.exploration.id}: ${cost}.\nFollow it: qualiloop knowledge explorations${projectFlag(ctx)}`);
|
|
503
|
+
}));
|
|
504
|
+
knowledge
|
|
505
|
+
.command('explorations')
|
|
506
|
+
.description("The project's latest explorations and where each stands.")
|
|
507
|
+
.action(run(async ({ client, out, project }) => {
|
|
508
|
+
const result = await client.action('list_explorations', { project });
|
|
509
|
+
out.result(result, () => table(result.explorations.map((row) => ({
|
|
510
|
+
...row,
|
|
511
|
+
number: row.number ?? row.id,
|
|
512
|
+
round: `${row.current_round ?? 0}/${row.rounds ?? '-'}`,
|
|
513
|
+
})), [
|
|
514
|
+
['number', 'Number'],
|
|
515
|
+
['trigger', 'Started by'],
|
|
516
|
+
['status', 'Status'],
|
|
517
|
+
['round', 'Round'],
|
|
518
|
+
['created_at', 'Created', 20],
|
|
519
|
+
['completed_at', 'Finished', 20],
|
|
520
|
+
]) || 'No explorations yet.');
|
|
521
|
+
}));
|
|
522
|
+
const ORIGIN_LABEL = {
|
|
523
|
+
code: 'coding agent',
|
|
524
|
+
manual: 'by hand',
|
|
525
|
+
connector: 'connection settings',
|
|
526
|
+
trace: 'seen in traces',
|
|
527
|
+
};
|
|
528
|
+
const KIND_LABEL = { system_prompt: 'System prompt', tools: 'Tools', documentation: 'Documentation' };
|
|
529
|
+
knowledge
|
|
530
|
+
.command('sources')
|
|
531
|
+
.description('What the knowledge is read from: the system prompts, tools and documentation, with their ids.')
|
|
532
|
+
.addOption(new Option('--kind <kind>', 'only one kind').choices(['system_prompt', 'tools', 'documentation']))
|
|
533
|
+
.option('--in-force', 'leave out retired sources')
|
|
534
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
535
|
+
const result = await client.action('list_sources', {
|
|
536
|
+
project,
|
|
537
|
+
kind: opts.kind,
|
|
538
|
+
include_retired: !opts.inForce,
|
|
539
|
+
});
|
|
540
|
+
out.result(result, () => table(result.sources.map((row) => ({
|
|
541
|
+
...row,
|
|
542
|
+
kind_label: KIND_LABEL[String(row.kind)] ?? row.kind,
|
|
543
|
+
from: ORIGIN_LABEL[String(row.origin)] ?? row.origin,
|
|
544
|
+
state: row.retired ? 'retired' : row.version ? `version ${row.version}` : 'not confirmed',
|
|
545
|
+
})), [
|
|
546
|
+
['id', 'ID'],
|
|
547
|
+
['kind_label', 'Kind'],
|
|
548
|
+
['name', 'Name', 45],
|
|
549
|
+
['from', 'From'],
|
|
550
|
+
['state', 'State'],
|
|
551
|
+
['last_seen_at', 'Last seen', 20],
|
|
552
|
+
]) || 'No sources yet. The coding agent setup sends them: qualiloop connect knowledge --file <json>');
|
|
553
|
+
}));
|
|
554
|
+
knowledge
|
|
555
|
+
.command('source <id>')
|
|
556
|
+
.description('One source: its current text, versions, and what it states.')
|
|
557
|
+
.option('--max-chars <n>', 'most characters of the text to show', '20000')
|
|
558
|
+
.option('--show-version <n>', "show this version's text instead of the current one")
|
|
559
|
+
.option('--diff <n>', 'show the changes from this version to the one shown')
|
|
560
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
561
|
+
const result = await client.action('get_source', {
|
|
562
|
+
project,
|
|
563
|
+
source: intArg(id),
|
|
564
|
+
max_chars: intArg(String(opts.maxChars)),
|
|
565
|
+
version: opts.showVersion === undefined ? undefined : intArg(String(opts.showVersion)),
|
|
566
|
+
compare_to: opts.diff === undefined ? undefined : intArg(String(opts.diff)),
|
|
567
|
+
});
|
|
568
|
+
const shown = result.shown_version !== undefined && result.shown_version !== result.version
|
|
569
|
+
? [`Showing version ${result.shown_version}.`, '']
|
|
570
|
+
: [];
|
|
571
|
+
const body = result.diff !== undefined
|
|
572
|
+
? [
|
|
573
|
+
String(result.diff) || `No changes from version ${result.compared_to}.`,
|
|
574
|
+
...(result.diff_cut ? ['\n(the diff is cut; more with --max-chars)'] : []),
|
|
575
|
+
]
|
|
576
|
+
: [
|
|
577
|
+
String(result.text ?? ''),
|
|
578
|
+
...(result.text_cut ? [`\n(${result.text_chars} characters; more with --max-chars)`] : []),
|
|
579
|
+
];
|
|
580
|
+
out.result(result, () => [
|
|
581
|
+
fields([
|
|
582
|
+
['Source', `${result.id} ${result.name}`],
|
|
583
|
+
['Kind', KIND_LABEL[String(result.kind)] ?? result.kind],
|
|
584
|
+
['From', ORIGIN_LABEL[String(result.origin)] ?? result.origin],
|
|
585
|
+
['State', result.retired ? 'retired' : result.version ? `version ${result.version}` : 'not confirmed'],
|
|
586
|
+
['Agent', result.component],
|
|
587
|
+
['Placeholders', result.placeholders],
|
|
588
|
+
['Seen at steps', result.trace_steps],
|
|
589
|
+
['Versions', result.versions.map((row) => row.number).join(', ')],
|
|
590
|
+
['Link', result.url],
|
|
591
|
+
]),
|
|
592
|
+
'',
|
|
593
|
+
...shown,
|
|
594
|
+
...body,
|
|
595
|
+
...(result.states.length
|
|
596
|
+
? ['', table(result.states, [['node_id', 'Item'], ['section', 'Section'], ['name', 'It states', 60]])]
|
|
597
|
+
: []),
|
|
598
|
+
].join('\n'));
|
|
599
|
+
}));
|
|
600
|
+
knowledge
|
|
601
|
+
.command('add-doc <name>')
|
|
602
|
+
.description('Add a document the agent answers from, or a system prompt with --kind system_prompt; the same name again ' +
|
|
603
|
+
'saves a new version (admins, ML team).')
|
|
604
|
+
.requiredOption('--file <path>', 'the text, from a file (or - for stdin)')
|
|
605
|
+
.addOption(new Option('--kind <kind>', 'documentation (default) or system_prompt').choices(['documentation', 'system_prompt']))
|
|
606
|
+
.action(run(async ({ client, out, project, opts }, name) => {
|
|
607
|
+
const text = readText(String(opts.file));
|
|
608
|
+
const result = await client.action('save_documentation', {
|
|
609
|
+
project,
|
|
610
|
+
name,
|
|
611
|
+
text,
|
|
612
|
+
kind: opts.kind,
|
|
613
|
+
});
|
|
614
|
+
out.result(result, () => `Saved ${result.source.name} as source ${result.source.id}, version ${result.source.version}.` +
|
|
615
|
+
(result.fill_queued || result.change_queued ? ' QualiLoop reads it into the system knowledge.' : ''));
|
|
616
|
+
}));
|
|
617
|
+
knowledge
|
|
618
|
+
.command('retire-source <id>')
|
|
619
|
+
.description('Take a source added by hand or seen in traces out of force (admins, ML team). Its versions are kept.')
|
|
620
|
+
.action(run(async (ctx, id) => {
|
|
621
|
+
const { client, out, project } = ctx;
|
|
622
|
+
const result = await client.action('retire_source', { project, source: intArg(id) });
|
|
623
|
+
out.result(result, () => `Retired ${result.source.name}. Bring it back with: ` +
|
|
624
|
+
`qualiloop knowledge restore-source ${result.source.id}${projectFlag(ctx)}`);
|
|
625
|
+
}));
|
|
626
|
+
knowledge
|
|
627
|
+
.command('restore-source <id>')
|
|
628
|
+
.description('Put a retired source back in force with the version it had (admins, ML team).')
|
|
629
|
+
.action(run(async ({ client, out, project }, id) => {
|
|
630
|
+
const result = await client.action('restore_source', { project, source: intArg(id) });
|
|
631
|
+
out.result(result, () => `Restored ${result.source.name}, version ${result.source.version}.`);
|
|
632
|
+
}));
|
|
633
|
+
knowledge
|
|
634
|
+
.command('link-source <id> [component]')
|
|
635
|
+
.description('Tie a system prompt to the agent or subagent it instructs: a component, by its id or exact name (admins, ML team).')
|
|
636
|
+
.option('--none', 'remove the link')
|
|
637
|
+
.action(run(async ({ client, out, project, opts }, id, component) => {
|
|
638
|
+
if (opts.none ? component !== undefined : component === undefined) {
|
|
639
|
+
throw new ApiError('Give a component, or --none to remove the link.', 400, EXIT.usage);
|
|
640
|
+
}
|
|
641
|
+
const result = await client.action('link_source_component', {
|
|
642
|
+
project,
|
|
643
|
+
source: intArg(id),
|
|
644
|
+
component: component === undefined ? null : /^\d+$/.test(component) ? Number(component) : component,
|
|
645
|
+
});
|
|
646
|
+
out.result(result, () => result.component
|
|
647
|
+
? `Linked ${result.source.name} to ${result.component}.`
|
|
648
|
+
: `${result.source.name} is linked to no component.`);
|
|
649
|
+
}));
|
|
650
|
+
const privateObjects = knowledge
|
|
651
|
+
.command('private')
|
|
652
|
+
.description('Private objects: values the simulated user holds, such as account numbers. Names and ids only; values are never shown.');
|
|
653
|
+
privateObjects
|
|
654
|
+
.command('list', { isDefault: true })
|
|
655
|
+
.description('List the categories and items, by name and id.')
|
|
656
|
+
.action(run(async ({ client, out, project }) => {
|
|
657
|
+
const result = await client.action('list_private_objects', {
|
|
658
|
+
project,
|
|
659
|
+
});
|
|
660
|
+
out.result(result, () => result.categories.length
|
|
661
|
+
? result.categories
|
|
662
|
+
.map((category) => [
|
|
663
|
+
`${category.name}${category.description ? `: ${category.description}` : ''}`,
|
|
664
|
+
table(category.items.map((item) => ({
|
|
665
|
+
...item,
|
|
666
|
+
fields: Array.isArray(item.fields) ? item.fields.join(', ') : '',
|
|
667
|
+
})), [
|
|
668
|
+
['id', 'ID', 36],
|
|
669
|
+
['description', 'Description', 50],
|
|
670
|
+
['fields', 'Fields', 40],
|
|
671
|
+
]) || ' No items.',
|
|
672
|
+
].join('\n'))
|
|
673
|
+
.join('\n\n')
|
|
674
|
+
: 'No private objects. Add them with: qualiloop knowledge private set --file <json>');
|
|
675
|
+
}));
|
|
676
|
+
privateObjects
|
|
677
|
+
.command('set')
|
|
678
|
+
.description('Add or change categories and items from a JSON file (admins, ML team): {"categories": [{"name", "rename_to"?, ' +
|
|
679
|
+
'"description"?, "items": [{"id"?, "description"?, "value"?}]}]}. An item without an id is added; one with an ' +
|
|
680
|
+
'id keeps its value unless a new one is given. What is not named is kept.')
|
|
681
|
+
.requiredOption('--file <path>', 'the JSON, from a file (or - for stdin)')
|
|
682
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
683
|
+
const file = String(opts.file);
|
|
684
|
+
let body;
|
|
685
|
+
try {
|
|
686
|
+
body = JSON.parse(readText(file));
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
if (error instanceof ApiError)
|
|
690
|
+
throw error;
|
|
691
|
+
throw new ApiError(`${file} is not JSON: ${error.message}`, 400, EXIT.usage);
|
|
692
|
+
}
|
|
693
|
+
const categories = Array.isArray(body) ? body : body?.categories;
|
|
694
|
+
if (!Array.isArray(categories)) {
|
|
695
|
+
throw new ApiError(`${file} needs a "categories" list.`, 400, EXIT.usage);
|
|
696
|
+
}
|
|
697
|
+
const result = await client.action('set_private_objects', { project, categories });
|
|
698
|
+
out.result(result, () => {
|
|
699
|
+
const added = result.categories_added ?? [];
|
|
700
|
+
const changed = result.categories_changed ?? [];
|
|
701
|
+
return [
|
|
702
|
+
`Saved private objects: ${result.items_added} items added, ${result.items_changed} changed.`,
|
|
703
|
+
...(added.length ? [`New categories: ${added.join(', ')}`] : []),
|
|
704
|
+
...(changed.length ? [`Changed categories: ${changed.join(', ')}`] : []),
|
|
705
|
+
].join('\n');
|
|
706
|
+
});
|
|
707
|
+
}));
|
|
708
|
+
privateObjects
|
|
709
|
+
.command('delete <category>')
|
|
710
|
+
.description('Delete a category with its items, or only the items given with --item (admins, ML team).')
|
|
711
|
+
.option('--item <id...>', 'only these items, by id')
|
|
712
|
+
.option('--yes', 'delete without asking')
|
|
713
|
+
.action(run(async ({ client, out, project, opts }, category) => {
|
|
714
|
+
const items = opts.item;
|
|
715
|
+
if (!opts.yes) {
|
|
716
|
+
const what = items?.length ? `${items.length} items from private object category ${category}` : `private object category ${category} with its items`;
|
|
717
|
+
if (!(await confirm(`Delete ${what}?`))) {
|
|
718
|
+
out.result({ deleted: false, category }, () => 'Not deleted.');
|
|
719
|
+
return EXIT.ok;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
const result = await client.action('delete_private_objects', { project, category, items });
|
|
723
|
+
out.result(result, () => result.category_deleted
|
|
724
|
+
? `Deleted ${result.category} and its ${result.items_deleted} items.`
|
|
725
|
+
: `Deleted ${result.items_deleted} items from ${result.category}.`);
|
|
726
|
+
}));
|
|
727
|
+
program
|
|
728
|
+
.command('change <description...>')
|
|
729
|
+
.description('Tell QualiLoop the agent changed, so it re-checks what the change touches.')
|
|
730
|
+
.option('--no-explore', 'record the change without exploring again')
|
|
731
|
+
.action(run(async ({ client, out, project, opts }, words) => {
|
|
732
|
+
const result = await client.action('report_change', {
|
|
733
|
+
project,
|
|
734
|
+
description: words.join(' '),
|
|
735
|
+
explore: opts.explore !== false,
|
|
736
|
+
});
|
|
737
|
+
out.result(result, () => `Change recorded in ${result.project}.${result.exploring ? ' QualiLoop explores what it touches again.' : ''}`);
|
|
738
|
+
}));
|
|
739
|
+
const testColumns = [
|
|
740
|
+
['id', 'ID'],
|
|
741
|
+
['name', 'Name', 45],
|
|
742
|
+
['mode', 'Mode'],
|
|
743
|
+
['category', 'Category', 25],
|
|
744
|
+
['last', 'Last run'],
|
|
745
|
+
['suites', 'Suites'],
|
|
746
|
+
];
|
|
747
|
+
const lastRun = (row) => {
|
|
748
|
+
const last = row.last_run;
|
|
749
|
+
return last ? `#${last.run_number} ${last.outcome}` : '-';
|
|
750
|
+
};
|
|
751
|
+
const tests = program.command('tests').description('Saved tests.');
|
|
752
|
+
tests
|
|
753
|
+
.command('list', { isDefault: true })
|
|
754
|
+
.description('List the saved tests of the project.')
|
|
755
|
+
.option('--suite <suite>', 'only the tests of this suite (id or name)')
|
|
756
|
+
.option('--search <text>', 'only tests whose name contains this')
|
|
757
|
+
.addOption(new Option('--mode <mode>', 'only tests of this mode').choices(['regular', 'red_team', 'bias']))
|
|
758
|
+
.option('--category <category>', 'only the regular tests of this category (id or name)')
|
|
759
|
+
.option('--new', 'only tests a generation wrote that nobody has opened yet')
|
|
760
|
+
.addOption(new Option('--sort <order>', 'latest change, name, latest run or most runs first')
|
|
761
|
+
.choices(['updated', 'name', 'last_run', 'runs']))
|
|
762
|
+
.addOption(limitOption('tests', '100', 1000))
|
|
763
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
764
|
+
const result = await client.action('list_tests', {
|
|
765
|
+
project,
|
|
766
|
+
suite: opts.suite,
|
|
767
|
+
search: opts.search,
|
|
768
|
+
mode: opts.mode,
|
|
769
|
+
category: typeof opts.category === 'string' ? idOrName(opts.category) : undefined,
|
|
770
|
+
new_only: opts.new ? true : undefined,
|
|
771
|
+
sort: opts.sort,
|
|
772
|
+
limit: limitOf(opts, 1000),
|
|
773
|
+
});
|
|
774
|
+
out.result(result, () => listed(table(result.tests.map((row) => ({
|
|
775
|
+
...row,
|
|
776
|
+
last: lastRun(row),
|
|
777
|
+
category: row.category?.name ?? '',
|
|
778
|
+
name: row.new ? `${row.name} (new)` : row.name,
|
|
779
|
+
})), testColumns), result.tests.length, result.total, 'No tests.'));
|
|
780
|
+
}));
|
|
781
|
+
tests
|
|
782
|
+
.command('show <id>')
|
|
783
|
+
.description('One saved test in full.')
|
|
784
|
+
.action(run(async ({ client, out, project }, id) => {
|
|
785
|
+
const result = await client.action('get_test', { project, test: intArg(id) });
|
|
786
|
+
out.result(result, () => fields([
|
|
787
|
+
['Test', `${result.id} ${result.name}`],
|
|
788
|
+
['Mode', `${result.mode} (${result.run_type})`],
|
|
789
|
+
...(result.attack_type ? [['Attack', result.attack_type]] : []),
|
|
790
|
+
...(result.bias
|
|
791
|
+
? [['Bias', `${result.bias.bias_type}: ${result.bias.group_a} vs ${result.bias.group_b}`]]
|
|
792
|
+
: []),
|
|
793
|
+
...(result.category ? [['Category', result.category.name]] : []),
|
|
794
|
+
['Instructions', result.instructions],
|
|
795
|
+
['Persona', result.persona],
|
|
796
|
+
['Steps', result.steps],
|
|
797
|
+
...(result.send_steps_literally ? [['Steps sent', 'exactly as written']] : []),
|
|
798
|
+
['Turns', result.max_turns],
|
|
799
|
+
['Conversations', result.conversations],
|
|
800
|
+
...(Object.keys(result.variables ?? {}).length
|
|
801
|
+
? [
|
|
802
|
+
[
|
|
803
|
+
'Variables',
|
|
804
|
+
`${Object.entries(result.variables)
|
|
805
|
+
.map(([name, values]) => `${name}=${values.join(',')}`)
|
|
806
|
+
.join('; ')} (${result.variable_mode})`,
|
|
807
|
+
],
|
|
808
|
+
]
|
|
809
|
+
: []),
|
|
810
|
+
...(result.channel === 'voice'
|
|
811
|
+
? [['Channel', `voice${result.voice_id ? ` (${result.voice_id})` : ''}`]]
|
|
812
|
+
: []),
|
|
813
|
+
['Suites', result.suites],
|
|
814
|
+
['Last run', lastRun(result)],
|
|
815
|
+
]));
|
|
816
|
+
}));
|
|
817
|
+
const repeat = (value, all = []) => [...all, value];
|
|
818
|
+
const idOrName = (value) => (/^\d+$/.test(value) ? Number(value) : value);
|
|
819
|
+
const variablesOf = (given) => {
|
|
820
|
+
if (!given)
|
|
821
|
+
return undefined;
|
|
822
|
+
const out = {};
|
|
823
|
+
for (const item of given) {
|
|
824
|
+
const at = item.indexOf('=');
|
|
825
|
+
if (at < 1)
|
|
826
|
+
throw new ApiError(`--var takes name=value1,value2, not ${item}.`, 400, EXIT.usage);
|
|
827
|
+
out[item.slice(0, at).trim()] = item
|
|
828
|
+
.slice(at + 1)
|
|
829
|
+
.split(',')
|
|
830
|
+
.map((value) => value.trim())
|
|
831
|
+
.filter(Boolean);
|
|
832
|
+
}
|
|
833
|
+
return out;
|
|
834
|
+
};
|
|
835
|
+
const testFieldOptions = (command) => command
|
|
836
|
+
.option('--instructions <text>', 'what the simulated user wants and how they behave')
|
|
837
|
+
.option('--persona <text>', 'who the simulated user is')
|
|
838
|
+
.option('--step <text>', 'a scripted step, in order (repeat)', repeat)
|
|
839
|
+
.option('--turns <n>', 'most turns of one conversation')
|
|
840
|
+
.option('--conversations <n>', 'conversations per run (matched pairs for a bias test)')
|
|
841
|
+
.option('--language <language>', 'the language the simulated user speaks')
|
|
842
|
+
.option('--bias <type>', 'make it a bias test of this type (gender, age, location, ...); give --group-a and --group-b')
|
|
843
|
+
.option('--group-a <group>', 'bias test: the first group compared')
|
|
844
|
+
.option('--group-b <group>', 'bias test: the second group compared')
|
|
845
|
+
.option('--category <category>', 'regular test: its category (id or name)')
|
|
846
|
+
.option('--var <name=values>', 'a variable for {{name}} placeholders, values split by commas (repeat)', repeat)
|
|
847
|
+
.addOption(new Option('--variable-order <order>', 'how a conversation picks a value').choices(['random', 'sequential']))
|
|
848
|
+
.option('--literal', 'send each step exactly as written')
|
|
849
|
+
.option('--no-literal', 'let the simulated user phrase the steps')
|
|
850
|
+
.addOption(new Option('--channel <channel>', 'how the simulated user reaches the agent (voice needs ElevenLabs)').choices(['text', 'voice']))
|
|
851
|
+
.option('--voice-id <id>', 'the ElevenLabs voice the simulated user speaks with');
|
|
852
|
+
const testFields = (opts) => ({
|
|
853
|
+
instructions: opts.instructions,
|
|
854
|
+
persona: opts.persona,
|
|
855
|
+
max_turns: opts.turns ? intArg(String(opts.turns)) : undefined,
|
|
856
|
+
conversations: opts.conversations ? intArg(String(opts.conversations)) : undefined,
|
|
857
|
+
language: opts.language,
|
|
858
|
+
bias_type: opts.bias,
|
|
859
|
+
group_a: opts.groupA,
|
|
860
|
+
group_b: opts.groupB,
|
|
861
|
+
category: typeof opts.category === 'string' ? idOrName(opts.category) : undefined,
|
|
862
|
+
variables: opts.clearVariables ? {} : variablesOf(opts.var),
|
|
863
|
+
variable_mode: opts.variableOrder,
|
|
864
|
+
send_steps_literally: opts.literal,
|
|
865
|
+
channel: opts.channel,
|
|
866
|
+
voice_id: opts.voiceId,
|
|
867
|
+
});
|
|
868
|
+
testFieldOptions(tests
|
|
869
|
+
.command('create')
|
|
870
|
+
.description('Write a new saved test.')
|
|
871
|
+
.requiredOption('--name <name>', 'a short name for the test'))
|
|
872
|
+
.option('--red-team <attack>', 'make it an attack of this type (prompt_injection, jailbreak, data_leak, ...)')
|
|
873
|
+
.option('--single', 'one message per prompt instead of a conversation')
|
|
874
|
+
.option('--suite <suite>', 'add it to this suite (repeat)', repeat)
|
|
875
|
+
.action(run(async (ctx) => {
|
|
876
|
+
const { client, out, project, opts } = ctx;
|
|
877
|
+
if (!opts.instructions)
|
|
878
|
+
throw new ApiError('Give --instructions.', 400, EXIT.usage);
|
|
879
|
+
const result = await client.action('create_test', {
|
|
880
|
+
project,
|
|
881
|
+
name: opts.name,
|
|
882
|
+
...testFields(opts),
|
|
883
|
+
steps: opts.step,
|
|
884
|
+
mode: opts.redTeam ? 'red_team' : opts.bias ? 'bias' : 'regular',
|
|
885
|
+
attack_type: opts.redTeam,
|
|
886
|
+
shape: opts.single ? 'single' : 'conversation',
|
|
887
|
+
suites: opts.suite,
|
|
888
|
+
});
|
|
889
|
+
out.result(result, () => `Saved test ${result.id} ${result.name}. Run it: qualiloop run ${result.id}${projectFlag(ctx)}`);
|
|
890
|
+
}));
|
|
891
|
+
tests
|
|
892
|
+
.command('delete <id>')
|
|
893
|
+
.description('Delete a saved test and take it out of its suites. Its past runs stay.')
|
|
894
|
+
.option('--yes', 'delete without asking')
|
|
895
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
896
|
+
const test = intArg(id);
|
|
897
|
+
if (!opts.yes) {
|
|
898
|
+
const found = await client.action('get_test', { project, test });
|
|
899
|
+
if (!(await confirm(`Delete test ${found.id} ${found.name}?`))) {
|
|
900
|
+
out.result({ deleted: false, id: test }, () => 'Not deleted.');
|
|
901
|
+
return EXIT.ok;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
const result = await client.action('delete_test', { project, test });
|
|
905
|
+
out.result(result, () => `Deleted test ${result.id} ${result.name}.`);
|
|
906
|
+
}));
|
|
907
|
+
tests
|
|
908
|
+
.command('seen [test-ids...]')
|
|
909
|
+
.description('Take the New mark off generated tests.')
|
|
910
|
+
.option('--all', 'every new test of the project')
|
|
911
|
+
.action(run(async ({ client, out, project, opts }, ids = []) => {
|
|
912
|
+
if (Boolean(opts.all) === ids.length > 0)
|
|
913
|
+
throw new ApiError('Give test ids or --all.', 400, EXIT.usage);
|
|
914
|
+
const result = await client.action('mark_tests_seen', {
|
|
915
|
+
project,
|
|
916
|
+
tests: ids.length ? ids.map(intArg) : undefined,
|
|
917
|
+
all: opts.all ? true : undefined,
|
|
918
|
+
});
|
|
919
|
+
out.result(result, () => result.tests.length ? `Marked ${result.tests.length} test(s) seen: ${result.tests.join(', ')}.` : 'No new test to mark.');
|
|
920
|
+
}));
|
|
921
|
+
testFieldOptions(tests.command('edit <id>').description('Change a saved test; only what you give changes.').option('--name <name>', 'a new name'))
|
|
922
|
+
.option('--no-steps', 'remove the scripted steps')
|
|
923
|
+
.option('--regular', 'make it a regular test')
|
|
924
|
+
.option('--red-team <attack>', 'make it an attack of this type, or change its attack type')
|
|
925
|
+
.addOption(new Option('--shape <shape>', 'a conversation, or one message per prompt').choices(['conversation', 'single']))
|
|
926
|
+
.option('--clear-variables', 'remove every variable')
|
|
927
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
928
|
+
const result = await client.action('update_test', {
|
|
929
|
+
project,
|
|
930
|
+
test: intArg(id),
|
|
931
|
+
name: opts.name,
|
|
932
|
+
...testFields(opts),
|
|
933
|
+
steps: opts.steps === false ? [] : opts.step,
|
|
934
|
+
mode: opts.redTeam ? 'red_team' : opts.bias ? 'bias' : opts.regular ? 'regular' : undefined,
|
|
935
|
+
attack_type: opts.redTeam,
|
|
936
|
+
shape: opts.shape,
|
|
937
|
+
});
|
|
938
|
+
out.result(result, () => `Updated test ${result.id}: ${result.updated.join(', ')}.`);
|
|
939
|
+
}));
|
|
940
|
+
tests
|
|
941
|
+
.command('copy <id>')
|
|
942
|
+
.description('Save a copy of a saved test with every field, in the same suites.')
|
|
943
|
+
.option('--name <name>', 'the copy\'s name (default: the name with (copy) after it)')
|
|
944
|
+
.option('--suite <suite>', 'put the copy in this suite instead of the test\'s own (repeat)', repeat)
|
|
945
|
+
.action(run(async (ctx, id) => {
|
|
946
|
+
const { client, out, project, opts } = ctx;
|
|
947
|
+
const result = await client.action('copy_test', {
|
|
948
|
+
project,
|
|
949
|
+
test: intArg(id),
|
|
950
|
+
name: opts.name,
|
|
951
|
+
suites: opts.suite,
|
|
952
|
+
});
|
|
953
|
+
out.result(result, () => `Saved test ${result.id} ${result.name}, a copy of test ${id}. Change it: qualiloop tests edit ${result.id}${projectFlag(ctx)}`);
|
|
954
|
+
}));
|
|
955
|
+
tests
|
|
956
|
+
.command('draft <description...>')
|
|
957
|
+
.description('Fill in a test from a description, or a change to one with --test. Saves nothing.')
|
|
958
|
+
.option('--test <id>', 'draft a change to this saved test')
|
|
959
|
+
.addOption(new Option('--mode <mode>', 'keep the draft in this mode').choices(['regular', 'red_team', 'bias']))
|
|
960
|
+
.action(run(async ({ client, out, project, opts }, words) => {
|
|
961
|
+
const result = await client.action('draft_test', {
|
|
962
|
+
project,
|
|
963
|
+
instruction: words.join(' '),
|
|
964
|
+
test: opts.test ? intArg(String(opts.test)) : undefined,
|
|
965
|
+
mode: opts.mode,
|
|
966
|
+
});
|
|
967
|
+
const shown = result.changed ?? result.fields;
|
|
968
|
+
out.result(result, () => [
|
|
969
|
+
Object.keys(shown).length
|
|
970
|
+
? fields(Object.entries(shown).map(([key, value]) => [key, value]))
|
|
971
|
+
: 'Nothing to change.',
|
|
972
|
+
'',
|
|
973
|
+
result.changed
|
|
974
|
+
? `Not saved. Save the changes with qualiloop tests edit ${opts.test} and these fields.`
|
|
975
|
+
: 'Not saved. Save it with qualiloop tests create and these fields, or run this with --json.',
|
|
976
|
+
].join('\n'));
|
|
977
|
+
}));
|
|
978
|
+
const launched = async (ctx, result) => {
|
|
979
|
+
const { out, project, opts } = ctx;
|
|
980
|
+
for (const item of result.failed) {
|
|
981
|
+
const what = item.test_id !== undefined ? `Test ${item.test_id}` : `Run #${item.run_number}`;
|
|
982
|
+
out.progress(`${what} did not start: ${item.reason}`);
|
|
983
|
+
}
|
|
984
|
+
if (!result.batch_id || !result.started.length) {
|
|
985
|
+
out.result(result, () => 'Nothing started.');
|
|
986
|
+
return EXIT.failed;
|
|
987
|
+
}
|
|
988
|
+
const started = `Started ${result.started.length} run(s): ${result.started.map((item) => `#${item.run_number}`).join(', ')}`;
|
|
989
|
+
const resume = `qualiloop runs wait ${result.batch_id}${projectFlag(ctx)}`;
|
|
990
|
+
if (!opts.wait) {
|
|
991
|
+
out.result(result, () => [started, `Batch ${result.batch_id}. Wait for it: ${resume}`, `Or open ${result.url}`].join('\n'));
|
|
992
|
+
return EXIT.ok;
|
|
993
|
+
}
|
|
994
|
+
out.progress(`${started}\nBatch ${result.batch_id}. If you stop waiting, resume with: ${resume}`);
|
|
995
|
+
return follow(ctx, project ?? String(result.project_number), result.batch_id, result);
|
|
996
|
+
};
|
|
997
|
+
const follow = async (ctx, project, batch, launch = {}) => {
|
|
998
|
+
const { client, out, opts } = ctx;
|
|
999
|
+
out.progress('Waiting until every run has talked to the agent, been judged and had its problems sorted...');
|
|
1000
|
+
const runs = await waitForBatch(client, project, batch, {
|
|
1001
|
+
timeoutMinutes: intArg(String(opts.timeout)),
|
|
1002
|
+
onProgress: (message) => out.progress(message),
|
|
1003
|
+
});
|
|
1004
|
+
const code = runsExitCode(runs, opts.failOn);
|
|
1005
|
+
const failing = runs.filter((item) => runsExitCode([item], opts.failOn) !== EXIT.ok);
|
|
1006
|
+
let comparison = null;
|
|
1007
|
+
try {
|
|
1008
|
+
comparison = await compareBatch(client, project, batch);
|
|
1009
|
+
}
|
|
1010
|
+
catch (error) {
|
|
1011
|
+
out.progress(`Could not compare with the previous runs: ${error.message}`);
|
|
1012
|
+
}
|
|
1013
|
+
out.result({ ...launch, batch_id: batch, runs, passed: code === EXIT.ok, comparison }, () => [
|
|
1014
|
+
table(runs, [
|
|
1015
|
+
['run_number', 'Run'],
|
|
1016
|
+
['name', 'Test', 40],
|
|
1017
|
+
['outcome', 'Outcome'],
|
|
1018
|
+
['major_problems', 'Major'],
|
|
1019
|
+
['minor_problems', 'Minor'],
|
|
1020
|
+
]),
|
|
1021
|
+
...(comparison ? ['', comparisonText(comparison, projectFlag(ctx))] : []),
|
|
1022
|
+
'',
|
|
1023
|
+
code === EXIT.ok
|
|
1024
|
+
? 'Passed.'
|
|
1025
|
+
: ['Failed. Read why:', ...failing.map((item) => ` qualiloop problems --run ${item.run_number}${projectFlag(ctx)}`)].join('\n'),
|
|
1026
|
+
].join('\n'));
|
|
1027
|
+
return code;
|
|
1028
|
+
};
|
|
1029
|
+
const waitOptions = (command, waitFlag = true) => {
|
|
1030
|
+
if (waitFlag)
|
|
1031
|
+
command.option('--wait', 'wait for the results and exit 1 if a run fails');
|
|
1032
|
+
else
|
|
1033
|
+
command.addOption(new Option('--wait').hideHelp());
|
|
1034
|
+
return command.addOption(failOnOption()).option('--timeout <minutes>', 'most minutes to wait', '60');
|
|
1035
|
+
};
|
|
1036
|
+
waitOptions(program
|
|
1037
|
+
.command('run [test-ids...]')
|
|
1038
|
+
.description('Run saved tests now, as one batch. With --category and no ids, every test of the category.')
|
|
1039
|
+
.option('--label <label>', 'what Test Results calls this launch')
|
|
1040
|
+
.option('--category <category>', 'a test category (id or name): the launch is a category run named after it')).action(run(async (ctx, ids = []) => {
|
|
1041
|
+
const category = ctx.opts.category;
|
|
1042
|
+
if (!ids.length && !category)
|
|
1043
|
+
throw new ApiError('Give the test ids to run, or --category.', 400, EXIT.usage);
|
|
1044
|
+
const result = await ctx.client.action('run_tests', {
|
|
1045
|
+
project: ctx.project,
|
|
1046
|
+
tests: ids.map(intArg),
|
|
1047
|
+
label: ctx.opts.label,
|
|
1048
|
+
category: category === undefined ? undefined : suiteRef(category),
|
|
1049
|
+
});
|
|
1050
|
+
return launched(ctx, result);
|
|
1051
|
+
}));
|
|
1052
|
+
const suites = program.command('suites').description('Suites of saved tests.');
|
|
1053
|
+
suites
|
|
1054
|
+
.command('list', { isDefault: true })
|
|
1055
|
+
.description('List the suites of the project.')
|
|
1056
|
+
.addOption(limitOption('suites', '50', 1000))
|
|
1057
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1058
|
+
const result = await client.action('list_suites', { project });
|
|
1059
|
+
const shown = result.suites.slice(0, limitOf(opts, 1000));
|
|
1060
|
+
out.result({ ...result, total: result.suites.length, suites: shown }, () => listed(table(shown.map((row) => {
|
|
1061
|
+
const last = row.last_run;
|
|
1062
|
+
return { ...row, last: last ? `${last.status}, ${last.no_major_percent ?? '-'}% without major` : '-' };
|
|
1063
|
+
}), [
|
|
1064
|
+
['id', 'ID'],
|
|
1065
|
+
['name', 'Name', 40],
|
|
1066
|
+
['tests', 'Tests'],
|
|
1067
|
+
['core', 'Core'],
|
|
1068
|
+
['last', 'Last run', 40],
|
|
1069
|
+
]), shown.length, result.suites.length, 'No suites.'));
|
|
1070
|
+
}));
|
|
1071
|
+
const suiteRef = (suite) => (/^\d+$/.test(suite) ? Number(suite) : suite);
|
|
1072
|
+
suites
|
|
1073
|
+
.command('create <name>')
|
|
1074
|
+
.description('Make a new suite, optionally with tests in it.')
|
|
1075
|
+
.option('--description <text>', 'what the suite is for')
|
|
1076
|
+
.option('--test <id>', 'a saved test to put in it (repeat)', (value, all = []) => [...all, value])
|
|
1077
|
+
.action(run(async (ctx, name) => {
|
|
1078
|
+
const { client, out, project, opts } = ctx;
|
|
1079
|
+
const result = await client.action('create_suite', {
|
|
1080
|
+
project,
|
|
1081
|
+
name,
|
|
1082
|
+
description: opts.description,
|
|
1083
|
+
tests: (opts.test ?? []).map(intArg),
|
|
1084
|
+
});
|
|
1085
|
+
out.result(result, () => `Created suite ${result.suite.id} ${result.suite.name} with ${result.suite.tests} test(s). Run it: qualiloop suites run ${result.suite.id}${projectFlag(ctx)}`);
|
|
1086
|
+
}));
|
|
1087
|
+
suites
|
|
1088
|
+
.command('add <suite> <test-ids...>')
|
|
1089
|
+
.description('Put saved tests in a suite (id, name, or core). A test can be in several suites.')
|
|
1090
|
+
.action(run(async ({ client, out, project }, suite, ids) => {
|
|
1091
|
+
const result = await client.action('change_suite_tests', {
|
|
1092
|
+
project,
|
|
1093
|
+
suite: suiteRef(suite),
|
|
1094
|
+
add: ids.map(intArg),
|
|
1095
|
+
});
|
|
1096
|
+
out.result(result, () => `Added ${result.added} test(s) to suite ${result.suite.id} ${result.suite.name}` +
|
|
1097
|
+
(Number(result.added) < ids.length ? '; the others were in it already.' : '.'));
|
|
1098
|
+
}));
|
|
1099
|
+
suites
|
|
1100
|
+
.command('edit <suite>')
|
|
1101
|
+
.description('Rename a suite (id, name, or core) or change its description.')
|
|
1102
|
+
.option('--name <name>', 'a new name')
|
|
1103
|
+
.option('--description <text>', 'what the suite is for; empty removes it')
|
|
1104
|
+
.action(run(async ({ client, out, project, opts }, suite) => {
|
|
1105
|
+
const result = await client.action('update_suite', {
|
|
1106
|
+
project,
|
|
1107
|
+
suite: suiteRef(suite),
|
|
1108
|
+
name: opts.name,
|
|
1109
|
+
description: opts.description,
|
|
1110
|
+
});
|
|
1111
|
+
out.result(result, () => `Suite ${result.suite.id} is now ${result.suite.name}.`);
|
|
1112
|
+
}));
|
|
1113
|
+
waitOptions(suites.command('run <suite>').description('Run every test of a suite (id, name, or core).')).action(run(async (ctx, suite) => {
|
|
1114
|
+
const result = await ctx.client.action('run_suite', { project: ctx.project, suite: suiteRef(suite) });
|
|
1115
|
+
return launched(ctx, result);
|
|
1116
|
+
}));
|
|
1117
|
+
suites
|
|
1118
|
+
.command('delete <suite>')
|
|
1119
|
+
.description('Delete a suite (id or name). Its tests stay unless --with-tests; past runs stay.')
|
|
1120
|
+
.option('--with-tests', 'also delete its tests, from the library and every other suite')
|
|
1121
|
+
.option('--yes', 'delete without asking')
|
|
1122
|
+
.action(run(async ({ client, out, project, opts }, suite) => {
|
|
1123
|
+
const withTests = Boolean(opts.withTests);
|
|
1124
|
+
if (!opts.yes) {
|
|
1125
|
+
const found = (await client.action('list_suites', { project })).suites.find((row) => String(row.id) === suite || String(row.name).toLowerCase() === suite.toLowerCase());
|
|
1126
|
+
const what = found ? `suite ${found.id} ${found.name}` : `suite ${suite}`;
|
|
1127
|
+
const tests = withTests ? (found ? ` and its ${found.tests} test(s)` : ' and its tests') : '';
|
|
1128
|
+
if (!(await confirm(`Delete ${what}${tests}?`))) {
|
|
1129
|
+
out.result({ deleted: false, suite }, () => 'Not deleted.');
|
|
1130
|
+
return EXIT.ok;
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
const result = await client.action('delete_suite', {
|
|
1134
|
+
project,
|
|
1135
|
+
suite: suiteRef(suite),
|
|
1136
|
+
delete_tests: withTests,
|
|
1137
|
+
});
|
|
1138
|
+
out.result(result, () => `Deleted suite ${result.id} ${result.name}` + (result.tests_deleted ? ` and its ${result.tests} test(s).` : '.'));
|
|
1139
|
+
}));
|
|
1140
|
+
const runs = program.command('runs').description('Test runs and their results.');
|
|
1141
|
+
const offsetOption = () => new Option('--offset <n>', 'skip this many, for the next page').default('0');
|
|
1142
|
+
const offsetOf = (opts) => {
|
|
1143
|
+
const offset = intArg(String(opts.offset ?? '0'));
|
|
1144
|
+
if (offset < 0)
|
|
1145
|
+
throw new ApiError('--offset takes 0 or more.', 400, EXIT.usage);
|
|
1146
|
+
return offset;
|
|
1147
|
+
};
|
|
1148
|
+
const testModeOption = () => new Option('--mode <mode>', 'only tests of this mode').choices(['regular', 'red_team', 'bias']);
|
|
1149
|
+
const fromOption = () => new Option('--from <date>', 'only what started on or after this date (YYYY-MM-DD) or time');
|
|
1150
|
+
const toOption = () => new Option('--to <date>', 'only what started on or before this date (the whole day) or time');
|
|
1151
|
+
const paged = (rendered, shown, total, offset, empty) => {
|
|
1152
|
+
if (!rendered)
|
|
1153
|
+
return empty;
|
|
1154
|
+
if (offset + shown >= total)
|
|
1155
|
+
return rendered;
|
|
1156
|
+
return `${rendered}\n\n${offset + 1} to ${offset + shown} of ${total} shown. Next page: --offset ${offset + shown}.`;
|
|
1157
|
+
};
|
|
1158
|
+
runs
|
|
1159
|
+
.command('list', { isDefault: true })
|
|
1160
|
+
.description('Recent runs, newest first, filtered as Test Results filters them.')
|
|
1161
|
+
.option('--batch <id>', 'only the runs of one launch')
|
|
1162
|
+
.option('--status <status>', 'only runs in this status')
|
|
1163
|
+
.addOption(testModeOption())
|
|
1164
|
+
.addOption(new Option('--result <result>', 'only finished runs with this result').choices(['clean', 'minor', 'major', 'not_reviewed']))
|
|
1165
|
+
.addOption(fromOption())
|
|
1166
|
+
.addOption(toOption())
|
|
1167
|
+
.addOption(new Option('--started <how>', 'started by a schedule or by hand').choices(['scheduled', 'manual']))
|
|
1168
|
+
.option('--category <category>', 'only runs with a problem in this problem category (id or title)')
|
|
1169
|
+
.option('--test <id>', 'only runs of this saved test')
|
|
1170
|
+
.option('--schedule <id>', 'only runs this schedule started')
|
|
1171
|
+
.option('--search <text>', 'only runs whose test name contains this')
|
|
1172
|
+
.addOption(limitOption('runs', '20', 500))
|
|
1173
|
+
.addOption(offsetOption())
|
|
1174
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1175
|
+
const offset = offsetOf(opts);
|
|
1176
|
+
const result = await client.action('list_runs', {
|
|
1177
|
+
project,
|
|
1178
|
+
batch: opts.batch,
|
|
1179
|
+
status: opts.status,
|
|
1180
|
+
mode: opts.mode,
|
|
1181
|
+
result: opts.result,
|
|
1182
|
+
from: opts.from,
|
|
1183
|
+
to: opts.to,
|
|
1184
|
+
started: opts.started,
|
|
1185
|
+
category: opts.category ? suiteRef(String(opts.category)) : undefined,
|
|
1186
|
+
test: opts.test ? intArg(String(opts.test)) : undefined,
|
|
1187
|
+
schedule: opts.schedule ? intArg(String(opts.schedule)) : undefined,
|
|
1188
|
+
search: opts.search,
|
|
1189
|
+
limit: limitOf(opts, 500),
|
|
1190
|
+
offset,
|
|
1191
|
+
});
|
|
1192
|
+
out.result(result, () => paged(table(result.runs, [
|
|
1193
|
+
['run_number', 'Run'],
|
|
1194
|
+
['name', 'Test', 40],
|
|
1195
|
+
['mode', 'Mode'],
|
|
1196
|
+
['status_label', 'Status'],
|
|
1197
|
+
['outcome', 'Outcome'],
|
|
1198
|
+
['major_problems', 'Major'],
|
|
1199
|
+
['minor_problems', 'Minor'],
|
|
1200
|
+
]), result.runs.length, result.total, offset, 'No runs.'));
|
|
1201
|
+
}));
|
|
1202
|
+
runs
|
|
1203
|
+
.command('show <run>')
|
|
1204
|
+
.description('One run: status, outcome, problems found and quality scores.')
|
|
1205
|
+
.action(run(async ({ client, out, project }, number) => {
|
|
1206
|
+
const result = await client.action('get_run', {
|
|
1207
|
+
project,
|
|
1208
|
+
run_number: intArg(number),
|
|
1209
|
+
});
|
|
1210
|
+
const summary = result.judging_summary;
|
|
1211
|
+
const scores = (summary?.quality_scores ?? []).filter((item) => item.average !== null && item.average !== undefined);
|
|
1212
|
+
out.result(result, () => fields([
|
|
1213
|
+
['Run', `#${result.run_number} ${result.name}`],
|
|
1214
|
+
['Status', result.status_label],
|
|
1215
|
+
['Outcome', result.outcome],
|
|
1216
|
+
['Passed', result.test_passed],
|
|
1217
|
+
['Summary', summary?.headline],
|
|
1218
|
+
['Conversations', result.conversations],
|
|
1219
|
+
['Not reviewed', summary?.unjudged_conversations],
|
|
1220
|
+
['Major problems', result.major_problems],
|
|
1221
|
+
['Minor problems', result.minor_problems],
|
|
1222
|
+
['Quality (1-5)', summary?.quality_average],
|
|
1223
|
+
...scores.map((item) => [` ${item.label}`, item.average]),
|
|
1224
|
+
['Error', result.error_message],
|
|
1225
|
+
['Link', result.url],
|
|
1226
|
+
]));
|
|
1227
|
+
}));
|
|
1228
|
+
runs
|
|
1229
|
+
.command('batches')
|
|
1230
|
+
.description('Launches, newest first: tests started together count as one, as the Suites view lists them.')
|
|
1231
|
+
.addOption(new Option('--kind <kind>', 'only launches of this kind').choices(['suite', 'schedule', 'selection', 'category', 'single']))
|
|
1232
|
+
.option('--suite <suite>', 'only the launches of this suite (id or name)')
|
|
1233
|
+
.addOption(new Option('--status <status>', 'still running or completed').choices(['running', 'completed']))
|
|
1234
|
+
.addOption(testModeOption())
|
|
1235
|
+
.addOption(fromOption())
|
|
1236
|
+
.addOption(toOption())
|
|
1237
|
+
.option('--search <text>', 'only launches whose label or a test name contains this')
|
|
1238
|
+
.addOption(limitOption('launches', '20', 100))
|
|
1239
|
+
.addOption(offsetOption())
|
|
1240
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1241
|
+
const offset = offsetOf(opts);
|
|
1242
|
+
const result = await client.action('list_batches', {
|
|
1243
|
+
project,
|
|
1244
|
+
kind: opts.kind,
|
|
1245
|
+
suite: opts.suite ? suiteRef(String(opts.suite)) : undefined,
|
|
1246
|
+
status: opts.status,
|
|
1247
|
+
mode: opts.mode,
|
|
1248
|
+
from: opts.from,
|
|
1249
|
+
to: opts.to,
|
|
1250
|
+
search: opts.search,
|
|
1251
|
+
limit: limitOf(opts, 100),
|
|
1252
|
+
offset,
|
|
1253
|
+
});
|
|
1254
|
+
out.result(result, () => paged(table(result.batches.map((row) => ({
|
|
1255
|
+
...row,
|
|
1256
|
+
passing: row.no_major_percent === null || row.no_major_percent === undefined ? null : `${row.no_major_percent}%`,
|
|
1257
|
+
runs: Array.isArray(row.run_numbers) ? row.run_numbers.map((value) => `#${value}`) : null,
|
|
1258
|
+
})), [
|
|
1259
|
+
['batch_id', 'Batch', 36],
|
|
1260
|
+
['label', 'Launch', 36],
|
|
1261
|
+
['status', 'Status'],
|
|
1262
|
+
['tests', 'Tests'],
|
|
1263
|
+
['passing', 'No major'],
|
|
1264
|
+
['major_problems', 'Major'],
|
|
1265
|
+
['minor_problems', 'Minor'],
|
|
1266
|
+
['runs', 'Runs', 30],
|
|
1267
|
+
]), result.batches.length, result.total, offset, 'No launches.'));
|
|
1268
|
+
}));
|
|
1269
|
+
runs
|
|
1270
|
+
.command('delete <run>')
|
|
1271
|
+
.description('Delete a run with its conversations and problems. A run still working is stopped first.')
|
|
1272
|
+
.option('--yes', 'delete without asking')
|
|
1273
|
+
.action(run(async ({ client, out, project, opts }, number) => {
|
|
1274
|
+
const runNumber = intArg(number);
|
|
1275
|
+
if (!opts.yes) {
|
|
1276
|
+
const found = await client.action('get_run', { project, run_number: runNumber });
|
|
1277
|
+
if (!(await confirm(`Delete run #${found.run_number} ${found.name}?`))) {
|
|
1278
|
+
out.result({ deleted: false, run_number: runNumber }, () => 'Not deleted.');
|
|
1279
|
+
return EXIT.ok;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
const result = await client.action('delete_run', { project, run_number: runNumber });
|
|
1283
|
+
out.result(result, () => `Deleted run #${result.run_number} ${result.name}.`);
|
|
1284
|
+
}));
|
|
1285
|
+
const runsAgainArgs = (numbers, opts) => {
|
|
1286
|
+
if (!numbers.length && !opts.batch)
|
|
1287
|
+
throw new ApiError('Give the run numbers, or --batch.', 400, EXIT.usage);
|
|
1288
|
+
return { runs: numbers.map(intArg), batch: opts.batch };
|
|
1289
|
+
};
|
|
1290
|
+
waitOptions(runs
|
|
1291
|
+
.command('restart [runs...]')
|
|
1292
|
+
.description('Run the tests of earlier runs again, as new runs in one batch. A saved test runs as it stands now.')
|
|
1293
|
+
.option('--batch <id>', 'every run of one launch')).action(run(async (ctx, numbers = []) => {
|
|
1294
|
+
const result = await ctx.client.action('restart_runs', { project: ctx.project, ...runsAgainArgs(numbers, ctx.opts) });
|
|
1295
|
+
return launched(ctx, result);
|
|
1296
|
+
}));
|
|
1297
|
+
runs
|
|
1298
|
+
.command('rejudge [runs...]')
|
|
1299
|
+
.description('Judge the conversations of finished runs again with the current rules. Nothing is sent to the agent.')
|
|
1300
|
+
.option('--batch <id>', 'every run of one launch')
|
|
1301
|
+
.action(run(async (ctx, numbers = []) => {
|
|
1302
|
+
const { client, out, project, opts } = ctx;
|
|
1303
|
+
const result = await client.action('rejudge_runs', { project, ...runsAgainArgs(numbers, opts) });
|
|
1304
|
+
out.result(result, () => [
|
|
1305
|
+
result.judging.length
|
|
1306
|
+
? `Judging again: ${result.judging.map((number) => `#${number}`).join(', ')}. Wait for it: qualiloop runs wait ${result.batch_id}${projectFlag(ctx)}`
|
|
1307
|
+
: 'Nothing is being judged.',
|
|
1308
|
+
...result.skipped.map((item) => `Run #${item.run_number} skipped: ${item.reason}`),
|
|
1309
|
+
].join('\n'));
|
|
1310
|
+
return result.judging.length ? EXIT.ok : EXIT.failed;
|
|
1311
|
+
}));
|
|
1312
|
+
runs
|
|
1313
|
+
.command('rejudge-conversation <conversation>')
|
|
1314
|
+
.description('Judge one conversation again now, test or live. Nothing is sent to the agent.')
|
|
1315
|
+
.action(run(async (ctx, conversation) => {
|
|
1316
|
+
const { client, out, project } = ctx;
|
|
1317
|
+
const result = await client.action('rejudge_conversation', { project, conversation });
|
|
1318
|
+
out.result(result, () => result.judging
|
|
1319
|
+
? `Judging ${conversation} again. Read it in a minute: qualiloop conversation ${conversation}${projectFlag(ctx)}`
|
|
1320
|
+
: `${conversation} is being judged already, or has nothing to judge.`);
|
|
1321
|
+
}));
|
|
1322
|
+
runs
|
|
1323
|
+
.command('delete-conversation <run> <conversation>')
|
|
1324
|
+
.description('Delete one conversation of a finished run, with its verdict and problems.')
|
|
1325
|
+
.option('--yes', 'delete without asking')
|
|
1326
|
+
.action(run(async ({ client, out, project, opts }, number, conversation) => {
|
|
1327
|
+
const runNumber = intArg(number);
|
|
1328
|
+
if (!opts.yes) {
|
|
1329
|
+
const found = await client.action('get_run', { project, run_number: runNumber });
|
|
1330
|
+
if (!(await confirm(`Delete conversation ${conversation} of run #${found.run_number} ${found.name}?`))) {
|
|
1331
|
+
out.result({ deleted: false, run_number: runNumber, conversation }, () => 'Not deleted.');
|
|
1332
|
+
return EXIT.ok;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
const result = await client.action('delete_conversation', {
|
|
1336
|
+
project,
|
|
1337
|
+
run_number: runNumber,
|
|
1338
|
+
conversation,
|
|
1339
|
+
});
|
|
1340
|
+
out.result(result, () => `Deleted conversation ${result.conversation} of run #${result.run_number}.`);
|
|
1341
|
+
}));
|
|
1342
|
+
waitOptions(runs
|
|
1343
|
+
.command('wait <batch>')
|
|
1344
|
+
.description('Wait for the runs of one launch to finish (the batch run --wait prints), and exit by --fail-on.'), false).action(run(async (ctx, batch) => follow(ctx, ctx.project, batch)));
|
|
1345
|
+
const modeOption = () => new Option('--mode <mode>', 'only problems found by tests of this mode; live traffic counts as regular').choices([
|
|
1346
|
+
'regular',
|
|
1347
|
+
'red_team',
|
|
1348
|
+
'bias',
|
|
1349
|
+
]);
|
|
1350
|
+
const sourceOption = () => new Option('--source <source>', "test for Test Lab runs, live for the agent's real traffic").choices(['test', 'live']);
|
|
1351
|
+
const problems = program.command('problems').description('Problems QualiLoop found.');
|
|
1352
|
+
problems
|
|
1353
|
+
.command('list', { isDefault: true })
|
|
1354
|
+
.description('Problems, newest first.')
|
|
1355
|
+
.option('--run <n>', 'only problems of this run')
|
|
1356
|
+
.addOption(new Option('--severity <severity>', 'major or minor').choices(['major', 'minor']))
|
|
1357
|
+
.option('--category <id>', 'only problems of this category: its id, or part of its title')
|
|
1358
|
+
.option('--unsorted', 'only problems no category holds yet')
|
|
1359
|
+
.addOption(modeOption())
|
|
1360
|
+
.addOption(sourceOption())
|
|
1361
|
+
.addOption(limitOption('problems', '20', 200))
|
|
1362
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1363
|
+
const result = await client.action('list_problems', {
|
|
1364
|
+
project,
|
|
1365
|
+
run_number: opts.run ? intArg(String(opts.run)) : undefined,
|
|
1366
|
+
severity: opts.severity,
|
|
1367
|
+
category: opts.category,
|
|
1368
|
+
unsorted: opts.unsorted ? true : undefined,
|
|
1369
|
+
mode: opts.mode,
|
|
1370
|
+
source: opts.source,
|
|
1371
|
+
limit: limitOf(opts, 200),
|
|
1372
|
+
});
|
|
1373
|
+
out.result(result, () => listed(table(result.problems, [
|
|
1374
|
+
['id', 'ID'],
|
|
1375
|
+
['severity', 'Severity'],
|
|
1376
|
+
['title', 'Problem', 55],
|
|
1377
|
+
['run_number', 'Run'],
|
|
1378
|
+
['conversation', 'Conversation', 36],
|
|
1379
|
+
]), result.problems.length, result.total, 'No problems.'));
|
|
1380
|
+
}));
|
|
1381
|
+
const categories = problems
|
|
1382
|
+
.command('categories')
|
|
1383
|
+
.description('Recurring kinds of problem, biggest first, with their suggested fix.');
|
|
1384
|
+
categories
|
|
1385
|
+
.command('list', { isDefault: true })
|
|
1386
|
+
.description('List the categories, biggest first, with their ids.')
|
|
1387
|
+
.option('--solved', 'include categories marked solved')
|
|
1388
|
+
.addOption(modeOption())
|
|
1389
|
+
.addOption(sourceOption())
|
|
1390
|
+
.addOption(limitOption('categories', '20', 200))
|
|
1391
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1392
|
+
const result = await client.action('list_problem_categories', {
|
|
1393
|
+
project,
|
|
1394
|
+
include_solved: Boolean(opts.solved),
|
|
1395
|
+
mode: opts.mode,
|
|
1396
|
+
source: opts.source,
|
|
1397
|
+
limit: limitOf(opts, 200),
|
|
1398
|
+
});
|
|
1399
|
+
out.result(result, () => listed(table(result.categories, [
|
|
1400
|
+
['id', 'ID'],
|
|
1401
|
+
['severity', 'Severity'],
|
|
1402
|
+
['problems', 'Problems'],
|
|
1403
|
+
['solved', 'Solved'],
|
|
1404
|
+
['title', 'Category', 50],
|
|
1405
|
+
['suggested_fix', 'Suggested fix', 50],
|
|
1406
|
+
]), result.categories.length, result.total_categories, 'No categories yet.') + (result.categories.length ? '\n\nThe whole fix: qualiloop problems categories show <id>' : ''));
|
|
1407
|
+
}));
|
|
1408
|
+
categories
|
|
1409
|
+
.command('show <id>')
|
|
1410
|
+
.description('One category in full: its description, the whole suggested fix, and its latest problems.')
|
|
1411
|
+
.action(run(async ({ client, out, project }, id) => {
|
|
1412
|
+
const result = await client.action('get_problem_category', {
|
|
1413
|
+
project,
|
|
1414
|
+
category: intArg(id),
|
|
1415
|
+
});
|
|
1416
|
+
out.result(result, () => [
|
|
1417
|
+
fields([
|
|
1418
|
+
['Category', `${result.id} ${result.title}`],
|
|
1419
|
+
['Severity', result.severity],
|
|
1420
|
+
['Problems', result.problems],
|
|
1421
|
+
['Solved', result.solved],
|
|
1422
|
+
['Link', result.url],
|
|
1423
|
+
]),
|
|
1424
|
+
'',
|
|
1425
|
+
'Description:',
|
|
1426
|
+
String(result.description ?? '-'),
|
|
1427
|
+
'',
|
|
1428
|
+
'Suggested fix:',
|
|
1429
|
+
String(result.suggested_fix ?? '-'),
|
|
1430
|
+
'',
|
|
1431
|
+
table(result.latest_problems, [
|
|
1432
|
+
['severity', 'Severity'],
|
|
1433
|
+
['title', 'Latest problems', 55],
|
|
1434
|
+
['conversation', 'Conversation', 36],
|
|
1435
|
+
]),
|
|
1436
|
+
].join('\n'));
|
|
1437
|
+
}));
|
|
1438
|
+
categories
|
|
1439
|
+
.command('solve <id>')
|
|
1440
|
+
.description('Mark a category solved once its fix is deployed; the next problem in it opens it again.')
|
|
1441
|
+
.option('--reopen', 'open it again instead')
|
|
1442
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1443
|
+
const result = await client.action('set_category_solved', {
|
|
1444
|
+
project,
|
|
1445
|
+
category: intArg(id),
|
|
1446
|
+
solved: !opts.reopen,
|
|
1447
|
+
});
|
|
1448
|
+
out.result(result, () => `Category ${result.id} ${result.category} is ${result.solved ? 'solved' : 'open again'}.`);
|
|
1449
|
+
}));
|
|
1450
|
+
categories
|
|
1451
|
+
.command('delete <id>')
|
|
1452
|
+
.description('Delete a category (id or title) and every problem in it.')
|
|
1453
|
+
.option('--never-flag', 'also add a do-not-flag rule written from the category')
|
|
1454
|
+
.option('--yes', 'delete without asking')
|
|
1455
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1456
|
+
const category = suiteRef(id);
|
|
1457
|
+
if (!opts.yes) {
|
|
1458
|
+
const found = await client.action('get_problem_category', { project, category });
|
|
1459
|
+
if (!(await confirm(`Delete category ${found.id} ${found.title} and its ${found.problems} problems?`))) {
|
|
1460
|
+
out.result({ deleted: false, id: found.id }, () => 'Not deleted.');
|
|
1461
|
+
return EXIT.ok;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
const result = await client.action('delete_problem_category', {
|
|
1465
|
+
project,
|
|
1466
|
+
category,
|
|
1467
|
+
add_to_never_flag: Boolean(opts.neverFlag),
|
|
1468
|
+
});
|
|
1469
|
+
out.result(result, () => `Deleted category ${result.id} ${result.category} and its ${result.deleted_problems} problems.` +
|
|
1470
|
+
(result.never_flag_rule ? `\nAdded do-not-flag rule: ${result.never_flag_rule}` : ''));
|
|
1471
|
+
}));
|
|
1472
|
+
problems
|
|
1473
|
+
.command('severity <id> <severity>')
|
|
1474
|
+
.description("Upgrade a problem to major or downgrade it to minor; the new tier replaces the judge's everywhere.")
|
|
1475
|
+
.action(run(async ({ client, out, project }, id, severity) => {
|
|
1476
|
+
if (!['major', 'minor'].includes(severity))
|
|
1477
|
+
throw new ApiError('Say major or minor.', 400, EXIT.usage);
|
|
1478
|
+
const result = await client.action('set_problem_severity', { project, problem: intArg(id), severity });
|
|
1479
|
+
out.result(result, () => `Problem ${result.id} ${result.title} is ${result.severity} (was ${result.previous_severity}).`);
|
|
1480
|
+
}));
|
|
1481
|
+
problems
|
|
1482
|
+
.command('delete <id>')
|
|
1483
|
+
.description('Delete a problem for good; nothing of it remains, unlike dismiss.')
|
|
1484
|
+
.option('--with-category', 'also delete its category and every problem in it')
|
|
1485
|
+
.option('--never-flag', 'also add a do-not-flag rule written from its category or the problem')
|
|
1486
|
+
.option('--yes', 'delete without asking')
|
|
1487
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1488
|
+
const problem = intArg(id);
|
|
1489
|
+
const what = opts.withCategory ? `problem ${problem} with its category and every problem in it` : `problem ${problem}`;
|
|
1490
|
+
if (!opts.yes && !(await confirm(`Delete ${what}?`))) {
|
|
1491
|
+
out.result({ deleted: false, id: problem }, () => 'Not deleted.');
|
|
1492
|
+
return EXIT.ok;
|
|
1493
|
+
}
|
|
1494
|
+
const result = await client.action('delete_problem', {
|
|
1495
|
+
project,
|
|
1496
|
+
problem,
|
|
1497
|
+
delete_category: Boolean(opts.withCategory),
|
|
1498
|
+
add_to_never_flag: Boolean(opts.neverFlag),
|
|
1499
|
+
});
|
|
1500
|
+
out.result(result, () => `Deleted problem ${result.id} ${result.title}` +
|
|
1501
|
+
(result.deleted_category ? ` with category ${result.deleted_category} (${result.deleted_problems} problems)` : '') +
|
|
1502
|
+
'.' +
|
|
1503
|
+
(result.never_flag_rule ? `\nAdded do-not-flag rule: ${result.never_flag_rule}` : ''));
|
|
1504
|
+
}));
|
|
1505
|
+
problems
|
|
1506
|
+
.command('sort')
|
|
1507
|
+
.description('Sort problems into categories now instead of waiting for the next test batch.')
|
|
1508
|
+
.addOption(new Option('--scope <scope>', 'unsorted: the problems in no category, now; unsolved or solved: every problem on that tab again, in the background')
|
|
1509
|
+
.choices(['unsorted', 'unsolved', 'solved'])
|
|
1510
|
+
.default('unsorted'))
|
|
1511
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1512
|
+
const result = await client.action('sort_problems', { project, scope: opts.scope });
|
|
1513
|
+
out.result(result, () => result.background
|
|
1514
|
+
? `Sorting the ${result.scope} problems again in the background. Then: qualiloop problems categories`
|
|
1515
|
+
: result.skipped
|
|
1516
|
+
? String(result.skipped)
|
|
1517
|
+
: `Sorted ${result.sorted} problems; ${result.new_categories} new categories, ${result.updated_fixes} fixes rewritten.`);
|
|
1518
|
+
}));
|
|
1519
|
+
const checksRender = (result) => {
|
|
1520
|
+
const limit = result.max_tokens_per_turn ? `${result.max_tokens_per_turn} tokens` : 'no limit set';
|
|
1521
|
+
return [
|
|
1522
|
+
fields([
|
|
1523
|
+
['Token limit per turn', result.token_budget_enabled ? `on, ${limit}` : `off (${limit})`],
|
|
1524
|
+
['Unanswered messages', result.no_answer_enabled ? 'reported' : 'not reported'],
|
|
1525
|
+
['Link', result.url],
|
|
1526
|
+
]),
|
|
1527
|
+
'',
|
|
1528
|
+
table(result.custom_checks, [
|
|
1529
|
+
['id', 'ID'],
|
|
1530
|
+
['severity', 'Severity'],
|
|
1531
|
+
['title', 'Custom check', 50],
|
|
1532
|
+
['description', 'Description', 50],
|
|
1533
|
+
]) || 'No custom checks.',
|
|
1534
|
+
].join('\n');
|
|
1535
|
+
};
|
|
1536
|
+
const onOff = (value, flag) => {
|
|
1537
|
+
if (value === undefined)
|
|
1538
|
+
return undefined;
|
|
1539
|
+
if (!['on', 'off'].includes(String(value)))
|
|
1540
|
+
throw new ApiError(`${flag} takes on or off.`, 400, EXIT.usage);
|
|
1541
|
+
return value === 'on';
|
|
1542
|
+
};
|
|
1543
|
+
const checks = problems
|
|
1544
|
+
.command('checks')
|
|
1545
|
+
.description('Checks: the token limit per turn, unanswered messages, and custom checks added by hand.');
|
|
1546
|
+
checks
|
|
1547
|
+
.command('list', { isDefault: true })
|
|
1548
|
+
.description('Show the checks.')
|
|
1549
|
+
.action(run(async ({ client, out, project }) => {
|
|
1550
|
+
const result = await client.action('get_checks', { project });
|
|
1551
|
+
out.result(result, () => checksRender(result));
|
|
1552
|
+
}));
|
|
1553
|
+
checks
|
|
1554
|
+
.command('add <title...>')
|
|
1555
|
+
.description('Add a custom check: the judge looks for it in every conversation from now on.')
|
|
1556
|
+
.addOption(new Option('--severity <severity>', 'major or minor').choices(['major', 'minor']).makeOptionMandatory())
|
|
1557
|
+
.option('--description <text>', 'what counts as this problem')
|
|
1558
|
+
.action(run(async ({ client, out, project, opts }, words) => {
|
|
1559
|
+
const result = await client.action('create_custom_check', {
|
|
1560
|
+
project,
|
|
1561
|
+
title: words.join(' ').trim(),
|
|
1562
|
+
severity: opts.severity,
|
|
1563
|
+
description: opts.description,
|
|
1564
|
+
});
|
|
1565
|
+
out.result(result, () => `Added custom check ${result.id} ${result.title} (${result.severity}).\n` +
|
|
1566
|
+
'Move earlier problems into it: qualiloop problems sort');
|
|
1567
|
+
}));
|
|
1568
|
+
checks
|
|
1569
|
+
.command('set')
|
|
1570
|
+
.description('Change the token limit per turn and the unanswered messages check; only what you give changes.')
|
|
1571
|
+
.option('--token-limit <on|off>', 'turn the token limit per turn on or off')
|
|
1572
|
+
.option('--max-tokens <n>', 'the most tokens one turn may use')
|
|
1573
|
+
.option('--unanswered <on|off>', 'report a conversation whose last message got no reply')
|
|
1574
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1575
|
+
const result = await client.action('set_checks', {
|
|
1576
|
+
project,
|
|
1577
|
+
token_budget_enabled: onOff(opts.tokenLimit, '--token-limit'),
|
|
1578
|
+
max_tokens_per_turn: opts.maxTokens === undefined ? undefined : intArg(String(opts.maxTokens)),
|
|
1579
|
+
no_answer_enabled: onOff(opts.unanswered, '--unanswered'),
|
|
1580
|
+
});
|
|
1581
|
+
out.result(result, () => checksRender(result));
|
|
1582
|
+
}));
|
|
1583
|
+
checks
|
|
1584
|
+
.command('import-elevenlabs')
|
|
1585
|
+
.description("Add a custom check for each success criterion of the project's ElevenLabs agent. Names already taken are left as they are.")
|
|
1586
|
+
.action(run(async ({ client, out, project }) => {
|
|
1587
|
+
const result = await client.action('elevenlabs_import_criteria', { project });
|
|
1588
|
+
out.result(result, () => [
|
|
1589
|
+
result.added.length ? `Added: ${result.added.join(', ')}` : 'No new checks.',
|
|
1590
|
+
...(result.existing.length ? [`Already there: ${result.existing.join(', ')}`] : []),
|
|
1591
|
+
].join('\n'));
|
|
1592
|
+
}));
|
|
1593
|
+
problems
|
|
1594
|
+
.command('dismiss <id>')
|
|
1595
|
+
.description('Mark a problem a false alarm: it stops counting but stays on its conversation.')
|
|
1596
|
+
.option('--never-flag', 'also add a do-not-flag rule written from its category or the problem')
|
|
1597
|
+
.option('--undo', 'put a dismissed problem back')
|
|
1598
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1599
|
+
const result = await client.action('dismiss_problem', {
|
|
1600
|
+
project,
|
|
1601
|
+
problem: intArg(id),
|
|
1602
|
+
dismissed: !opts.undo,
|
|
1603
|
+
add_to_never_flag: Boolean(opts.neverFlag),
|
|
1604
|
+
});
|
|
1605
|
+
out.result(result, () => `${result.dismissed ? 'Dismissed' : 'Put back'} problem ${result.id} ${result.title}.` +
|
|
1606
|
+
(result.never_flag_rule ? `\nAdded do-not-flag rule: ${result.never_flag_rule}` : ''));
|
|
1607
|
+
}));
|
|
1608
|
+
const rulesRender = (result) => table(result.rules, [
|
|
1609
|
+
['number', '#'],
|
|
1610
|
+
['rule', 'Do not flag', 90],
|
|
1611
|
+
]) || 'No do-not-flag rules.';
|
|
1612
|
+
const rules = problems
|
|
1613
|
+
.command('rules')
|
|
1614
|
+
.description('Do-not-flag rules: behaviour the judge does not report because the team decided it is correct.');
|
|
1615
|
+
rules
|
|
1616
|
+
.command('list', { isDefault: true })
|
|
1617
|
+
.description('List the rules, numbered.')
|
|
1618
|
+
.action(run(async ({ client, out, project }) => {
|
|
1619
|
+
const result = await client.action('list_never_flag_rules', { project });
|
|
1620
|
+
out.result(result, () => rulesRender(result));
|
|
1621
|
+
}));
|
|
1622
|
+
rules
|
|
1623
|
+
.command('add [rule...]')
|
|
1624
|
+
.description('Add a rule in your words, or write one from a problem or a problem category.')
|
|
1625
|
+
.option('--problem <id>', 'write the rule from this problem')
|
|
1626
|
+
.option('--category <id>', 'write the rule from this problem category')
|
|
1627
|
+
.action(run(async ({ client, out, project, opts }, words) => {
|
|
1628
|
+
const text = (words ?? []).join(' ').trim();
|
|
1629
|
+
const result = await client.action('add_never_flag_rule', {
|
|
1630
|
+
project,
|
|
1631
|
+
rule: text || undefined,
|
|
1632
|
+
problem: opts.problem ? intArg(String(opts.problem)) : undefined,
|
|
1633
|
+
category: opts.category ? suiteRef(String(opts.category)) : undefined,
|
|
1634
|
+
});
|
|
1635
|
+
out.result(result, () => `${result.added ? 'Added' : 'Already there'}: ${result.rule}\n\n${rulesRender(result)}`);
|
|
1636
|
+
}));
|
|
1637
|
+
rules
|
|
1638
|
+
.command('remove <number>')
|
|
1639
|
+
.description('Remove a rule by its number, so the judge reports that behaviour again.')
|
|
1640
|
+
.action(run(async ({ client, out, project }, number) => {
|
|
1641
|
+
const result = await client.action('remove_never_flag_rule', {
|
|
1642
|
+
project,
|
|
1643
|
+
number: intArg(number),
|
|
1644
|
+
});
|
|
1645
|
+
out.result(result, () => `Removed: ${result.removed}\n\n${rulesRender(result)}`);
|
|
1646
|
+
}));
|
|
1647
|
+
program
|
|
1648
|
+
.command('conversations')
|
|
1649
|
+
.description('Tested conversations across runs, newest first, clean ones included, as the Conversations view lists them.')
|
|
1650
|
+
.option('--run <n>', 'only the conversations of this run')
|
|
1651
|
+
.option('--batch <id>', 'only the conversations of one launch')
|
|
1652
|
+
.addOption(new Option('--verdict <verdict>', 'only conversations with this verdict').choices([
|
|
1653
|
+
'major',
|
|
1654
|
+
'minor',
|
|
1655
|
+
'clean',
|
|
1656
|
+
'not_reviewed',
|
|
1657
|
+
'pending',
|
|
1658
|
+
]))
|
|
1659
|
+
.addOption(testModeOption())
|
|
1660
|
+
.addOption(fromOption())
|
|
1661
|
+
.addOption(toOption())
|
|
1662
|
+
.option('--search <text>', 'only conversations whose test name or id contains this')
|
|
1663
|
+
.addOption(limitOption('conversations', '50', 200))
|
|
1664
|
+
.addOption(offsetOption())
|
|
1665
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1666
|
+
const offset = offsetOf(opts);
|
|
1667
|
+
const result = await client.action('list_conversations', {
|
|
1668
|
+
project,
|
|
1669
|
+
run_number: opts.run ? intArg(String(opts.run)) : undefined,
|
|
1670
|
+
batch: opts.batch,
|
|
1671
|
+
verdict: opts.verdict,
|
|
1672
|
+
mode: opts.mode,
|
|
1673
|
+
from: opts.from,
|
|
1674
|
+
to: opts.to,
|
|
1675
|
+
search: opts.search,
|
|
1676
|
+
limit: limitOf(opts, 200),
|
|
1677
|
+
offset,
|
|
1678
|
+
});
|
|
1679
|
+
out.result(result, () => paged(table(result.conversations, [
|
|
1680
|
+
['conversation', 'Conversation', 36],
|
|
1681
|
+
['run_number', 'Run'],
|
|
1682
|
+
['test', 'Test', 36],
|
|
1683
|
+
['verdict', 'Verdict'],
|
|
1684
|
+
['major_problems', 'Major'],
|
|
1685
|
+
['minor_problems', 'Minor'],
|
|
1686
|
+
['turns', 'Turns'],
|
|
1687
|
+
]), result.conversations.length, result.total, offset, 'No conversations.') + (result.conversations.length ? '\n\nRead one: qualiloop conversation <id>' : ''));
|
|
1688
|
+
}));
|
|
1689
|
+
const sourceLines = (problem) => (problem.evidence ?? [])
|
|
1690
|
+
.map((item) => item.knowledge_source)
|
|
1691
|
+
.filter((source) => Boolean(source))
|
|
1692
|
+
.map((source) => ` Quotes ${source.name} (source ${source.id}, version ${source.version_number ?? '-'}${source.current ? '' : ', no longer in force'})`);
|
|
1693
|
+
const traceLines = (trace) => {
|
|
1694
|
+
if (!trace)
|
|
1695
|
+
return [];
|
|
1696
|
+
const short = (value) => {
|
|
1697
|
+
const text = typeof value === 'string' ? value : JSON.stringify(value);
|
|
1698
|
+
return text === undefined ? '' : text.length > 160 ? `${text.slice(0, 157)}...` : text;
|
|
1699
|
+
};
|
|
1700
|
+
const calls = (trace.tool_calls ?? trace.agent_reported_steps ?? []);
|
|
1701
|
+
return [
|
|
1702
|
+
...calls.map((call) => ` tool ${call.name}(${short(call.arguments)}) -> ${short(call.output)}`),
|
|
1703
|
+
...(trace.model_calls ?? []).map((name) => ` model call ${name}`),
|
|
1704
|
+
];
|
|
1705
|
+
};
|
|
1706
|
+
program
|
|
1707
|
+
.command('conversation <id>')
|
|
1708
|
+
.description("One conversation in full, with its verdict, problems and the agent's traced steps.")
|
|
1709
|
+
.option('--no-trace', "leave out the agent's steps")
|
|
1710
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1711
|
+
const result = await client.action('get_conversation', { project, conversation: id, include_trace: opts.trace !== false });
|
|
1712
|
+
out.result(result, () => [
|
|
1713
|
+
...result.messages.flatMap((message) => [
|
|
1714
|
+
`${message.role === 'user' ? 'User ' : 'Agent'} ${message.text}`,
|
|
1715
|
+
...traceLines(message.trace),
|
|
1716
|
+
]),
|
|
1717
|
+
'',
|
|
1718
|
+
`Verdict: ${result.verdict?.status ?? 'not judged'}`,
|
|
1719
|
+
...result.problems.map((problem) => [
|
|
1720
|
+
`\n[${problem.severity}] ${problem.title}\n ${problem.explanation}${problem.suggested_fix ? `\n Fix: ${problem.suggested_fix}` : ''}`,
|
|
1721
|
+
...sourceLines(problem),
|
|
1722
|
+
].join('\n')),
|
|
1723
|
+
].join('\n'));
|
|
1724
|
+
}));
|
|
1725
|
+
const reportPeriod = (row) => row.period_start
|
|
1726
|
+
? `${String(row.period_start).slice(0, 10)} to ${String(row.period_end ?? '').slice(0, 10) || 'now'}`
|
|
1727
|
+
: `${row.runs_selected ?? 0} run(s)`;
|
|
1728
|
+
const reports = program.command('reports').description('Reports: frozen snapshots of test results to read and share.');
|
|
1729
|
+
reports
|
|
1730
|
+
.command('list', { isDefault: true })
|
|
1731
|
+
.description('The project\'s reports, newest first.')
|
|
1732
|
+
.addOption(limitOption('reports', '20', 200))
|
|
1733
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1734
|
+
const result = await client.action('list_reports', {
|
|
1735
|
+
project,
|
|
1736
|
+
limit: limitOf(opts, 200),
|
|
1737
|
+
});
|
|
1738
|
+
out.result(result, () => listed(table(result.reports.map((row) => ({ ...row, covers: reportPeriod(row) })), [
|
|
1739
|
+
['id', 'ID'],
|
|
1740
|
+
['title', 'Title', 45],
|
|
1741
|
+
['status', 'Status'],
|
|
1742
|
+
['covers', 'Covers', 26],
|
|
1743
|
+
['modes', 'Modes', 24],
|
|
1744
|
+
['shared', 'Shared'],
|
|
1745
|
+
]), result.reports.length, result.total, 'No reports yet. Make one with: qualiloop reports create'));
|
|
1746
|
+
}));
|
|
1747
|
+
reports
|
|
1748
|
+
.command('show <id>')
|
|
1749
|
+
.description('One report: its verdict, numbers and issues with their fixes.')
|
|
1750
|
+
.action(run(async ({ client, out, project }, id) => {
|
|
1751
|
+
const result = await client.action('get_report', {
|
|
1752
|
+
project,
|
|
1753
|
+
report: intArg(id),
|
|
1754
|
+
});
|
|
1755
|
+
out.result(result, () => [
|
|
1756
|
+
fields([
|
|
1757
|
+
['Report', `${result.id} ${result.title}`],
|
|
1758
|
+
['Status', result.status],
|
|
1759
|
+
['Covers', reportPeriod(result)],
|
|
1760
|
+
['Modes', result.modes],
|
|
1761
|
+
['Shared', result.shared ? `yes, until ${result.share_expires_at ?? 'revoked'}` : 'no'],
|
|
1762
|
+
['Verdict', result.decision?.title],
|
|
1763
|
+
['Pass rate', result.numbers?.pass_rate === undefined ? undefined : `${result.numbers.pass_rate}%`],
|
|
1764
|
+
['Error', result.error],
|
|
1765
|
+
['Link', result.url],
|
|
1766
|
+
]),
|
|
1767
|
+
...(result.next_step ? ['', String(result.next_step)] : []),
|
|
1768
|
+
...(result.issues?.length
|
|
1769
|
+
? [
|
|
1770
|
+
'',
|
|
1771
|
+
table(result.issues, [
|
|
1772
|
+
['ref', 'Ref'],
|
|
1773
|
+
['title', 'Issue', 50],
|
|
1774
|
+
['major_problems', 'Major'],
|
|
1775
|
+
['minor_problems', 'Minor'],
|
|
1776
|
+
['fix', 'Fix', 60],
|
|
1777
|
+
]),
|
|
1778
|
+
]
|
|
1779
|
+
: []),
|
|
1780
|
+
].join('\n'));
|
|
1781
|
+
}));
|
|
1782
|
+
reports
|
|
1783
|
+
.command('create')
|
|
1784
|
+
.description('Make a report of chosen runs, the last few days or a date range. Builds in about a minute.')
|
|
1785
|
+
.option('--title <title>', 'the report\'s title')
|
|
1786
|
+
.option('--runs <numbers...>', 'run numbers to report on')
|
|
1787
|
+
.option('--days <n>', 'the runs of the last this many days (default 30 without --runs or --from)')
|
|
1788
|
+
.option('--from <date>', 'the runs from this day, YYYY-MM-DD (UTC)')
|
|
1789
|
+
.option('--to <date>', 'with --from, the last day to include, YYYY-MM-DD (UTC); default now')
|
|
1790
|
+
.addOption(new Option('--mode <modes...>', 'test modes to include (default all)').choices(['regular', 'red_team', 'bias']))
|
|
1791
|
+
.option('--exclude-minor', 'leave minor problems out')
|
|
1792
|
+
.option('--all-conversations', 'list every conversation, not only those with problems')
|
|
1793
|
+
.option('--language <language>', 'the language to write it in', 'English')
|
|
1794
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
1795
|
+
const result = await client.action('create_report', {
|
|
1796
|
+
project,
|
|
1797
|
+
title: opts.title,
|
|
1798
|
+
runs: (opts.runs ?? []).map(intArg),
|
|
1799
|
+
days: opts.days === undefined ? undefined : intArg(String(opts.days)),
|
|
1800
|
+
from_date: opts.from,
|
|
1801
|
+
to_date: opts.to,
|
|
1802
|
+
modes: opts.mode,
|
|
1803
|
+
exclude_minor: Boolean(opts.excludeMinor),
|
|
1804
|
+
include_all_conversations: Boolean(opts.allConversations),
|
|
1805
|
+
language: opts.language,
|
|
1806
|
+
});
|
|
1807
|
+
out.result(result, () => `Started report ${result.id} ${result.title}.\n${result.next_step ?? ''}`.trim());
|
|
1808
|
+
}));
|
|
1809
|
+
reports
|
|
1810
|
+
.command('rebuild <id>')
|
|
1811
|
+
.alias('update')
|
|
1812
|
+
.description('Build a report again from the results as they are now, with its period, runs and options. Keeps its id and share link.')
|
|
1813
|
+
.action(run(async ({ client, out, project }, id) => {
|
|
1814
|
+
const result = await client.action('rebuild_report', { project, report: intArg(id) });
|
|
1815
|
+
out.result(result, () => `Updating report ${result.id} ${result.title}.\n${result.next_step ?? ''}`.trim());
|
|
1816
|
+
}));
|
|
1817
|
+
reports
|
|
1818
|
+
.command('share <id>')
|
|
1819
|
+
.description('Make a public link to a ready report: anyone with the link and its password can read it without signing in. Replaces an earlier link.')
|
|
1820
|
+
.addOption(new Option('--expires <days>', 'days until the link stops working').choices(['7', '30', '90', '365', 'never']).default('30'))
|
|
1821
|
+
.option('--password <password>', 'the password the link asks for, 8 to 128 characters; it stays in your shell history (default: a strong one is made)')
|
|
1822
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1823
|
+
const result = await client.action('share_report', {
|
|
1824
|
+
project,
|
|
1825
|
+
report: intArg(id),
|
|
1826
|
+
expires_in_days: opts.expires === 'never' ? null : intArg(String(opts.expires)),
|
|
1827
|
+
password: opts.password,
|
|
1828
|
+
});
|
|
1829
|
+
out.result(result, () => [
|
|
1830
|
+
fields([
|
|
1831
|
+
['Link', result.share_url],
|
|
1832
|
+
['Password', result.password],
|
|
1833
|
+
['Expires', result.expires_at ?? 'never'],
|
|
1834
|
+
]),
|
|
1835
|
+
'',
|
|
1836
|
+
'Shown only this once: QualiLoop keeps only a hash of the link and the password.',
|
|
1837
|
+
...(result.replaced_earlier_link ? ['The earlier link and password no longer work.'] : []),
|
|
1838
|
+
].join('\n'));
|
|
1839
|
+
}));
|
|
1840
|
+
reports
|
|
1841
|
+
.command('unshare <id>')
|
|
1842
|
+
.description('Revoke a report\'s public link: the link and its password stop working at once.')
|
|
1843
|
+
.action(run(async ({ client, out, project }, id) => {
|
|
1844
|
+
const result = await client.action('unshare_report', { project, report: intArg(id) });
|
|
1845
|
+
out.result(result, () => result.was_shared
|
|
1846
|
+
? `Report ${result.id} ${result.title} is no longer shared.`
|
|
1847
|
+
: `Report ${result.id} ${result.title} was not shared.`);
|
|
1848
|
+
}));
|
|
1849
|
+
reports
|
|
1850
|
+
.command('delete <id>')
|
|
1851
|
+
.description('Delete a report. Its public link stops working; the runs and problems stay.')
|
|
1852
|
+
.option('--yes', 'delete without asking')
|
|
1853
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1854
|
+
const reportId = intArg(id);
|
|
1855
|
+
if (!opts.yes) {
|
|
1856
|
+
const found = await client.action('get_report', { project, report: reportId });
|
|
1857
|
+
if (!(await confirm(`Delete report ${found.id} ${found.title}?`))) {
|
|
1858
|
+
out.result({ deleted: false, id: reportId }, () => 'Not deleted.');
|
|
1859
|
+
return EXIT.ok;
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
const result = await client.action('delete_report', { project, report: reportId });
|
|
1863
|
+
out.result(result, () => `Deleted report ${result.id} ${result.title}.`);
|
|
1864
|
+
}));
|
|
1865
|
+
const DOWNLOADS = {
|
|
1866
|
+
pdf: { path: 'pdf', extension: 'pdf' },
|
|
1867
|
+
'summary-csv': { path: 'summary-csv', extension: 'csv' },
|
|
1868
|
+
csv: { path: 'csv', extension: 'csv' },
|
|
1869
|
+
};
|
|
1870
|
+
reports
|
|
1871
|
+
.command('download <id>')
|
|
1872
|
+
.description('Save a ready report as the executive PDF, the test summary CSV, or the CSV of all conversations.')
|
|
1873
|
+
.addOption(new Option('--format <format>', 'pdf, summary-csv (one row per test) or csv (every conversation)')
|
|
1874
|
+
.choices(Object.keys(DOWNLOADS))
|
|
1875
|
+
.default('pdf'))
|
|
1876
|
+
.option('--out <file>', 'where to save it; - for stdout (default: the name QualiLoop gives it, here)')
|
|
1877
|
+
.action(run(async ({ client, out, project, opts }, id) => {
|
|
1878
|
+
const reportId = intArg(id);
|
|
1879
|
+
const found = await client.action('get_report', { project, report: reportId });
|
|
1880
|
+
if (found.status !== 'ready') {
|
|
1881
|
+
throw new ApiError(`Report ${found.id} is ${found.status}, not ready. ${found.next_step ?? ''}`.trim(), 409, EXIT.usage);
|
|
1882
|
+
}
|
|
1883
|
+
const format = DOWNLOADS[String(opts.format)];
|
|
1884
|
+
const file = await client.download(`/v1/reports/${found.id}/${format.path}`);
|
|
1885
|
+
const target = opts.out;
|
|
1886
|
+
if (target === '-') {
|
|
1887
|
+
process.stdout.write(file.data);
|
|
1888
|
+
return;
|
|
1889
|
+
}
|
|
1890
|
+
const where = resolvePath(target || basename(file.filename || `qualiloop-report-${found.id}.${format.extension}`));
|
|
1891
|
+
writeFileSync(where, file.data);
|
|
1892
|
+
out.result({ id: found.id, format: opts.format, file: where, bytes: file.data.length }, () => `Saved ${where}`);
|
|
1893
|
+
}));
|
|
1894
|
+
const gateRunRender = (result) => [
|
|
1895
|
+
fields([
|
|
1896
|
+
['Gate run', `#${result.gate_run_number ?? result.org_number} ${result.gate ?? result.release_gate_name ?? ''}`],
|
|
1897
|
+
['Status', result.ended ? `${result.status} (${result.ended === 'timed_out' ? 'past its CI time limit' : 'cancelled'})` : result.status],
|
|
1898
|
+
['Decision', result.decision],
|
|
1899
|
+
['Passing', `${result.pass_percentage ?? 0}% (${result.required_pass_percentage}% required)`],
|
|
1900
|
+
['Tests', `${result.completed_tests ?? 0}/${result.total_tests ?? 0} done`],
|
|
1901
|
+
]),
|
|
1902
|
+
...(Array.isArray(result.tests)
|
|
1903
|
+
? ['', table(result.tests, [['verdict', 'Verdict'], ['test', 'Test', 45], ['run_number', 'Run'], ['problems', 'Problems']])]
|
|
1904
|
+
: []),
|
|
1905
|
+
...(Array.isArray(result.items)
|
|
1906
|
+
? ['', table(result.items, [['verdict', 'Verdict'], ['scheduled_test_name', 'Test', 45], ['test_run_number', 'Run'], ['violation_count', 'Problems']])]
|
|
1907
|
+
: []),
|
|
1908
|
+
].join('\n');
|
|
1909
|
+
const gate = program.command('gate').alias('gates').description('Release gates: a fixed set of tests that decides pass or fail before a deploy.');
|
|
1910
|
+
gate
|
|
1911
|
+
.command('list', { isDefault: true })
|
|
1912
|
+
.description("List the organization's release gates.")
|
|
1913
|
+
.action(run(async ({ client, out }) => {
|
|
1914
|
+
const result = await client.action('list_release_gates');
|
|
1915
|
+
out.result(result, () => table(result.gates, [
|
|
1916
|
+
['id', 'ID'],
|
|
1917
|
+
['name', 'Gate', 40],
|
|
1918
|
+
['tests', 'Tests'],
|
|
1919
|
+
['required_pass_percentage', 'Pass %'],
|
|
1920
|
+
['active', 'Active'],
|
|
1921
|
+
]) || 'No release gates.');
|
|
1922
|
+
}));
|
|
1923
|
+
gate
|
|
1924
|
+
.command('run [gate]')
|
|
1925
|
+
.description("Run a release gate. In CI, set QUALILOOP_GATE_KEY to the gate's deploy key and leave out the gate.")
|
|
1926
|
+
.option('--wait', 'wait for the decision; exit 1 when the gate fails')
|
|
1927
|
+
.option('--ref <ref>', 'what is being released, such as the commit sha')
|
|
1928
|
+
.option('--name <name>', 'a name for this run')
|
|
1929
|
+
.option('--timeout <minutes>', "most minutes to wait (default: the gate's CI time limit)")
|
|
1930
|
+
.action(run(async ({ client, out, opts }, gateRef) => {
|
|
1931
|
+
const key = process.env.QUALILOOP_GATE_KEY;
|
|
1932
|
+
let started;
|
|
1933
|
+
let follow;
|
|
1934
|
+
if (key && !gateRef) {
|
|
1935
|
+
started = await startGateWithKey(client, key, {
|
|
1936
|
+
name: opts.name ?? 'CI run',
|
|
1937
|
+
external_ref: opts.ref,
|
|
1938
|
+
});
|
|
1939
|
+
follow = (minutes) => waitForGateRunWithKey(client, key, Number(started.id), {
|
|
1940
|
+
timeoutMinutes: minutes,
|
|
1941
|
+
onProgress: (message) => out.progress(message),
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
else {
|
|
1945
|
+
if (!gateRef)
|
|
1946
|
+
throw new ApiError('Name the gate, or set QUALILOOP_GATE_KEY in CI.', 400, EXIT.usage);
|
|
1947
|
+
started = await client.action('run_release_gate', {
|
|
1948
|
+
gate: /^\d+$/.test(gateRef) ? Number(gateRef) : gateRef,
|
|
1949
|
+
name: opts.name,
|
|
1950
|
+
external_ref: opts.ref,
|
|
1951
|
+
});
|
|
1952
|
+
follow = (minutes) => waitForGateRun(client, Number(started.gate_run_number), {
|
|
1953
|
+
timeoutMinutes: minutes,
|
|
1954
|
+
onProgress: (message) => out.progress(message),
|
|
1955
|
+
});
|
|
1956
|
+
}
|
|
1957
|
+
const number = started.gate_run_number ?? started.org_number;
|
|
1958
|
+
if (!opts.wait) {
|
|
1959
|
+
out.result(started, () => `Started gate run #${number}. Follow it: qualiloop gate show ${number}`);
|
|
1960
|
+
return EXIT.ok;
|
|
1961
|
+
}
|
|
1962
|
+
const minutes = opts.timeout ? intArg(String(opts.timeout)) : (started.ci_timeout_minutes ?? 60);
|
|
1963
|
+
out.progress(`Started gate run #${number}. Waiting up to ${minutes} minutes for the decision...`);
|
|
1964
|
+
const finished = await follow(minutes);
|
|
1965
|
+
out.result(finished, () => `${gateRunRender(finished)}\n\nGate ${finished.decision === 'pass' ? 'passed' : 'failed'}.`);
|
|
1966
|
+
return finished.decision === 'pass' ? EXIT.ok : EXIT.failed;
|
|
1967
|
+
}));
|
|
1968
|
+
gate
|
|
1969
|
+
.command('runs')
|
|
1970
|
+
.description('Recent gate runs, newest first.')
|
|
1971
|
+
.addOption(limitOption('gate runs', '20', 200))
|
|
1972
|
+
.action(run(async ({ client, out, opts }) => {
|
|
1973
|
+
const result = await client.action('list_gate_runs', {
|
|
1974
|
+
limit: limitOf(opts, 200),
|
|
1975
|
+
});
|
|
1976
|
+
out.result(result, () => listed(table(result.gate_runs, [
|
|
1977
|
+
['gate_run_number', 'Run'],
|
|
1978
|
+
['gate', 'Gate', 30],
|
|
1979
|
+
['name', 'Name', 30],
|
|
1980
|
+
['status', 'Status'],
|
|
1981
|
+
['decision', 'Decision'],
|
|
1982
|
+
['pass_percentage', 'Pass %'],
|
|
1983
|
+
['external_ref', 'Ref', 14],
|
|
1984
|
+
]), result.gate_runs.length, result.total, 'No gate runs yet.'));
|
|
1985
|
+
}));
|
|
1986
|
+
gate
|
|
1987
|
+
.command('show <gate-run>')
|
|
1988
|
+
.description('One gate run: decision and each test.')
|
|
1989
|
+
.action(run(async ({ client, out }, number) => {
|
|
1990
|
+
const result = await client.action('get_gate_run', { gate_run_number: intArg(number) });
|
|
1991
|
+
out.result(result, () => gateRunRender(result));
|
|
1992
|
+
}));
|
|
1993
|
+
gate
|
|
1994
|
+
.command('cancel <gate-run>')
|
|
1995
|
+
.description('End a gate run that is still waiting on its tests. It ends as cancelled, which CI treats as not passed. Its test runs keep going. A run past its CI time limit is ended on its own, as failed.')
|
|
1996
|
+
.action(run(async ({ client, out }, number) => {
|
|
1997
|
+
const result = await client.action('cancel_gate_run', { gate_run_number: intArg(number) });
|
|
1998
|
+
out.result(result, () => `Cancelled gate run #${result.gate_run_number}: CI treats it as not passed.`);
|
|
1999
|
+
}));
|
|
2000
|
+
const packRefs = (values, project, key) => (values ?? []).map((value) => {
|
|
2001
|
+
const at = value.lastIndexOf(':');
|
|
2002
|
+
const owner = at >= 0 ? value.slice(0, at) : project;
|
|
2003
|
+
return { project: owner === undefined ? undefined : idOrName(owner), [key]: intArg(at >= 0 ? value.slice(at + 1) : value) };
|
|
2004
|
+
});
|
|
2005
|
+
const gateRender = (gateRow) => fields([
|
|
2006
|
+
['Gate', `${gateRow.id} ${gateRow.name}`],
|
|
2007
|
+
['Pack', gateRow.pack],
|
|
2008
|
+
['Pass %', gateRow.required_pass_percentage],
|
|
2009
|
+
['CI time limit', `${gateRow.ci_timeout_minutes} minutes`],
|
|
2010
|
+
['Active', gateRow.active],
|
|
2011
|
+
]);
|
|
2012
|
+
const packRender = (pack) => [
|
|
2013
|
+
fields([
|
|
2014
|
+
['Pack', `${pack.id} ${pack.name}`],
|
|
2015
|
+
['Description', pack.description],
|
|
2016
|
+
['Gates', Array.isArray(pack.gates) && pack.gates.length ? pack.gates.join(', ') : 'none'],
|
|
2017
|
+
]),
|
|
2018
|
+
'',
|
|
2019
|
+
table(pack.tests, [
|
|
2020
|
+
['kind', 'Kind'],
|
|
2021
|
+
['id', 'ID'],
|
|
2022
|
+
['name', 'Test', 45],
|
|
2023
|
+
['project_number', 'Project'],
|
|
2024
|
+
]),
|
|
2025
|
+
].join('\n');
|
|
2026
|
+
gate
|
|
2027
|
+
.command('create <name>')
|
|
2028
|
+
.description('Create a release gate for a pack of tests.')
|
|
2029
|
+
.requiredOption('--pack <pack>', 'the pack it runs (id or name, see qualiloop gate packs)')
|
|
2030
|
+
.option('--pass-percent <n>', 'the share of tests that must pass', '95')
|
|
2031
|
+
.option('--timeout <minutes>', 'how long CI waits for a run before it fails', '60')
|
|
2032
|
+
.option('--off', 'create it turned off: CI calls are refused')
|
|
2033
|
+
.action(run(async ({ client, out, opts }, name) => {
|
|
2034
|
+
const result = await client.action('create_release_gate', {
|
|
2035
|
+
name,
|
|
2036
|
+
pack: idOrName(String(opts.pack)),
|
|
2037
|
+
required_pass_percentage: intArg(String(opts.passPercent)),
|
|
2038
|
+
ci_timeout_minutes: intArg(String(opts.timeout)),
|
|
2039
|
+
active: !opts.off,
|
|
2040
|
+
});
|
|
2041
|
+
out.result(result, () => `${gateRender(result.gate)}\n\n${result.next_step ?? ''}`.trimEnd());
|
|
2042
|
+
}));
|
|
2043
|
+
gate
|
|
2044
|
+
.command('edit <gate>')
|
|
2045
|
+
.description('Change a release gate; only what you give changes.')
|
|
2046
|
+
.option('--name <name>', 'a new name')
|
|
2047
|
+
.option('--pack <pack>', 'run this pack instead (id or name)')
|
|
2048
|
+
.option('--pass-percent <n>', 'the share of tests that must pass')
|
|
2049
|
+
.option('--timeout <minutes>', 'how long CI waits for a run before it fails')
|
|
2050
|
+
.addOption(new Option('--on', 'turn it on').conflicts('off'))
|
|
2051
|
+
.option('--off', 'turn it off: CI calls are refused')
|
|
2052
|
+
.action(run(async ({ client, out, opts }, gateRef) => {
|
|
2053
|
+
const result = await client.action('update_release_gate', {
|
|
2054
|
+
gate: idOrName(gateRef),
|
|
2055
|
+
name: opts.name,
|
|
2056
|
+
pack: opts.pack === undefined ? undefined : idOrName(String(opts.pack)),
|
|
2057
|
+
required_pass_percentage: opts.passPercent === undefined ? undefined : intArg(String(opts.passPercent)),
|
|
2058
|
+
ci_timeout_minutes: opts.timeout === undefined ? undefined : intArg(String(opts.timeout)),
|
|
2059
|
+
active: opts.on ? true : opts.off ? false : undefined,
|
|
2060
|
+
});
|
|
2061
|
+
out.result(result, () => `${result.changes.join('\n')}\n\n${gateRender(result.gate)}`);
|
|
2062
|
+
}));
|
|
2063
|
+
gate
|
|
2064
|
+
.command('delete <gate>')
|
|
2065
|
+
.description("Delete a release gate and its deploy tokens. Its pack and its past runs stay.")
|
|
2066
|
+
.option('--yes', 'delete without asking')
|
|
2067
|
+
.action(run(async ({ client, out, opts }, gateRef) => {
|
|
2068
|
+
if (!opts.yes) {
|
|
2069
|
+
if (!(await confirm(`Delete release gate ${gateRef}? CI jobs that call it will be refused.`))) {
|
|
2070
|
+
out.result({ deleted: false, gate: gateRef }, () => 'Not deleted.');
|
|
2071
|
+
return EXIT.ok;
|
|
2072
|
+
}
|
|
2073
|
+
}
|
|
2074
|
+
const result = await client.action('delete_release_gate', { gate: idOrName(gateRef) });
|
|
2075
|
+
out.result(result, () => `Deleted release gate ${result.id} ${result.name}. Its ${result.runs_kept} past runs stay.`);
|
|
2076
|
+
}));
|
|
2077
|
+
gate
|
|
2078
|
+
.command('history <pack>')
|
|
2079
|
+
.description("A pack's gate runs, newest first, with each test's verdict in each run.")
|
|
2080
|
+
.addOption(limitOption('gate runs', '10', 100))
|
|
2081
|
+
.action(run(async ({ client, out, opts }, packRef) => {
|
|
2082
|
+
const result = await client.action('get_pack_history', {
|
|
2083
|
+
pack: idOrName(packRef),
|
|
2084
|
+
limit: limitOf(opts, 100),
|
|
2085
|
+
});
|
|
2086
|
+
out.result(result, () => {
|
|
2087
|
+
if (!result.gate_runs.length)
|
|
2088
|
+
return `Pack ${result.pack} has no gate runs yet.`;
|
|
2089
|
+
const runs = result.gate_runs;
|
|
2090
|
+
const names = [];
|
|
2091
|
+
for (const gateRun of runs)
|
|
2092
|
+
for (const item of gateRun.tests ?? []) {
|
|
2093
|
+
const label = `${item.test ?? '(deleted)'}${item.project_number ? ` (#${item.project_number})` : ''}`;
|
|
2094
|
+
if (!names.includes(label))
|
|
2095
|
+
names.push(label);
|
|
2096
|
+
}
|
|
2097
|
+
const rows = names.map((label) => {
|
|
2098
|
+
const row = { test: label };
|
|
2099
|
+
for (const gateRun of runs) {
|
|
2100
|
+
const item = (gateRun.tests ?? []).find((test) => `${test.test ?? '(deleted)'}${test.project_number ? ` (#${test.project_number})` : ''}` === label);
|
|
2101
|
+
row[`run${gateRun.gate_run_number}`] = item ? (item.verdict ?? item.status) : '';
|
|
2102
|
+
}
|
|
2103
|
+
return row;
|
|
2104
|
+
});
|
|
2105
|
+
const decisions = { test: 'Decision' };
|
|
2106
|
+
for (const gateRun of runs)
|
|
2107
|
+
decisions[`run${gateRun.gate_run_number}`] = gateRun.decision ?? gateRun.status;
|
|
2108
|
+
const columns = [
|
|
2109
|
+
['test', 'Test', 40],
|
|
2110
|
+
...runs.map((gateRun) => [`run${gateRun.gate_run_number}`, `#${gateRun.gate_run_number}`]),
|
|
2111
|
+
];
|
|
2112
|
+
return listed(table([...rows, decisions], columns), runs.length, result.total, '');
|
|
2113
|
+
});
|
|
2114
|
+
}));
|
|
2115
|
+
gate
|
|
2116
|
+
.command('ci-snippet <gate>')
|
|
2117
|
+
.description("Print the shell script that runs a gate from CI. It reads the gate's deploy token from $QUALILOOP_RELEASE_GATE_TOKEN; create the token in the app.")
|
|
2118
|
+
.addOption(new Option('--format <format>', 'shell script, GitHub Actions step, or the qualiloop CLI').choices(['shell', 'github', 'cli']).default('shell'))
|
|
2119
|
+
.action(run(async ({ client, out, opts }, gateRef) => {
|
|
2120
|
+
const { gates } = await client.action('list_release_gates');
|
|
2121
|
+
const wanted = gateRef.trim().toLowerCase();
|
|
2122
|
+
const exact = gates.filter((row) => String(row.id) === gateRef.trim() || String(row.name).toLowerCase() === wanted);
|
|
2123
|
+
const found = exact.length ? exact : gates.filter((row) => String(row.name).toLowerCase().includes(wanted));
|
|
2124
|
+
if (found.length !== 1) {
|
|
2125
|
+
const names = found.map((row) => `${row.id} ${row.name}`).join(', ');
|
|
2126
|
+
throw new ApiError(found.length ? `'${gateRef}' matches several gates: ${names}. Use the id.` : `No release gate '${gateRef}'. \`qualiloop gates\` lists them.`, found.length ? 400 : 404, found.length ? EXIT.usage : EXIT.notFound);
|
|
2127
|
+
}
|
|
2128
|
+
const chosen = found[0];
|
|
2129
|
+
const script = gateCiScript(client.url, Number(chosen.id));
|
|
2130
|
+
const format = String(opts.format);
|
|
2131
|
+
const text = format === 'github'
|
|
2132
|
+
? gateGithubStep(script)
|
|
2133
|
+
: format === 'cli'
|
|
2134
|
+
? gateCliStep(client.url)
|
|
2135
|
+
: script;
|
|
2136
|
+
out.result({ gate: chosen.name, id: chosen.id, format, script: text, ci_timeout_minutes: chosen.ci_timeout_minutes }, () => text);
|
|
2137
|
+
}));
|
|
2138
|
+
const packCommand = gate.command('pack').alias('packs').description('Release gate packs: the set of tests a gate runs.');
|
|
2139
|
+
packCommand
|
|
2140
|
+
.command('list', { isDefault: true })
|
|
2141
|
+
.description("List the organization's packs and their tests.")
|
|
2142
|
+
.action(run(async ({ client, out }) => {
|
|
2143
|
+
const result = await client.action('list_gate_packs');
|
|
2144
|
+
out.result(result, () => result.packs.length
|
|
2145
|
+
? table(result.packs.map((pack) => ({ ...pack, gates: Array.isArray(pack.gates) ? pack.gates.join(', ') : '' })), [
|
|
2146
|
+
['id', 'ID'],
|
|
2147
|
+
['name', 'Pack', 40],
|
|
2148
|
+
['test_count', 'Tests'],
|
|
2149
|
+
['gates', 'Gates', 40],
|
|
2150
|
+
])
|
|
2151
|
+
: 'No packs yet. Make one: qualiloop gate pack create <name> --test <project>:<id>');
|
|
2152
|
+
}));
|
|
2153
|
+
packCommand
|
|
2154
|
+
.command('create <name>')
|
|
2155
|
+
.description('Create a pack from saved tests and schedules of any project.')
|
|
2156
|
+
.option('--test <project:id>', 'a saved test, as <project>:<test id>, or a bare id in the -p project (repeat)', repeat)
|
|
2157
|
+
.option('--schedule <project:id>', 'a schedule, as <project>:<schedule id> (repeat)', repeat)
|
|
2158
|
+
.option('--description <text>', 'what the pack is for')
|
|
2159
|
+
.action(run(async ({ client, out, project, opts }, name) => {
|
|
2160
|
+
const result = await client.action('create_gate_pack', {
|
|
2161
|
+
name,
|
|
2162
|
+
description: opts.description,
|
|
2163
|
+
tests: packRefs(opts.test, project, 'test'),
|
|
2164
|
+
schedules: packRefs(opts.schedule, project, 'schedule'),
|
|
2165
|
+
});
|
|
2166
|
+
out.result(result, () => `${packRender(result.pack)}\n\nMake a gate for it: qualiloop gate create <name> --pack ${result.pack.id}`);
|
|
2167
|
+
}));
|
|
2168
|
+
packCommand
|
|
2169
|
+
.command('edit <pack>')
|
|
2170
|
+
.description('Change a pack. --test and --schedule each replace that kind of test as a whole; leave one out to keep it.')
|
|
2171
|
+
.option('--name <name>', 'a new name')
|
|
2172
|
+
.option('--description <text>', 'a new description')
|
|
2173
|
+
.option('--test <project:id>', 'a saved test, as <project>:<test id> (repeat)', repeat)
|
|
2174
|
+
.option('--schedule <project:id>', 'a schedule, as <project>:<schedule id> (repeat)', repeat)
|
|
2175
|
+
.option('--no-tests', 'remove every saved test')
|
|
2176
|
+
.option('--no-schedules', 'remove every schedule')
|
|
2177
|
+
.action(run(async ({ client, out, project, opts }, packRef) => {
|
|
2178
|
+
const listOf = (given, keep, key) => keep === false ? [] : given === undefined ? undefined : packRefs(given, project, key);
|
|
2179
|
+
const result = await client.action('update_gate_pack', {
|
|
2180
|
+
pack: idOrName(packRef),
|
|
2181
|
+
name: opts.name,
|
|
2182
|
+
description: opts.description,
|
|
2183
|
+
tests: listOf(opts.test, opts.tests, 'test'),
|
|
2184
|
+
schedules: listOf(opts.schedule, opts.schedules, 'schedule'),
|
|
2185
|
+
});
|
|
2186
|
+
out.result(result, () => `${result.changes.join('\n')}\n\n${packRender(result.pack)}`);
|
|
2187
|
+
}));
|
|
2188
|
+
packCommand
|
|
2189
|
+
.command('delete <pack>')
|
|
2190
|
+
.description('Delete a pack. Its tests and past gate runs stay. A pack a gate still runs is not deleted.')
|
|
2191
|
+
.option('--yes', 'delete without asking')
|
|
2192
|
+
.action(run(async ({ client, out, opts }, packRef) => {
|
|
2193
|
+
if (!opts.yes) {
|
|
2194
|
+
if (!(await confirm(`Delete pack ${packRef}?`))) {
|
|
2195
|
+
out.result({ deleted: false, pack: packRef }, () => 'Not deleted.');
|
|
2196
|
+
return EXIT.ok;
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
const result = await client.action('delete_gate_pack', { pack: idOrName(packRef) });
|
|
2200
|
+
out.result(result, () => `Deleted pack ${result.id} ${result.name}.`);
|
|
2201
|
+
}));
|
|
2202
|
+
const gateCiScript = (url, gateId) => {
|
|
2203
|
+
const api = `${url.replace(/\/+$/, '')}/v1`;
|
|
2204
|
+
return `RESPONSE=$(curl -s -X POST "${api}/release-gates/hooks/${gateId}/runs" \\
|
|
2205
|
+
-H "Authorization: Bearer $QUALILOOP_RELEASE_GATE_TOKEN" \\
|
|
2206
|
+
-H "Content-Type: application/json" \\
|
|
2207
|
+
-d '{"name":"Deploy run","external_ref":"'"$GIT_SHA"'"}')
|
|
2208
|
+
RUN_ID=$(echo "$RESPONSE" | jq -r '.id // empty')
|
|
2209
|
+
if [ -z "$RUN_ID" ]; then
|
|
2210
|
+
echo "QualiLoop did not start the release gate: $RESPONSE" >&2
|
|
2211
|
+
exit 1
|
|
2212
|
+
fi
|
|
2213
|
+
LIMIT_MINUTES=$(echo "$RESPONSE" | jq -r '.ci_timeout_minutes // 60')
|
|
2214
|
+
DEADLINE=$((SECONDS + LIMIT_MINUTES * 60))
|
|
2215
|
+
|
|
2216
|
+
while true; do
|
|
2217
|
+
RESULT=$(curl -s "${api}/release-gates/hooks/runs/$RUN_ID" \\
|
|
2218
|
+
-H "Authorization: Bearer $QUALILOOP_RELEASE_GATE_TOKEN")
|
|
2219
|
+
STATUS=$(echo "$RESULT" | jq -r '.status')
|
|
2220
|
+
DECISION=$(echo "$RESULT" | jq -r '.decision // empty')
|
|
2221
|
+
if [ "$STATUS" = "completed" ]; then
|
|
2222
|
+
PASSED=$(echo "$RESULT" | jq -r '.pass_percentage')
|
|
2223
|
+
NEEDED=$(echo "$RESULT" | jq -r '.required_pass_percentage')
|
|
2224
|
+
echo "QualiLoop release gate: $DECISION, $PASSED% passed, $NEEDED% needed."
|
|
2225
|
+
[ "$DECISION" = "pass" ] && exit 0 || exit 1
|
|
2226
|
+
fi
|
|
2227
|
+
if [ "$SECONDS" -ge "$DEADLINE" ]; then
|
|
2228
|
+
echo "QualiLoop release gate run $RUN_ID did not finish within $LIMIT_MINUTES minutes. Failing the deploy." >&2
|
|
2229
|
+
exit 1
|
|
2230
|
+
fi
|
|
2231
|
+
sleep 10
|
|
2232
|
+
done`;
|
|
2233
|
+
};
|
|
2234
|
+
const gateGithubStep = (script) => `- name: Run QualiLoop release gate
|
|
2235
|
+
env:
|
|
2236
|
+
QUALILOOP_RELEASE_GATE_TOKEN: \${{ secrets.QUALILOOP_RELEASE_GATE_TOKEN }}
|
|
2237
|
+
GIT_SHA: \${{ github.sha }}
|
|
2238
|
+
run: |
|
|
2239
|
+
${script
|
|
2240
|
+
.split('\n')
|
|
2241
|
+
.map((line) => (line ? ` ${line}` : ''))
|
|
2242
|
+
.join('\n')}`;
|
|
2243
|
+
const gateCliStep = (url) => `- name: Run QualiLoop release gate
|
|
2244
|
+
run: npx qualiloop gate run --wait --ref "$GITHUB_SHA"
|
|
2245
|
+
env:
|
|
2246
|
+
QUALILOOP_URL: ${url.replace(/\/+$/, '')}
|
|
2247
|
+
QUALILOOP_GATE_KEY: \${{ secrets.QUALILOOP_RELEASE_GATE_TOKEN }}`;
|
|
2248
|
+
const generate = program
|
|
2249
|
+
.command('generate')
|
|
2250
|
+
.description('Have QualiLoop write tests from one prompt.')
|
|
2251
|
+
.argument('[prompt...]', 'what to test, in plain words')
|
|
2252
|
+
.option('--suite <suite>', 'add the tests to this suite (id or name)')
|
|
2253
|
+
.option('--new-suite <name>', 'make a new suite for them')
|
|
2254
|
+
.option('--max <n>', 'most tests to write, up to 300')
|
|
2255
|
+
.option('--wait', 'wait until the tests are saved')
|
|
2256
|
+
.option('--timeout <minutes>', 'most minutes to wait', '15')
|
|
2257
|
+
.action(run(async ({ client, out, project, opts }, words = []) => {
|
|
2258
|
+
if (!words.length)
|
|
2259
|
+
throw new ApiError('Say what to test: qualiloop generate "refund requests"', 400, EXIT.usage);
|
|
2260
|
+
const started = await startGeneration(client, {
|
|
2261
|
+
project,
|
|
2262
|
+
prompt: words.join(' '),
|
|
2263
|
+
suite: opts.suite,
|
|
2264
|
+
newSuite: opts.newSuite,
|
|
2265
|
+
max: opts.max ? intArg(String(opts.max)) : undefined,
|
|
2266
|
+
});
|
|
2267
|
+
if (!opts.wait) {
|
|
2268
|
+
out.result(started, () => `Generating tests (generation ${started.id}). Follow it: qualiloop generate status ${started.id}`);
|
|
2269
|
+
return EXIT.ok;
|
|
2270
|
+
}
|
|
2271
|
+
const finished = await waitForGeneration(client, Number(started.id), {
|
|
2272
|
+
timeoutMinutes: intArg(String(opts.timeout)),
|
|
2273
|
+
onProgress: (message) => out.progress(message),
|
|
2274
|
+
});
|
|
2275
|
+
const saved = finished.saved_test_ids ?? [];
|
|
2276
|
+
out.result(finished, () => finished.status === 'completed'
|
|
2277
|
+
? `Saved ${saved.length} test(s): ${saved.join(', ') || 'none'}${finished.suite_name ? ` in ${finished.suite_name}` : ''}.
|
|
2278
|
+
Run them: qualiloop run ${saved.join(' ')}`
|
|
2279
|
+
: `Generation ${finished.status}${finished.error_message ? `: ${finished.error_message}` : ''}.`);
|
|
2280
|
+
return finished.status === 'completed' ? EXIT.ok : EXIT.failed;
|
|
2281
|
+
}));
|
|
2282
|
+
generate
|
|
2283
|
+
.command('status <id>')
|
|
2284
|
+
.description('Where a generation stands.')
|
|
2285
|
+
.action(run(async ({ client, out }, id) => {
|
|
2286
|
+
const result = await getGeneration(client, intArg(id));
|
|
2287
|
+
out.result(result, () => fields([
|
|
2288
|
+
['Generation', `${result.id} ${result.status}`],
|
|
2289
|
+
['Step', result.step_label ?? result.step],
|
|
2290
|
+
['Written', `${result.written ?? 0}/${result.planned ?? '-'}`],
|
|
2291
|
+
['Saved tests', result.saved_test_ids],
|
|
2292
|
+
['Suite', result.suite_name],
|
|
2293
|
+
['Error', result.error_message],
|
|
2294
|
+
]));
|
|
2295
|
+
}));
|
|
2296
|
+
generate
|
|
2297
|
+
.command('cancel <id>')
|
|
2298
|
+
.description('Stop a generation that is still running. Nothing is saved.')
|
|
2299
|
+
.action(run(async ({ client, out }, id) => {
|
|
2300
|
+
const result = await cancelGeneration(client, intArg(id));
|
|
2301
|
+
out.result(result, () => result.status === 'cancelled'
|
|
2302
|
+
? `Generation ${result.id} is cancelled. Nothing was saved.`
|
|
2303
|
+
: result.finished
|
|
2304
|
+
? `Generation ${result.id} had already finished (${result.status}); nothing to cancel.`
|
|
2305
|
+
: `Cancelling generation ${result.id}. It stops at its next step and saves nothing: qualiloop generate status ${result.id}`);
|
|
2306
|
+
}));
|
|
2307
|
+
generate
|
|
2308
|
+
.command('list')
|
|
2309
|
+
.description('The latest generations of the project, newest first.')
|
|
2310
|
+
.option('--everyone', "everyone's generations, not only yours")
|
|
2311
|
+
.addOption(limitOption('generations', '10', 50))
|
|
2312
|
+
.action(run(async ({ client, out, project, opts }) => {
|
|
2313
|
+
const result = await client.action('list_generations', {
|
|
2314
|
+
project,
|
|
2315
|
+
mine: opts.everyone ? false : undefined,
|
|
2316
|
+
limit: limitOf(opts, 50),
|
|
2317
|
+
});
|
|
2318
|
+
out.result(result, () => table(result.generations, [
|
|
2319
|
+
['id', 'Id'],
|
|
2320
|
+
['status', 'Status'],
|
|
2321
|
+
['saved_tests', 'Saved'],
|
|
2322
|
+
['prompt', 'Prompt', 60],
|
|
2323
|
+
['created_at', 'Started'],
|
|
2324
|
+
]) || 'No generations yet.');
|
|
2325
|
+
}));
|
|
2326
|
+
program
|
|
2327
|
+
.command('export [project]')
|
|
2328
|
+
.description("Export the project's corrected pairs (turns with a saved correction) to a file, in one of the Export page's formats.")
|
|
2329
|
+
.addOption(new Option('--format <format>', 'the file format')
|
|
2330
|
+
.choices(EXPORT_FORMATS.map((item) => item.id))
|
|
2331
|
+
.default('openai-chat-jsonl'))
|
|
2332
|
+
.option('--from <date>', 'first day, YYYY-MM-DD (default 30 days ago)')
|
|
2333
|
+
.option('--to <date>', 'last day, YYYY-MM-DD (default today)')
|
|
2334
|
+
.option('--out <file>', 'the file to write (default qualiloop-<project>-<format>-<from>-to-<to>.<ext>)')
|
|
2335
|
+
.action(run(async ({ client, out, project, opts }, given) => {
|
|
2336
|
+
const format = exportFormat(String(opts.format));
|
|
2337
|
+
const from = dateOr(opts.from, 30);
|
|
2338
|
+
const to = dateOr(opts.to, 0);
|
|
2339
|
+
if (from > to)
|
|
2340
|
+
throw new ApiError('--from must be on or before --to.', 400, EXIT.usage);
|
|
2341
|
+
const found = await fetchCorrectedPairs(client, given ?? project, from, to);
|
|
2342
|
+
if (!found.items.length) {
|
|
2343
|
+
out.result({ project: found.number, written: false, items: 0 }, () => `No corrected pairs in project #${found.number} ${found.name} from ${from} to ${to}.`);
|
|
2344
|
+
return EXIT.ok;
|
|
2345
|
+
}
|
|
2346
|
+
const file = opts.out ?? `qualiloop-${found.number}-${format.id}-${from}-to-${to}.${format.extension}`;
|
|
2347
|
+
writeFileSync(file, format.render(found.items), 'utf8');
|
|
2348
|
+
out.result({ project: found.number, written: true, file, format: format.id, items: found.items.length }, () => `Wrote ${found.items.length} corrected pairs to ${file}.`);
|
|
2349
|
+
}));
|
|
2350
|
+
const connectCommand = program
|
|
2351
|
+
.command('connect')
|
|
2352
|
+
.argument('[project]', 'the project: its number or name')
|
|
2353
|
+
.description('Connect the agent in this codebase to a project. With no subcommand: sign in if needed, use the project named (or create one when you have none), make it the default, write its key into .env, and print the steps to follow.')
|
|
2354
|
+
.addHelpText('after', `
|
|
2355
|
+
Start here:
|
|
2356
|
+
npx qualiloop connect 12 run in the agent's folder: signs in through the
|
|
2357
|
+
browser if needed, makes project 12 the default,
|
|
2358
|
+
writes the project key and traces address into
|
|
2359
|
+
.env, and prints the steps a coding agent follows
|
|
2360
|
+
qualiloop connect guide the steps alone
|
|
2361
|
+
|
|
2362
|
+
Project:
|
|
2363
|
+
With QUALILOOP_SETUP_TOKEN set, every command uses that token and its own
|
|
2364
|
+
project (-p only for a project the token created). Otherwise they use your
|
|
2365
|
+
sign-in, on the project named by the argument, -p, QUALILOOP_PROJECT or
|
|
2366
|
+
qualiloop projects use; with none named they stop. qualiloop connect alone
|
|
2367
|
+
creates a project only when you have none. Each command prints the project
|
|
2368
|
+
it acted on.
|
|
2369
|
+
`)
|
|
2370
|
+
.action(run(async (ctx, given) => {
|
|
2371
|
+
const { client, out } = ctx;
|
|
2372
|
+
if (!process.env.QUALILOOP_SETUP_TOKEN && !client.isSignedIn()) {
|
|
2373
|
+
out.progress(signedInAs(await browserLogin(client, out, true)));
|
|
2374
|
+
}
|
|
2375
|
+
const result = await connect.start(client, {
|
|
2376
|
+
project: given ?? ctx.opts.project,
|
|
2377
|
+
dir: process.cwd(),
|
|
2378
|
+
file: '.env',
|
|
2379
|
+
ask: (projects) => [
|
|
2380
|
+
`Name the project to connect: ${invocation()} connect <number>`,
|
|
2381
|
+
...projects.map((item) => ` #${item.number} ${item.name}`),
|
|
2382
|
+
].join('\n'),
|
|
2383
|
+
});
|
|
2384
|
+
let guide = null;
|
|
2385
|
+
let guideError = null;
|
|
2386
|
+
try {
|
|
2387
|
+
guide = await connect.skill(client);
|
|
2388
|
+
}
|
|
2389
|
+
catch (error) {
|
|
2390
|
+
guideError = `${error instanceof Error ? error.message : String(error)} Print the steps later with: ${invocation()} connect guide`;
|
|
2391
|
+
}
|
|
2392
|
+
const install = viaNpx() ? 'To use qualiloop directly: npm install -g qualiloop' : null;
|
|
2393
|
+
const mcp = viaNpx()
|
|
2394
|
+
? 'Using Claude Desktop, Cursor or VS Code? After installing, run: qualiloop mcp install'
|
|
2395
|
+
: 'Using Claude Desktop, Cursor or VS Code? Run: qualiloop mcp install';
|
|
2396
|
+
out.result({ ...result, guide, guide_error: guideError, install, mcp }, () => [
|
|
2397
|
+
`Project #${result.project.number} ${result.project.name}` +
|
|
2398
|
+
(result.created ? ' (created: you had no project, so it is named after this codebase)' : ''),
|
|
2399
|
+
...(result.default_set ? [`Commands now use project #${result.project.number}.`] : []),
|
|
2400
|
+
[
|
|
2401
|
+
`Wrote ${result.env.written.join(' and ')} to ${result.env.file}.`,
|
|
2402
|
+
connect.gitNote(result.env.file, result.env.git_ignored),
|
|
2403
|
+
]
|
|
2404
|
+
.filter(Boolean)
|
|
2405
|
+
.join(' '),
|
|
2406
|
+
'',
|
|
2407
|
+
guide
|
|
2408
|
+
? `Next, follow these steps.\n\n${guide.text.trimEnd()}\n\n(From ${guide.url}. The code for each step: ${guide.reference_url})`
|
|
2409
|
+
: String(guideError),
|
|
2410
|
+
...(install ? ['', install] : []),
|
|
2411
|
+
'',
|
|
2412
|
+
mcp,
|
|
2413
|
+
].join('\n'));
|
|
2414
|
+
}));
|
|
2415
|
+
const connectProject = (ctx) => ctx.opts.project;
|
|
2416
|
+
const actedOn = (result, text) => result.project ? `Project #${result.project.number} ${result.project.name}\n${text}` : text;
|
|
2417
|
+
connectCommand
|
|
2418
|
+
.command('guide')
|
|
2419
|
+
.description('Print the connect skill from QualiLoop (/connect/SKILL.md): the steps a coding agent follows.')
|
|
2420
|
+
.action(run(async ({ client, out }) => {
|
|
2421
|
+
const result = await connect.skill(client);
|
|
2422
|
+
out.result(result, () => `${result.text.trimEnd()}\n\n(From ${result.url}. The code for each step: ${result.reference_url})`);
|
|
2423
|
+
}));
|
|
2424
|
+
connectCommand
|
|
2425
|
+
.command('info')
|
|
2426
|
+
.description('What the agent needs: request contract, traces address, saved endpoint (key masked).')
|
|
2427
|
+
.action(run(async (ctx) => {
|
|
2428
|
+
const result = await connect.info(ctx.client, { project: connectProject(ctx) });
|
|
2429
|
+
ctx.out.result(result, () => [
|
|
2430
|
+
fields([
|
|
2431
|
+
['Project', `#${result.project.number} ${result.project.name}`],
|
|
2432
|
+
['Traces address', result.tracing.traces_url],
|
|
2433
|
+
['Project key', `${result.tracing.project_key} (write it with: qualiloop connect env)`],
|
|
2434
|
+
['Saved connection', connect.targetAddress(result.target)],
|
|
2435
|
+
...(result.target ? [['Agent name', result.target.name]] : []),
|
|
2436
|
+
['Scoring with traces', !result.project.traces_disabled],
|
|
2437
|
+
['Live traffic', result.project.live_data_enabled],
|
|
2438
|
+
['QualiLoop calls from', result.outbound_addresses],
|
|
2439
|
+
]),
|
|
2440
|
+
'',
|
|
2441
|
+
'Request contract:',
|
|
2442
|
+
JSON.stringify(result.request_contract, null, 2),
|
|
2443
|
+
].join('\n'));
|
|
2444
|
+
}));
|
|
2445
|
+
connectCommand
|
|
2446
|
+
.command('projects')
|
|
2447
|
+
.description('The projects you can connect agents to.')
|
|
2448
|
+
.action(run(async ({ client, out }) => {
|
|
2449
|
+
const result = await connect.projects(client);
|
|
2450
|
+
out.result(result, () => table(result.projects, [
|
|
2451
|
+
['number', '#'],
|
|
2452
|
+
['agent', 'Agent', 40],
|
|
2453
|
+
['environment', 'Environment'],
|
|
2454
|
+
]));
|
|
2455
|
+
}));
|
|
2456
|
+
connectCommand
|
|
2457
|
+
.command('env')
|
|
2458
|
+
.description("Write the project key and traces address into an env file (values not printed).")
|
|
2459
|
+
.option('--file <path>', 'the env file', '.env')
|
|
2460
|
+
.option('--suffix <name>', 'for a second agent: TRIAGE gives QUALILOOP_PROJECT_KEY_TRIAGE')
|
|
2461
|
+
.action(run(async (ctx) => {
|
|
2462
|
+
const result = await connect.writeEnv(ctx.client, {
|
|
2463
|
+
project: connectProject(ctx),
|
|
2464
|
+
file: String(ctx.opts.file),
|
|
2465
|
+
suffix: ctx.opts.suffix,
|
|
2466
|
+
});
|
|
2467
|
+
ctx.out.result(result, () => actedOn(result, [`Wrote ${result.written.join(' and ')} to ${result.file}.`, connect.gitNote(result.file, result.git_ignored)]
|
|
2468
|
+
.filter(Boolean)
|
|
2469
|
+
.join(' ')));
|
|
2470
|
+
}));
|
|
2471
|
+
connectCommand
|
|
2472
|
+
.command('create-project <name>')
|
|
2473
|
+
.description('Create a project for another agent or environment (admins).')
|
|
2474
|
+
.addOption(new Option('--environment <env>').choices(['local', 'dev', 'staging', 'prod']))
|
|
2475
|
+
.option('--description <text>')
|
|
2476
|
+
.action(run(async (ctx, name) => {
|
|
2477
|
+
const result = await connect.createProject(ctx.client, {
|
|
2478
|
+
name,
|
|
2479
|
+
environment: ctx.opts.environment,
|
|
2480
|
+
description: ctx.opts.description,
|
|
2481
|
+
});
|
|
2482
|
+
ctx.out.result(result, () => `Created project #${result.project.number} ${result.project.name}.`);
|
|
2483
|
+
}));
|
|
2484
|
+
connectCommand
|
|
2485
|
+
.command('rename')
|
|
2486
|
+
.description("Rename the project, describe it, name its environment, or name the agent on the saved endpoint.")
|
|
2487
|
+
.option('--name <name>')
|
|
2488
|
+
.option('--description <text>')
|
|
2489
|
+
.addOption(new Option('--environment <env>').choices(['local', 'dev', 'staging', 'prod']))
|
|
2490
|
+
.option('--agent-name <name>', "the agent's name on the saved endpoint, as the connection settings show it")
|
|
2491
|
+
.action(run(async (ctx) => {
|
|
2492
|
+
const options = { project: connectProject(ctx) };
|
|
2493
|
+
const project = {
|
|
2494
|
+
name: ctx.opts.name,
|
|
2495
|
+
description: ctx.opts.description,
|
|
2496
|
+
environment: ctx.opts.environment,
|
|
2497
|
+
};
|
|
2498
|
+
const agentName = ctx.opts.agentName;
|
|
2499
|
+
const projectGiven = Object.values(project).some((value) => value !== undefined);
|
|
2500
|
+
if (!projectGiven && agentName === undefined) {
|
|
2501
|
+
throw new ApiError('Give --name, --description, --environment or --agent-name.', 400, EXIT.usage);
|
|
2502
|
+
}
|
|
2503
|
+
const updated = projectGiven ? await connect.updateProject(ctx.client, options, project) : null;
|
|
2504
|
+
const named = agentName !== undefined ? await connect.updateTarget(ctx.client, options, { name: agentName }) : null;
|
|
2505
|
+
const result = {
|
|
2506
|
+
...(updated ?? {}),
|
|
2507
|
+
...(named ? { project: named.project, target: named.target } : {}),
|
|
2508
|
+
};
|
|
2509
|
+
const lines = [
|
|
2510
|
+
...(updated ? ['Project updated.'] : []),
|
|
2511
|
+
...(named ? [`Agent name: ${String(named.target?.name ?? agentName)}.`] : []),
|
|
2512
|
+
];
|
|
2513
|
+
ctx.out.result(result, () => actedOn(result, lines.join('\n')));
|
|
2514
|
+
}));
|
|
2515
|
+
connectCommand
|
|
2516
|
+
.command('target')
|
|
2517
|
+
.description('Save how QualiLoop reaches the agent, from a JSON file (or - for stdin): an endpoint, or mode dify, async_session, browser, elevenlabs or gohighlevel with its block. Secrets come from variables: --auth-header, or <field>_env in a block (elevenlabs.api_key_env, gohighlevel.private_token_env, browser.browserbase_context_id_env, observability.secret_key_env).')
|
|
2518
|
+
.requiredOption('--file <path>', 'the body of PUT /v1/setup/target')
|
|
2519
|
+
.addOption(new Option('--mode <mode>', 'the connection mode; wins over the one in the file').choices([...connect.MODES]))
|
|
2520
|
+
.option('--auth-header <Name=VARIABLE>', 'send header Name with the value of VARIABLE, read from the environment or --env-file')
|
|
2521
|
+
.option('--auth-prefix <prefix>', 'put this before the value, such as "Bearer "')
|
|
2522
|
+
.option('--env-file <path>', 'where to read a VARIABLE when the environment lacks it', '.env')
|
|
2523
|
+
.action(run(async (ctx) => {
|
|
2524
|
+
const body = connect.readJson(String(ctx.opts.file));
|
|
2525
|
+
if (ctx.opts.mode)
|
|
2526
|
+
body.mode = ctx.opts.mode;
|
|
2527
|
+
body.env_file = String(ctx.opts.envFile);
|
|
2528
|
+
if (ctx.opts.authHeader) {
|
|
2529
|
+
const [name, variable] = String(ctx.opts.authHeader).split('=');
|
|
2530
|
+
if (!name || !variable)
|
|
2531
|
+
throw new ApiError('--auth-header takes Name=VARIABLE.', 400, EXIT.usage);
|
|
2532
|
+
body.auth_header_name = name;
|
|
2533
|
+
body.auth_header_env = variable;
|
|
2534
|
+
body.auth_header_prefix = ctx.opts.authPrefix;
|
|
2535
|
+
}
|
|
2536
|
+
const result = await connect.saveTarget(ctx.client, { project: connectProject(ctx) }, body);
|
|
2537
|
+
ctx.out.result(result, () => actedOn(result, `Saved the connection: ${connect.targetAddress(result.target)}.`));
|
|
2538
|
+
}));
|
|
2539
|
+
connectCommand
|
|
2540
|
+
.command('limits')
|
|
2541
|
+
.description('Set how hard QualiLoop drives the saved endpoint: conversations at once, and the seconds one reply may take. With no flags, print the saved values.')
|
|
2542
|
+
.option('--parallel <n>', 'the most conversations at once (0 removes the limit)')
|
|
2543
|
+
.option('--reply-timeout <seconds>', 'the most seconds one reply may take (1 to 600)')
|
|
2544
|
+
.action(run(async (ctx) => {
|
|
2545
|
+
const result = await connect.setLimits(ctx.client, { project: connectProject(ctx) }, {
|
|
2546
|
+
max_parallel_conversations: ctx.opts.parallel !== undefined ? intArg(String(ctx.opts.parallel)) : undefined,
|
|
2547
|
+
reply_timeout_seconds: ctx.opts.replyTimeout !== undefined ? intArg(String(ctx.opts.replyTimeout)) : undefined,
|
|
2548
|
+
});
|
|
2549
|
+
if (!result.target) {
|
|
2550
|
+
ctx.out.result(result, () => actedOn(result, 'No connection is saved for this project yet.'));
|
|
2551
|
+
return;
|
|
2552
|
+
}
|
|
2553
|
+
const target = result.target;
|
|
2554
|
+
const parallel = target.max_parallel_conversations;
|
|
2555
|
+
const timeout = target.reply_timeout_seconds;
|
|
2556
|
+
ctx.out.result(result, () => actedOn(result, `Conversations at once: ${parallel ? String(parallel) : 'no limit'}. ` +
|
|
2557
|
+
`Reply timeout: ${timeout ? `${String(timeout)} seconds` : 'the default'}.`));
|
|
2558
|
+
}));
|
|
2559
|
+
connectCommand
|
|
2560
|
+
.command('knowledge')
|
|
2561
|
+
.alias('context')
|
|
2562
|
+
.description("Fill the agent's system knowledge: its system prompts, tools, documentation and General, from a JSON file.")
|
|
2563
|
+
.requiredOption('--file <path>', 'the body of PUT /v1/setup/knowledge (or - for stdin)')
|
|
2564
|
+
.option('--overwrite', "write General over what is there; only when the user asked for it")
|
|
2565
|
+
.action(run(async (ctx) => {
|
|
2566
|
+
const result = await connect.saveKnowledge(ctx.client, { project: connectProject(ctx) }, connect.readJson(String(ctx.opts.file)), Boolean(ctx.opts.overwrite));
|
|
2567
|
+
ctx.out.result(result, () => actedOn(result, connect.knowledgeRender(result)));
|
|
2568
|
+
}));
|
|
2569
|
+
connectCommand
|
|
2570
|
+
.command('trace-fields', { hidden: true })
|
|
2571
|
+
.option('--file <path>')
|
|
2572
|
+
.action(run(async ({ out }) => {
|
|
2573
|
+
out.result({ status: 'no_longer_needed', detail: connect.TRACE_FIELDS_GONE }, () => connect.TRACE_FIELDS_GONE);
|
|
2574
|
+
}));
|
|
2575
|
+
const limitArg = (value) => (value.toLowerCase() === 'none' ? null : intArg(value));
|
|
2576
|
+
const PERIODS = ['day', 'week', 'month'];
|
|
2577
|
+
connectCommand
|
|
2578
|
+
.command('live <on|off>')
|
|
2579
|
+
.description("Turn the project's live traffic on or off (admins), and optionally how much is stored and scored. It sends real users' data.")
|
|
2580
|
+
.option('--collect-percent <n>', 'share of new live conversations stored, 0 to 100')
|
|
2581
|
+
.option('--scoring <on|off>', 'score stored live conversations')
|
|
2582
|
+
.option('--score-percent <n>', 'share of stored live conversations scored, 0 to 100')
|
|
2583
|
+
.option('--turn-limit <n|none>', 'the most live turns stored per period; none removes the limit')
|
|
2584
|
+
.addOption(new Option('--turn-limit-period <period>').choices(PERIODS))
|
|
2585
|
+
.option('--score-limit <n|none>', 'the most live conversations scored per period; none removes the limit')
|
|
2586
|
+
.addOption(new Option('--score-limit-period <period>').choices(PERIODS))
|
|
2587
|
+
.action(run(async (ctx, state) => {
|
|
2588
|
+
if (!['on', 'off'].includes(state))
|
|
2589
|
+
throw new ApiError('Say on or off.', 400, EXIT.usage);
|
|
2590
|
+
const opts = ctx.opts;
|
|
2591
|
+
const result = await connect.setLive(ctx.client, { project: connectProject(ctx) }, {
|
|
2592
|
+
enabled: state === 'on',
|
|
2593
|
+
collect_percent: opts.collectPercent !== undefined ? intArg(String(opts.collectPercent)) : undefined,
|
|
2594
|
+
scoring_enabled: onOff(opts.scoring, '--scoring'),
|
|
2595
|
+
score_percent: opts.scorePercent !== undefined ? intArg(String(opts.scorePercent)) : undefined,
|
|
2596
|
+
turn_limit: opts.turnLimit !== undefined ? limitArg(String(opts.turnLimit)) : undefined,
|
|
2597
|
+
turn_limit_period: opts.turnLimitPeriod,
|
|
2598
|
+
score_limit: opts.scoreLimit !== undefined ? limitArg(String(opts.scoreLimit)) : undefined,
|
|
2599
|
+
score_limit_period: opts.scoreLimitPeriod,
|
|
2600
|
+
});
|
|
2601
|
+
const limit = (value, period) => value === null || value === undefined ? 'no limit' : `at most ${String(value)} a ${String(period)}`;
|
|
2602
|
+
ctx.out.result(result, () => actedOn(result, [
|
|
2603
|
+
`Live traffic is ${result.live_data_enabled ? 'on' : 'off'}.`,
|
|
2604
|
+
fields([
|
|
2605
|
+
[
|
|
2606
|
+
'Stored',
|
|
2607
|
+
`${String(result.collect_percent)}% of new conversations, turns ${limit(result.turn_limit, result.turn_limit_period)}`,
|
|
2608
|
+
],
|
|
2609
|
+
[
|
|
2610
|
+
'Scored',
|
|
2611
|
+
result.scoring_enabled
|
|
2612
|
+
? `${String(result.score_percent)}% of stored conversations, ${limit(result.score_limit, result.score_limit_period)}`
|
|
2613
|
+
: 'off',
|
|
2614
|
+
],
|
|
2615
|
+
]),
|
|
2616
|
+
].join('\n')));
|
|
2617
|
+
}));
|
|
2618
|
+
connectCommand
|
|
2619
|
+
.command('traces [on|off]')
|
|
2620
|
+
.description("Whether scoring uses traces (on or off, admins), and how long QualiLoop waits for a conversation's traces once its last turn is done.")
|
|
2621
|
+
.option('--delay <seconds>', 'seconds before the first look, 0 to 120')
|
|
2622
|
+
.option('--interval <seconds>', 'seconds between looks, 1 to 60')
|
|
2623
|
+
.option('--max-wait <seconds>', 'seconds after which QualiLoop stops looking, 0 to 600')
|
|
2624
|
+
.action(run(async (ctx, state) => {
|
|
2625
|
+
const opts = ctx.opts;
|
|
2626
|
+
const result = await connect.setTraces(ctx.client, { project: connectProject(ctx) }, {
|
|
2627
|
+
enabled: onOff(state, 'traces'),
|
|
2628
|
+
delay_seconds: opts.delay !== undefined ? intArg(String(opts.delay)) : undefined,
|
|
2629
|
+
interval_seconds: opts.interval !== undefined ? intArg(String(opts.interval)) : undefined,
|
|
2630
|
+
max_wait_seconds: opts.maxWait !== undefined ? intArg(String(opts.maxWait)) : undefined,
|
|
2631
|
+
});
|
|
2632
|
+
const lines = [];
|
|
2633
|
+
if (result.traces_disabled !== undefined) {
|
|
2634
|
+
lines.push(result.traces_disabled ? 'Scoring without traces.' : 'Scoring with traces.');
|
|
2635
|
+
}
|
|
2636
|
+
if (result.target) {
|
|
2637
|
+
const target = result.target;
|
|
2638
|
+
lines.push(`Waiting for traces: first look after ${String(target.trace_fetch_delay_seconds)} s, then every ` +
|
|
2639
|
+
`${String(target.trace_fetch_interval_seconds)} s, at most ${String(target.trace_fetch_max_wait_seconds)} s.`);
|
|
2640
|
+
}
|
|
2641
|
+
ctx.out.result(result, () => actedOn(result, lines.join('\n')));
|
|
2642
|
+
}));
|
|
2643
|
+
const checkRender = (result) => {
|
|
2644
|
+
const items = (result.items ?? result.checks);
|
|
2645
|
+
const lines = [`ok: ${result.ok ? 'yes' : 'no'}`];
|
|
2646
|
+
if (Array.isArray(items)) {
|
|
2647
|
+
for (const item of items)
|
|
2648
|
+
lines.push(`${item.ok ? 'pass' : item.required === false ? 'want' : 'FAIL'} ${item.key ?? item.name} ${item.message ?? item.detail ?? ''}`);
|
|
2649
|
+
}
|
|
2650
|
+
return lines.join('\n');
|
|
2651
|
+
};
|
|
2652
|
+
connectCommand
|
|
2653
|
+
.command('check-traces <session-id>')
|
|
2654
|
+
.description('Check QualiLoop tracing from one session you produced on this machine.')
|
|
2655
|
+
.action(run(async (ctx, session) => {
|
|
2656
|
+
const result = await connect.checkTraces(ctx.client, { project: connectProject(ctx) }, session);
|
|
2657
|
+
ctx.out.result(result, () => actedOn(result, checkRender(result)));
|
|
2658
|
+
return result.ok ? EXIT.ok : EXIT.failed;
|
|
2659
|
+
}));
|
|
2660
|
+
connectCommand
|
|
2661
|
+
.command('check')
|
|
2662
|
+
.description('Send one real test message to the saved endpoint and report what arrived.')
|
|
2663
|
+
.action(run(async (ctx) => {
|
|
2664
|
+
ctx.out.progress('Sending one test message; this can take up to a minute...');
|
|
2665
|
+
const result = await connect.check(ctx.client, { project: connectProject(ctx) });
|
|
2666
|
+
ctx.out.result(result, () => actedOn(result, checkRender(result)));
|
|
2667
|
+
return result.ok ? EXIT.ok : EXIT.failed;
|
|
2668
|
+
}));
|
|
2669
|
+
connectCommand
|
|
2670
|
+
.command('disconnect')
|
|
2671
|
+
.description('Forget the saved endpoint and turn live data off. Past results stay.')
|
|
2672
|
+
.action(run(async (ctx) => {
|
|
2673
|
+
const result = await connect.disconnect(ctx.client, { project: connectProject(ctx) });
|
|
2674
|
+
ctx.out.result(result, () => actedOn(result, 'Disconnected.'));
|
|
2675
|
+
}));
|
|
2676
|
+
const mcp = program
|
|
2677
|
+
.command('mcp')
|
|
2678
|
+
.description('Run the QualiLoop MCP server over stdio, for chat apps and agents that cannot run commands. It uses your qualiloop login.')
|
|
2679
|
+
.action(async (_options, command) => {
|
|
2680
|
+
const opts = command.optsWithGlobals();
|
|
2681
|
+
await serveStdio(new QualiloopClient({ url: opts.url }));
|
|
2682
|
+
});
|
|
2683
|
+
mcp
|
|
2684
|
+
.command('install')
|
|
2685
|
+
.description('Add the MCP server to Claude Desktop, or to the clients given with --client.')
|
|
2686
|
+
.addOption(new Option('--client <client...>', 'which clients; all for every one')
|
|
2687
|
+
.choices([...CLIENTS, 'all'])
|
|
2688
|
+
.default(DEFAULT_CLIENTS))
|
|
2689
|
+
.addOption(new Option('--scope <scope>', 'for you everywhere, or for this project only').choices(['user', 'project']).default('user'))
|
|
2690
|
+
.option('--print', 'print the configuration to paste instead of writing it (every client, or those of --client)')
|
|
2691
|
+
.action(run(async ({ client, out, opts, command }) => {
|
|
2692
|
+
const chosen = opts.client.includes('all') ? [...CLIENTS] : opts.client;
|
|
2693
|
+
if (opts.print) {
|
|
2694
|
+
const given = command.getOptionValueSource('client') !== 'default';
|
|
2695
|
+
const text = snippets(client.url, given ? chosen : CLIENTS);
|
|
2696
|
+
out.result({ snippets: text }, () => text);
|
|
2697
|
+
return EXIT.ok;
|
|
2698
|
+
}
|
|
2699
|
+
const results = install(chosen, { scope: opts.scope, url: client.url });
|
|
2700
|
+
out.result(results, () => [
|
|
2701
|
+
...results.map((item) => `${item.done ? 'Added to' : 'Not added to'} ${item.client}: ${item.where}`),
|
|
2702
|
+
'',
|
|
2703
|
+
client.isSignedIn() ? 'Restart the agent to load it.' : 'Sign in first: qualiloop login. Then restart the agent.',
|
|
2704
|
+
].join('\n'));
|
|
2705
|
+
return results.every((item) => item.done) ? EXIT.ok : EXIT.failed;
|
|
2706
|
+
}));
|
|
2707
|
+
program
|
|
2708
|
+
.command('guide')
|
|
2709
|
+
.description('How to use QualiLoop well: the guide the MCP server gives agents as its instructions.')
|
|
2710
|
+
.action(run(async ({ out }) => {
|
|
2711
|
+
const guide = bundledGuide();
|
|
2712
|
+
out.result({ guide }, () => guide);
|
|
2713
|
+
}));
|
|
2714
|
+
program
|
|
2715
|
+
.command('actions')
|
|
2716
|
+
.description('List the actions you may run, as the MCP server offers them.')
|
|
2717
|
+
.action(run(async ({ client, out }) => {
|
|
2718
|
+
const catalog = await loadCatalog(client);
|
|
2719
|
+
out.result(catalog, () => table(catalog.map((item) => ({ ...item, kind: item.read_only ? 'read' : 'write' })), [
|
|
2720
|
+
['name', 'Action', 26],
|
|
2721
|
+
['kind', 'Kind'],
|
|
2722
|
+
['cli', 'Command', 60],
|
|
2723
|
+
]));
|
|
2724
|
+
}));
|
|
2725
|
+
program
|
|
2726
|
+
.command('action <name>')
|
|
2727
|
+
.description('Run one action with JSON arguments, as the MCP server would: qualiloop action list_runs --args \'{"limit": 5}\'')
|
|
2728
|
+
.option('--args <json>', 'the arguments as a JSON object', '{}')
|
|
2729
|
+
.option('--yes', 'answer yes to the question an action that deletes asks first')
|
|
2730
|
+
.action(run(async ({ client, out, project, opts }, name) => {
|
|
2731
|
+
let args;
|
|
2732
|
+
try {
|
|
2733
|
+
args = JSON.parse(String(opts.args ?? '{}'));
|
|
2734
|
+
}
|
|
2735
|
+
catch {
|
|
2736
|
+
throw new ApiError('--args must be a JSON object.', 400, EXIT.usage);
|
|
2737
|
+
}
|
|
2738
|
+
const spec = bundledCatalog().find((item) => item.name === name) ??
|
|
2739
|
+
(await loadCatalog(client)).find((item) => item.name === name);
|
|
2740
|
+
const properties = (spec?.input_schema.properties ?? {});
|
|
2741
|
+
if ('project' in properties && args.project === undefined && project !== undefined)
|
|
2742
|
+
args.project = project;
|
|
2743
|
+
if (spec?.confirm === 'always' && !opts.yes && !(await confirm(`Run ${name}, which deletes?`))) {
|
|
2744
|
+
throw new ApiError('Not run.', 400, EXIT.usage);
|
|
2745
|
+
}
|
|
2746
|
+
const result = await client.action(name, args);
|
|
2747
|
+
out.result(result, () => JSON.stringify(result, null, 2));
|
|
2748
|
+
}));
|
|
2749
|
+
const urlArg = (args) => {
|
|
2750
|
+
const index = args.indexOf('--url');
|
|
2751
|
+
if (index >= 0)
|
|
2752
|
+
return args[index + 1];
|
|
2753
|
+
return args.find((arg) => arg.startsWith('--url='))?.slice('--url='.length);
|
|
2754
|
+
};
|
|
2755
|
+
const showKnowledgeAdminCommands = async (args) => {
|
|
2756
|
+
if (!args.includes('knowledge') || !args.some((arg) => arg === '--help' || arg === '-h' || arg === 'help')) {
|
|
2757
|
+
return;
|
|
2758
|
+
}
|
|
2759
|
+
const catalog = await loadCatalog(new QualiloopClient({ url: urlArg(args), kind: 'cli' }));
|
|
2760
|
+
const names = new Set(catalog.map((item) => item.name));
|
|
2761
|
+
for (const [command, action] of Object.entries(SUPER_ADMIN_KNOWLEDGE)) {
|
|
2762
|
+
if (names.has(action))
|
|
2763
|
+
knowledgeAdminShown.add(command);
|
|
2764
|
+
}
|
|
2765
|
+
};
|
|
2766
|
+
export const main = async (argv = process.argv) => {
|
|
2767
|
+
await showKnowledgeAdminCommands(argv.slice(2));
|
|
2768
|
+
await program.parseAsync(argv);
|
|
2769
|
+
};
|
|
2770
|
+
main().catch((error) => {
|
|
2771
|
+
if (error instanceof CommanderError) {
|
|
2772
|
+
process.exitCode = error.exitCode === 0 ? EXIT.ok : EXIT.usage;
|
|
2773
|
+
return;
|
|
2774
|
+
}
|
|
2775
|
+
process.stderr.write(`qualiloop: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
2776
|
+
process.exitCode = EXIT.server;
|
|
2777
|
+
});
|