qualiloop 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,1480 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { createInterface } from 'node:readline/promises';
4
+ import { Command, CommanderError, Help, Option } from 'commander';
5
+ import { ApiError, EXIT, QualiloopClient, VERSION } from './api.js';
6
+ import { login } from './auth.js';
7
+ import { bundledCatalog, bundledGuide, loadCatalog } from './catalog.js';
8
+ import { credentialsPath, forgetCredentials, resolveProject, setDefaultProject, storedCredentials, } from './config.js';
9
+ import * as connect from './connect.js';
10
+ import { CLIENTS, DEFAULT_CLIENTS, install, snippets } from './mcp/install.js';
11
+ import { serveStdio } from './mcp/server.js';
12
+ import { fields, output, table } from './output.js';
13
+ import { cancelGeneration, compareBatch, comparisonText, getGeneration, runsExitCode, startGateWithKey, startGeneration, waitForBatch, waitForGateRun, waitForGateRunWithKey, waitForGeneration, } from './workflows.js';
14
+ const program = new Command();
15
+ const USE_EACH = `
16
+ Short form:
17
+ ql is the same command: ql suites run core --wait
18
+
19
+ Start here:
20
+ qualiloop guide how to use these commands well: what to run, in what order
21
+ qualiloop connect connect the agent in this codebase: sign in, choose the
22
+ project, write its key into .env, print the steps
23
+ qualiloop connect guide the steps to connect an agent in this codebase to QualiLoop
24
+
25
+ CLI or MCP?
26
+ Both use the same sign-in and run the same actions, so either one does
27
+ everything. Pick one and use it for everything.
28
+ The CLI (qualiloop ...) suits a terminal, scripts, CI, and coding agents
29
+ that can run commands, such as Claude Code, Cursor or Codex.
30
+ The MCP server (qualiloop mcp) suits chat apps and agents that cannot run
31
+ commands, such as Claude Desktop. Set it up with: qualiloop mcp install
32
+
33
+ Exit codes:
34
+ 0 done; with --wait, everything passed
35
+ 1 what was checked failed: a gate said fail, a run found a major problem
36
+ 2 the command or its arguments were wrong
37
+ 3 not signed in, the sign-in ended, or your role cannot do this
38
+ 4 not found
39
+ 5 waited longer than --timeout
40
+ 6 QualiLoop could not be reached or answered with an error
41
+
42
+ Environment:
43
+ QUALILOOP_URL the QualiLoop address (default https://app.qualiloop.com)
44
+ QUALILOOP_TOKEN a CLI sign-in token, for CI instead of qualiloop login
45
+ QUALILOOP_GATE_KEY a release gate's deploy key, for qualiloop gate run in CI
46
+ QUALILOOP_PROJECT the project to use when --project is not given
47
+ QUALILOOP_SETUP_TOKEN a project setup token for qualiloop connect; when set, it is
48
+ used instead of the sign-in, on the token's own project
49
+ `;
50
+ program
51
+ .name('qualiloop')
52
+ .description('QualiLoop from the terminal, scripts, CI and coding agents.')
53
+ .version(VERSION)
54
+ .option('--url <url>', 'the QualiLoop address (or QUALILOOP_URL)')
55
+ .option('--json', 'print the result as JSON, for scripts')
56
+ .option('-p, --project <project>', 'the project: its number or name (or QUALILOOP_PROJECT)')
57
+ .addHelpText('after', USE_EACH)
58
+ .showHelpAfterError('(add --help for usage)')
59
+ .exitOverride();
60
+ const run = (handler) => async (...args) => {
61
+ const command = args[args.length - 1];
62
+ const opts = command.optsWithGlobals();
63
+ const client = new QualiloopClient({ url: opts.url, kind: 'cli' });
64
+ const ctx = {
65
+ client,
66
+ out: output(Boolean(opts.json)),
67
+ project: resolveProject(client.url, opts.project),
68
+ opts,
69
+ command,
70
+ };
71
+ try {
72
+ const code = await handler(ctx, ...args.slice(0, -1));
73
+ process.exitCode = code ?? EXIT.ok;
74
+ }
75
+ catch (error) {
76
+ if (error instanceof ApiError) {
77
+ if (ctx.out.json) {
78
+ process.stdout.write(`${JSON.stringify({ error: error.message, status: error.status }, null, 2)}\n`);
79
+ }
80
+ else
81
+ process.stderr.write(`qualiloop: ${error.message}\n`);
82
+ process.exitCode = error.exitCode;
83
+ return;
84
+ }
85
+ process.stderr.write(`qualiloop: ${error instanceof Error ? error.message : String(error)}\n`);
86
+ process.exitCode = EXIT.server;
87
+ }
88
+ };
89
+ const intArg = (value) => {
90
+ const parsed = Number.parseInt(value.replace(/^#/, ''), 10);
91
+ if (!Number.isFinite(parsed))
92
+ throw new ApiError(`${value} is not a number.`, 400, EXIT.usage);
93
+ return parsed;
94
+ };
95
+ const limitOption = (what, fallback, most) => new Option('--limit <n>', `most ${what} to show (up to ${most})`).default(fallback);
96
+ const limitOf = (opts, most) => {
97
+ const limit = intArg(String(opts.limit));
98
+ if (limit < 1 || limit > most)
99
+ throw new ApiError(`--limit takes 1 to ${most}.`, 400, EXIT.usage);
100
+ return limit;
101
+ };
102
+ const listed = (rendered, shown, total, empty) => {
103
+ if (!rendered)
104
+ return empty;
105
+ if (total === undefined || total <= shown)
106
+ return rendered;
107
+ return `${rendered}\n\n${shown} of ${total} shown. See more with --limit ${total}.`;
108
+ };
109
+ const projectFlag = (ctx) => {
110
+ const given = ctx.opts.project;
111
+ if (!given)
112
+ return '';
113
+ return ` -p ${/^[\w#.-]+$/.test(given) ? given : JSON.stringify(given)}`;
114
+ };
115
+ const confirm = async (question) => {
116
+ if (!process.stdin.isTTY) {
117
+ throw new ApiError(`${question} Add --yes to answer without a terminal.`, 400, EXIT.usage);
118
+ }
119
+ const prompt = createInterface({ input: process.stdin, output: process.stderr });
120
+ try {
121
+ return /^y(es)?$/i.test((await prompt.question(`${question} [y/N] `)).trim());
122
+ }
123
+ finally {
124
+ prompt.close();
125
+ }
126
+ };
127
+ const failOnOption = () => new Option('--fail-on <severity>', 'with --wait, exit 1 when a run has a problem this bad')
128
+ .choices(['major', 'minor', 'none'])
129
+ .default('major');
130
+ const browserLogin = (client, out, browser) => login(client, {
131
+ browser,
132
+ onStarted: ({ url, code, opened }) => {
133
+ out.progress(`${opened ? 'Opened' : 'Open'} ${url}\n` +
134
+ `Check that the page shows ${code}, then approve. No account yet? Create one from that page.`);
135
+ out.progress('Waiting for approval...');
136
+ },
137
+ });
138
+ const signedInAs = (result) => `Signed in to ${result.url} as ${result.user?.email ?? 'you'}` +
139
+ (result.user?.organization_name ? ` (${result.user.organization_name})` : '') +
140
+ '.';
141
+ const viaNpx = () => process.env.npm_command === 'exec' || /[\\/]_npx[\\/]/.test(process.argv[1] ?? '');
142
+ const invocation = () => (viaNpx() ? 'npx qualiloop' : 'qualiloop');
143
+ program
144
+ .command('login')
145
+ .description('Sign in by approving the CLI in your browser.')
146
+ .option('--no-browser', 'print the link instead of opening it')
147
+ .action(run(async ({ client, out, opts }) => {
148
+ const result = await browserLogin(client, out, opts.browser !== false);
149
+ out.result(result, () => `${signedInAs(result)}\nThe sign-in is stored in ${credentialsPath()}.`);
150
+ }));
151
+ program
152
+ .command('logout')
153
+ .description('Sign out: revoke this sign-in and forget it.')
154
+ .action(run(async ({ client, out }) => {
155
+ if (storedCredentials(client.url)) {
156
+ try {
157
+ await client.request('DELETE', '/v1/cli/token');
158
+ }
159
+ catch (error) {
160
+ if (!(error instanceof ApiError) || error.exitCode !== EXIT.auth)
161
+ throw error;
162
+ }
163
+ }
164
+ const forgot = forgetCredentials(client.url);
165
+ out.result({ signed_out: forgot, url: client.url }, () => forgot ? `Signed out of ${client.url}.` : `Not signed in to ${client.url}.`);
166
+ }));
167
+ program
168
+ .command('whoami')
169
+ .description('Who you are signed in as, where, and the default project.')
170
+ .action(run(async ({ client, out, project }) => {
171
+ const me = await client.request('GET', '/v1/auth/me');
172
+ const stored = storedCredentials(client.url);
173
+ const data = { url: client.url, ...me, organization: stored?.user?.organization_name, project };
174
+ out.result(data, () => fields([
175
+ ['QualiLoop', client.url],
176
+ ['Email', me.email],
177
+ ['Role', me.role],
178
+ ['Organization', stored?.user?.organization_name],
179
+ ['Default project', project],
180
+ ]));
181
+ }));
182
+ const tokens = program.command('tokens').description('Your CLI and MCP sign-ins.');
183
+ tokens
184
+ .command('list', { isDefault: true })
185
+ .description('List your CLI and MCP sign-ins.')
186
+ .action(run(async ({ client, out }) => {
187
+ const rows = await client.request('GET', '/v1/cli/tokens');
188
+ out.result(rows, () => table(rows, [
189
+ ['id', 'ID'],
190
+ ['name', 'Name', 40],
191
+ ['current', 'This one'],
192
+ ['last_used_at', 'Last used', 20],
193
+ ['expires_at', 'Expires', 20],
194
+ ]) || 'No sign-ins.');
195
+ }));
196
+ tokens
197
+ .command('revoke <id>')
198
+ .description('Revoke one sign-in; it stops working at once.')
199
+ .action(run(async ({ client, out }, id) => {
200
+ const revoked = await client.request('DELETE', `/v1/cli/tokens/${intArg(id)}`);
201
+ out.result(revoked, () => `Revoked ${revoked.name}.`);
202
+ }));
203
+ const projects = program.command('projects').description('Your projects.');
204
+ projects
205
+ .command('list', { isDefault: true })
206
+ .description('List the projects of your organization.')
207
+ .action(run(async ({ client, out, project }) => {
208
+ const result = await client.action('list_projects');
209
+ out.result(result, () => table(result.projects.map((row) => ({ ...row, default: String(row.number) === String(project) || row.name === project })), [
210
+ ['number', '#'],
211
+ ['name', 'Name', 50],
212
+ ['live_data_enabled', 'Live'],
213
+ ['default', 'Default'],
214
+ ]) || 'No projects yet.');
215
+ }));
216
+ projects
217
+ .command('show [project]')
218
+ .description('A project at a glance: its agent and how its tests went.')
219
+ .option('--days <n>', 'days of results to count', '30')
220
+ .action(run(async ({ client, out, project, opts }, given) => {
221
+ const result = await client.action('get_project', {
222
+ project: given ?? project,
223
+ window_days: intArg(String(opts.days)),
224
+ });
225
+ out.result(result, () => fields([
226
+ ['Project', `#${result.number} ${result.name}`],
227
+ ['Agent', result.agent.connected ? result.agent.endpoint : 'not connected (qualiloop connect)'],
228
+ ['Traces from', result.agent.traces_from],
229
+ ['Live traffic', result.live_data_enabled],
230
+ [`Tests (${result.stats.window_days} days)`, `${result.stats.tests_passed}/${result.stats.tests_finished} passed (${result.stats.test_pass_rate_pct ?? '-'})`],
231
+ ['Major problems', result.stats.major_problems],
232
+ ['Minor problems', result.stats.minor_problems],
233
+ ['Link', result.url],
234
+ ]));
235
+ }));
236
+ projects
237
+ .command('use <project>')
238
+ .description('Make a project the default for this QualiLoop address.')
239
+ .action(run(async ({ client, out }, given) => {
240
+ const result = await client.action('get_project', { project: given });
241
+ setDefaultProject(client.url, String(result.number));
242
+ out.result({ project: result.number, name: result.name }, () => `Commands now use project #${result.number} ${result.name}.`);
243
+ }));
244
+ const knowledge = program
245
+ .command('knowledge')
246
+ .description('System knowledge: what QualiLoop knows of the agent, its coverage, and exploring it.');
247
+ const SUPER_ADMIN_KNOWLEDGE = {
248
+ show: 'get_knowledge_item',
249
+ edit: 'update_knowledge_item',
250
+ };
251
+ const knowledgeAdminShown = new Set();
252
+ knowledge.configureHelp({
253
+ visibleCommands(cmd) {
254
+ return Help.prototype.visibleCommands
255
+ .call(this, cmd)
256
+ .filter((sub) => !(sub.name() in SUPER_ADMIN_KNOWLEDGE) || knowledgeAdminShown.has(sub.name()));
257
+ },
258
+ });
259
+ knowledge
260
+ .command('summary', { isDefault: true })
261
+ .description('The agent at a glance: capabilities and test coverage.')
262
+ .action(run(async ({ client, out, project }) => {
263
+ const result = await client.action('get_knowledge', { project });
264
+ const sources = result.sources ?? [];
265
+ out.result(result, () => [
266
+ fields([
267
+ ['Project', result.project],
268
+ ['Coverage', result.coverage ? `${result.coverage.percent}% (${result.coverage.covered}/${result.coverage.total})` : '-'],
269
+ ['Sources', sources.length ? sources.map((row) => row.name).join(', ') : 'none (qualiloop connect knowledge)'],
270
+ ['Exploring now', result.exploring],
271
+ ['Link', result.url],
272
+ ]),
273
+ '',
274
+ table(result.capabilities, [
275
+ ['name', 'Capability', 50],
276
+ ['confirmed', 'Confirmed'],
277
+ ]) || 'No capabilities known yet.',
278
+ ].join('\n'));
279
+ }));
280
+ knowledge
281
+ .command('list')
282
+ .description('The items QualiLoop knows, by section, with their ids. Super admins see every section and status.')
283
+ .option('--section <section>', 'only one section: capability, entity_group, entity (super admins: also fact, component, state, action, transition)')
284
+ .addOption(limitOption('items', '100', 1000))
285
+ .action(run(async ({ client, out, project, opts }) => {
286
+ const result = await client.action('list_knowledge', {
287
+ project,
288
+ section: opts.section,
289
+ limit: limitOf(opts, 1000),
290
+ });
291
+ const columns = [
292
+ ['id', 'ID'],
293
+ ['section', 'Section'],
294
+ ['name', 'Name', 45],
295
+ ['confirmed', 'Confirmed'],
296
+ ];
297
+ if (result.full)
298
+ columns.push(['intended', 'Intended'], ['observed', 'Observed'], ['reported', 'Reported'], ['projected', 'Projected']);
299
+ out.result(result, () => listed(table(result.items, columns), result.items.length, result.total, 'Nothing known yet.'));
300
+ }));
301
+ knowledge
302
+ .command('show <id>')
303
+ .description('One item in full: statuses, evidence and links (super admins).')
304
+ .action(run(async ({ client, out, project }, id) => {
305
+ const result = await client.action('get_knowledge_item', {
306
+ project,
307
+ item: intArg(id),
308
+ });
309
+ const node = result.node;
310
+ out.result(result, () => [
311
+ fields([
312
+ ['Item', `${node.id} ${node.name}`],
313
+ ['Section', node.kind ? `${node.section} (${node.kind})` : node.section],
314
+ ['Description', node.description],
315
+ ['Intended', node.intended],
316
+ ['Observed', node.observed],
317
+ ['Reported', node.reported],
318
+ ['Projected', node.projected],
319
+ ['Locked', node.locked],
320
+ ]),
321
+ '',
322
+ table(result.evidence, [
323
+ ['dimension', 'Status'],
324
+ ['polarity', 'Says'],
325
+ ['source', 'Source'],
326
+ ['run_number', 'Run'],
327
+ ['quote', 'Quote', 70],
328
+ ]) || 'No evidence.',
329
+ ].join('\n'));
330
+ }));
331
+ const markOption = (name) => new Option(`--${name} <mark>`, `manual ${name} evidence: yes, opposite, or clear to remove it`).choices(['yes', 'opposite', 'clear']);
332
+ knowledge
333
+ .command('edit <id>')
334
+ .description('Change an item by hand: its name, description, or a status as manual evidence (super admins).')
335
+ .option('--name <name>')
336
+ .option('--description <text>')
337
+ .option('--kind <kind>')
338
+ .addOption(new Option('--belongs-to <owner>').choices(['agent', 'system', 'world']))
339
+ .addOption(markOption('intended'))
340
+ .addOption(markOption('observed'))
341
+ .addOption(markOption('reported'))
342
+ .addOption(markOption('projected'))
343
+ .action(run(async ({ client, out, project, opts }, id) => {
344
+ const result = await client.action('update_knowledge_item', {
345
+ project,
346
+ item: intArg(id),
347
+ name: opts.name,
348
+ description: opts.description,
349
+ kind: opts.kind,
350
+ belongs_to: opts.belongsTo,
351
+ intended: opts.intended,
352
+ observed: opts.observed,
353
+ reported: opts.reported,
354
+ projected: opts.projected,
355
+ });
356
+ out.result(result, () => `Updated item ${id}: ${result.updated.join(', ')}.`);
357
+ }));
358
+ knowledge
359
+ .command('general')
360
+ .description("Change the agent's name, summary or description in System knowledge.")
361
+ .option('--name <name>')
362
+ .option('--summary <text>')
363
+ .option('--description <text>')
364
+ .action(run(async ({ client, out, project, opts }) => {
365
+ const result = await client.action('update_knowledge_general', {
366
+ project,
367
+ name: opts.name,
368
+ summary: opts.summary,
369
+ description: opts.description,
370
+ });
371
+ out.result(result, () => `Updated ${result.updated.join(', ')}.`);
372
+ }));
373
+ knowledge
374
+ .command('explore')
375
+ .description('Explore the agent: 3 rounds of up to 8 conversations, up to 24 conversation credits, not judged.')
376
+ .option('--note <text>', 'what to look at more closely')
377
+ .action(run(async (ctx) => {
378
+ const { client, out, project, opts } = ctx;
379
+ const result = await client.action('start_exploration', {
380
+ project,
381
+ note: opts.note,
382
+ });
383
+ out.result(result, () => `Started exploration #${result.exploration.number ?? result.exploration.id}: up to ${result.most_credits} conversations, so up to ${result.most_credits} conversation credits.\nFollow it: qualiloop knowledge explorations${projectFlag(ctx)}`);
384
+ }));
385
+ knowledge
386
+ .command('explorations')
387
+ .description("The project's latest explorations and where each stands.")
388
+ .action(run(async ({ client, out, project }) => {
389
+ const result = await client.action('list_explorations', { project });
390
+ out.result(result, () => table(result.explorations.map((row) => ({
391
+ ...row,
392
+ number: row.number ?? row.id,
393
+ round: `${row.current_round ?? 0}/${row.rounds ?? '-'}`,
394
+ })), [
395
+ ['number', 'Number'],
396
+ ['trigger', 'Started by'],
397
+ ['status', 'Status'],
398
+ ['round', 'Round'],
399
+ ['created_at', 'Created', 20],
400
+ ['completed_at', 'Finished', 20],
401
+ ]) || 'No explorations yet.');
402
+ }));
403
+ const ORIGIN_LABEL = {
404
+ code: 'coding agent',
405
+ manual: 'by hand',
406
+ connector: 'connection settings',
407
+ trace: 'seen in traces',
408
+ };
409
+ const KIND_LABEL = { system_prompt: 'System prompt', tools: 'Tools', documentation: 'Documentation' };
410
+ knowledge
411
+ .command('sources')
412
+ .description('What the knowledge is read from: the system prompts, tools and documentation, with their ids.')
413
+ .addOption(new Option('--kind <kind>', 'only one kind').choices(['system_prompt', 'tools', 'documentation']))
414
+ .option('--in-force', 'leave out retired sources')
415
+ .action(run(async ({ client, out, project, opts }) => {
416
+ const result = await client.action('list_sources', {
417
+ project,
418
+ kind: opts.kind,
419
+ include_retired: !opts.inForce,
420
+ });
421
+ out.result(result, () => table(result.sources.map((row) => ({
422
+ ...row,
423
+ kind_label: KIND_LABEL[String(row.kind)] ?? row.kind,
424
+ from: ORIGIN_LABEL[String(row.origin)] ?? row.origin,
425
+ state: row.retired ? 'retired' : row.version ? `version ${row.version}` : 'not confirmed',
426
+ })), [
427
+ ['id', 'ID'],
428
+ ['kind_label', 'Kind'],
429
+ ['name', 'Name', 45],
430
+ ['from', 'From'],
431
+ ['state', 'State'],
432
+ ['last_seen_at', 'Last seen', 20],
433
+ ]) || 'No sources yet. The coding agent setup sends them: qualiloop connect knowledge --file <json>');
434
+ }));
435
+ knowledge
436
+ .command('source <id>')
437
+ .description('One source: its current text, versions, and what it states.')
438
+ .option('--max-chars <n>', 'most characters of the text to show', '20000')
439
+ .action(run(async ({ client, out, project, opts }, id) => {
440
+ const result = await client.action('get_source', {
441
+ project,
442
+ source: intArg(id),
443
+ max_chars: intArg(String(opts.maxChars)),
444
+ });
445
+ out.result(result, () => [
446
+ fields([
447
+ ['Source', `${result.id} ${result.name}`],
448
+ ['Kind', KIND_LABEL[String(result.kind)] ?? result.kind],
449
+ ['From', ORIGIN_LABEL[String(result.origin)] ?? result.origin],
450
+ ['State', result.retired ? 'retired' : result.version ? `version ${result.version}` : 'not confirmed'],
451
+ ['Agent', result.component],
452
+ ['Placeholders', result.placeholders],
453
+ ['Seen at steps', result.trace_steps],
454
+ ['Versions', result.versions.length],
455
+ ['Link', result.url],
456
+ ]),
457
+ '',
458
+ String(result.text ?? ''),
459
+ ...(result.text_cut ? [`\n(${result.text_chars} characters; more with --max-chars)`] : []),
460
+ ...(result.states.length
461
+ ? ['', table(result.states, [['node_id', 'Item'], ['section', 'Section'], ['name', 'It states', 60]])]
462
+ : []),
463
+ ].join('\n'));
464
+ }));
465
+ knowledge
466
+ .command('add-doc <name>')
467
+ .description('Add a document the agent answers from, or a new version of one added by hand (admins, ML team).')
468
+ .requiredOption('--file <path>', 'the text, from a file (or - for stdin)')
469
+ .action(run(async ({ client, out, project, opts }, name) => {
470
+ const file = String(opts.file);
471
+ let text;
472
+ try {
473
+ text = readFileSync(file === '-' ? 0 : file, 'utf8');
474
+ }
475
+ catch (error) {
476
+ throw new ApiError(`Cannot read ${file}: ${error.message}`, 400, EXIT.usage);
477
+ }
478
+ const result = await client.action('save_documentation', { project, name, text });
479
+ out.result(result, () => `Saved ${result.source.name} as source ${result.source.id}, version ${result.source.version}.` +
480
+ (result.fill_queued || result.change_queued ? ' QualiLoop reads it into the system knowledge.' : ''));
481
+ }));
482
+ knowledge
483
+ .command('retire-source <id>')
484
+ .description('Take a source added by hand or seen in traces out of force (admins, ML team). Its versions are kept.')
485
+ .action(run(async ({ client, out, project }, id) => {
486
+ const result = await client.action('retire_source', { project, source: intArg(id) });
487
+ out.result(result, () => `Retired ${result.source.name}. Restore it in System Knowledge, Sources.`);
488
+ }));
489
+ program
490
+ .command('change <description...>')
491
+ .description('Tell QualiLoop the agent changed, so it re-checks what the change touches.')
492
+ .option('--no-explore', 'record the change without exploring again')
493
+ .action(run(async ({ client, out, project, opts }, words) => {
494
+ const result = await client.action('report_change', {
495
+ project,
496
+ description: words.join(' '),
497
+ explore: opts.explore !== false,
498
+ });
499
+ out.result(result, () => `Change recorded in ${result.project}.${result.exploring ? ' QualiLoop explores what it touches again.' : ''}`);
500
+ }));
501
+ const testColumns = [
502
+ ['id', 'ID'],
503
+ ['name', 'Name', 45],
504
+ ['mode', 'Mode'],
505
+ ['last', 'Last run'],
506
+ ['suites', 'Suites'],
507
+ ];
508
+ const lastRun = (row) => {
509
+ const last = row.last_run;
510
+ return last ? `#${last.run_number} ${last.outcome}` : '-';
511
+ };
512
+ const tests = program.command('tests').description('Saved tests.');
513
+ tests
514
+ .command('list', { isDefault: true })
515
+ .description('List the saved tests of the project.')
516
+ .option('--suite <suite>', 'only the tests of this suite (id or name)')
517
+ .option('--search <text>', 'only tests whose name contains this')
518
+ .addOption(limitOption('tests', '100', 1000))
519
+ .action(run(async ({ client, out, project, opts }) => {
520
+ const result = await client.action('list_tests', {
521
+ project,
522
+ suite: opts.suite,
523
+ search: opts.search,
524
+ limit: limitOf(opts, 1000),
525
+ });
526
+ out.result(result, () => listed(table(result.tests.map((row) => ({ ...row, last: lastRun(row) })), testColumns), result.tests.length, result.total, 'No tests.'));
527
+ }));
528
+ tests
529
+ .command('show <id>')
530
+ .description('One saved test in full.')
531
+ .action(run(async ({ client, out, project }, id) => {
532
+ const result = await client.action('get_test', { project, test: intArg(id) });
533
+ out.result(result, () => fields([
534
+ ['Test', `${result.id} ${result.name}`],
535
+ ['Mode', `${result.mode} (${result.run_type})`],
536
+ ['Instructions', result.instructions],
537
+ ['Persona', result.persona],
538
+ ['Steps', result.steps],
539
+ ['Turns', result.max_turns],
540
+ ['Conversations', result.conversations],
541
+ ['Suites', result.suites],
542
+ ['Last run', lastRun(result)],
543
+ ]));
544
+ }));
545
+ const testFieldOptions = (command) => command
546
+ .option('--instructions <text>', 'what the simulated user wants and how they behave')
547
+ .option('--persona <text>', 'who the simulated user is')
548
+ .option('--step <text>', 'a scripted step, in order (repeat)', (value, all = []) => [...all, value])
549
+ .option('--turns <n>', 'most turns of one conversation')
550
+ .option('--conversations <n>', 'conversations per run')
551
+ .option('--language <language>', 'the language the simulated user speaks');
552
+ testFieldOptions(tests
553
+ .command('create')
554
+ .description('Write a new saved test.')
555
+ .requiredOption('--name <name>', 'a short name for the test'))
556
+ .option('--red-team <attack>', 'make it an attack of this type (prompt_injection, jailbreak, data_leak, ...)')
557
+ .option('--single', 'one message per prompt instead of a conversation')
558
+ .option('--suite <suite>', 'add it to this suite (repeat)', (value, all = []) => [...all, value])
559
+ .action(run(async (ctx) => {
560
+ const { client, out, project, opts } = ctx;
561
+ if (!opts.instructions)
562
+ throw new ApiError('Give --instructions.', 400, EXIT.usage);
563
+ const result = await client.action('create_test', {
564
+ project,
565
+ name: opts.name,
566
+ instructions: opts.instructions,
567
+ persona: opts.persona,
568
+ steps: opts.step,
569
+ max_turns: opts.turns ? intArg(String(opts.turns)) : undefined,
570
+ conversations: opts.conversations ? intArg(String(opts.conversations)) : undefined,
571
+ language: opts.language,
572
+ mode: opts.redTeam ? 'red_team' : 'regular',
573
+ attack_type: opts.redTeam,
574
+ shape: opts.single ? 'single' : 'conversation',
575
+ suites: opts.suite,
576
+ });
577
+ out.result(result, () => `Saved test ${result.id} ${result.name}. Run it: qualiloop run ${result.id}${projectFlag(ctx)}`);
578
+ }));
579
+ tests
580
+ .command('delete <id>')
581
+ .description('Delete a saved test and take it out of its suites. Its past runs stay.')
582
+ .option('--yes', 'delete without asking')
583
+ .action(run(async ({ client, out, project, opts }, id) => {
584
+ const test = intArg(id);
585
+ if (!opts.yes) {
586
+ const found = await client.action('get_test', { project, test });
587
+ if (!(await confirm(`Delete test ${found.id} ${found.name}?`))) {
588
+ out.result({ deleted: false, id: test }, () => 'Not deleted.');
589
+ return EXIT.ok;
590
+ }
591
+ }
592
+ const result = await client.action('delete_test', { project, test });
593
+ out.result(result, () => `Deleted test ${result.id} ${result.name}.`);
594
+ }));
595
+ testFieldOptions(tests.command('edit <id>').description('Change a saved test; only what you give changes.').option('--name <name>', 'a new name'))
596
+ .option('--no-steps', 'remove the scripted steps')
597
+ .action(run(async ({ client, out, project, opts }, id) => {
598
+ const result = await client.action('update_test', {
599
+ project,
600
+ test: intArg(id),
601
+ name: opts.name,
602
+ instructions: opts.instructions,
603
+ persona: opts.persona,
604
+ steps: opts.steps === false ? [] : opts.step,
605
+ max_turns: opts.turns ? intArg(String(opts.turns)) : undefined,
606
+ conversations: opts.conversations ? intArg(String(opts.conversations)) : undefined,
607
+ language: opts.language,
608
+ });
609
+ out.result(result, () => `Updated test ${result.id}: ${result.updated.join(', ')}.`);
610
+ }));
611
+ const launched = async (ctx, result) => {
612
+ const { out, project, opts } = ctx;
613
+ for (const item of result.failed)
614
+ out.progress(`Test ${item.test_id} did not start: ${item.reason}`);
615
+ if (!result.batch_id || !result.started.length) {
616
+ out.result(result, () => 'Nothing started.');
617
+ return EXIT.failed;
618
+ }
619
+ const started = `Started ${result.started.length} run(s): ${result.started.map((item) => `#${item.run_number}`).join(', ')}`;
620
+ const resume = `qualiloop runs wait ${result.batch_id}${projectFlag(ctx)}`;
621
+ if (!opts.wait) {
622
+ out.result(result, () => [started, `Batch ${result.batch_id}. Wait for it: ${resume}`, `Or open ${result.url}`].join('\n'));
623
+ return EXIT.ok;
624
+ }
625
+ out.progress(`${started}\nBatch ${result.batch_id}. If you stop waiting, resume with: ${resume}`);
626
+ return follow(ctx, project ?? String(result.project_number), result.batch_id, result);
627
+ };
628
+ const follow = async (ctx, project, batch, launch = {}) => {
629
+ const { client, out, opts } = ctx;
630
+ out.progress('Waiting until every run has talked to the agent, been judged and had its problems sorted...');
631
+ const runs = await waitForBatch(client, project, batch, {
632
+ timeoutMinutes: intArg(String(opts.timeout)),
633
+ onProgress: (message) => out.progress(message),
634
+ });
635
+ const code = runsExitCode(runs, opts.failOn);
636
+ const failing = runs.filter((item) => runsExitCode([item], opts.failOn) !== EXIT.ok);
637
+ let comparison = null;
638
+ try {
639
+ comparison = await compareBatch(client, project, batch);
640
+ }
641
+ catch (error) {
642
+ out.progress(`Could not compare with the previous runs: ${error.message}`);
643
+ }
644
+ out.result({ ...launch, batch_id: batch, runs, passed: code === EXIT.ok, comparison }, () => [
645
+ table(runs, [
646
+ ['run_number', 'Run'],
647
+ ['name', 'Test', 40],
648
+ ['outcome', 'Outcome'],
649
+ ['major_problems', 'Major'],
650
+ ['minor_problems', 'Minor'],
651
+ ]),
652
+ ...(comparison ? ['', comparisonText(comparison, projectFlag(ctx))] : []),
653
+ '',
654
+ code === EXIT.ok
655
+ ? 'Passed.'
656
+ : ['Failed. Read why:', ...failing.map((item) => ` qualiloop problems --run ${item.run_number}${projectFlag(ctx)}`)].join('\n'),
657
+ ].join('\n'));
658
+ return code;
659
+ };
660
+ const waitOptions = (command, waitFlag = true) => {
661
+ if (waitFlag)
662
+ command.option('--wait', 'wait for the results and exit 1 if a run fails');
663
+ else
664
+ command.addOption(new Option('--wait').hideHelp());
665
+ return command.addOption(failOnOption()).option('--timeout <minutes>', 'most minutes to wait', '60');
666
+ };
667
+ waitOptions(program
668
+ .command('run <test-ids...>')
669
+ .description('Run saved tests now, as one batch.')
670
+ .option('--label <label>', 'what Test Results calls this launch')).action(run(async (ctx, ids) => {
671
+ const result = await ctx.client.action('run_tests', { project: ctx.project, tests: ids.map(intArg), label: ctx.opts.label });
672
+ return launched(ctx, result);
673
+ }));
674
+ const suites = program.command('suites').description('Suites of saved tests.');
675
+ suites
676
+ .command('list', { isDefault: true })
677
+ .description('List the suites of the project.')
678
+ .addOption(limitOption('suites', '50', 1000))
679
+ .action(run(async ({ client, out, project, opts }) => {
680
+ const result = await client.action('list_suites', { project });
681
+ const shown = result.suites.slice(0, limitOf(opts, 1000));
682
+ out.result({ ...result, total: result.suites.length, suites: shown }, () => listed(table(shown.map((row) => {
683
+ const last = row.last_run;
684
+ return { ...row, last: last ? `${last.status}, ${last.no_major_percent ?? '-'}% without major` : '-' };
685
+ }), [
686
+ ['id', 'ID'],
687
+ ['name', 'Name', 40],
688
+ ['tests', 'Tests'],
689
+ ['core', 'Core'],
690
+ ['last', 'Last run', 40],
691
+ ]), shown.length, result.suites.length, 'No suites.'));
692
+ }));
693
+ const suiteRef = (suite) => (/^\d+$/.test(suite) ? Number(suite) : suite);
694
+ suites
695
+ .command('create <name>')
696
+ .description('Make a new suite, optionally with tests in it.')
697
+ .option('--description <text>', 'what the suite is for')
698
+ .option('--test <id>', 'a saved test to put in it (repeat)', (value, all = []) => [...all, value])
699
+ .action(run(async (ctx, name) => {
700
+ const { client, out, project, opts } = ctx;
701
+ const result = await client.action('create_suite', {
702
+ project,
703
+ name,
704
+ description: opts.description,
705
+ tests: (opts.test ?? []).map(intArg),
706
+ });
707
+ 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)}`);
708
+ }));
709
+ suites
710
+ .command('add <suite> <test-ids...>')
711
+ .description('Put saved tests in a suite (id, name, or core). A test can be in several suites.')
712
+ .action(run(async ({ client, out, project }, suite, ids) => {
713
+ const result = await client.action('change_suite_tests', {
714
+ project,
715
+ suite: suiteRef(suite),
716
+ add: ids.map(intArg),
717
+ });
718
+ out.result(result, () => `Added ${result.added} test(s) to suite ${result.suite.id} ${result.suite.name}` +
719
+ (Number(result.added) < ids.length ? '; the others were in it already.' : '.'));
720
+ }));
721
+ waitOptions(suites.command('run <suite>').description('Run every test of a suite (id, name, or core).')).action(run(async (ctx, suite) => {
722
+ const result = await ctx.client.action('run_suite', { project: ctx.project, suite: suiteRef(suite) });
723
+ return launched(ctx, result);
724
+ }));
725
+ suites
726
+ .command('delete <suite>')
727
+ .description('Delete a suite (id or name). Its tests stay unless --with-tests; past runs stay.')
728
+ .option('--with-tests', 'also delete its tests, from the library and every other suite')
729
+ .option('--yes', 'delete without asking')
730
+ .action(run(async ({ client, out, project, opts }, suite) => {
731
+ const withTests = Boolean(opts.withTests);
732
+ if (!opts.yes) {
733
+ const found = (await client.action('list_suites', { project })).suites.find((row) => String(row.id) === suite || String(row.name).toLowerCase() === suite.toLowerCase());
734
+ const what = found ? `suite ${found.id} ${found.name}` : `suite ${suite}`;
735
+ const tests = withTests ? (found ? ` and its ${found.tests} test(s)` : ' and its tests') : '';
736
+ if (!(await confirm(`Delete ${what}${tests}?`))) {
737
+ out.result({ deleted: false, suite }, () => 'Not deleted.');
738
+ return EXIT.ok;
739
+ }
740
+ }
741
+ const result = await client.action('delete_suite', {
742
+ project,
743
+ suite: suiteRef(suite),
744
+ delete_tests: withTests,
745
+ });
746
+ out.result(result, () => `Deleted suite ${result.id} ${result.name}` + (result.tests_deleted ? ` and its ${result.tests} test(s).` : '.'));
747
+ }));
748
+ const runs = program.command('runs').description('Test runs and their results.');
749
+ runs
750
+ .command('list', { isDefault: true })
751
+ .description('Recent runs, newest first.')
752
+ .option('--batch <id>', 'only the runs of one launch')
753
+ .option('--status <status>', 'only runs in this status')
754
+ .addOption(limitOption('runs', '20', 500))
755
+ .action(run(async ({ client, out, project, opts }) => {
756
+ const result = await client.action('list_runs', {
757
+ project,
758
+ batch: opts.batch,
759
+ status: opts.status,
760
+ limit: limitOf(opts, 500),
761
+ });
762
+ out.result(result, () => listed(table(result.runs, [
763
+ ['run_number', 'Run'],
764
+ ['name', 'Test', 40],
765
+ ['status_label', 'Status'],
766
+ ['outcome', 'Outcome'],
767
+ ['major_problems', 'Major'],
768
+ ['minor_problems', 'Minor'],
769
+ ]), result.runs.length, result.total, 'No runs.'));
770
+ }));
771
+ runs
772
+ .command('show <run>')
773
+ .description('One run: status, outcome and problems found.')
774
+ .action(run(async ({ client, out, project }, number) => {
775
+ const result = await client.action('get_run', { project, run_number: intArg(number) });
776
+ out.result(result, () => fields([
777
+ ['Run', `#${result.run_number} ${result.name}`],
778
+ ['Status', result.status_label],
779
+ ['Outcome', result.outcome],
780
+ ['Passed', result.test_passed],
781
+ ['Conversations', result.conversations],
782
+ ['Major problems', result.major_problems],
783
+ ['Minor problems', result.minor_problems],
784
+ ['Error', result.error_message],
785
+ ['Link', result.url],
786
+ ]));
787
+ }));
788
+ runs
789
+ .command('delete <run>')
790
+ .description('Delete a run with its conversations and problems. A run still working is stopped first.')
791
+ .option('--yes', 'delete without asking')
792
+ .action(run(async ({ client, out, project, opts }, number) => {
793
+ const runNumber = intArg(number);
794
+ if (!opts.yes) {
795
+ const found = await client.action('get_run', { project, run_number: runNumber });
796
+ if (!(await confirm(`Delete run #${found.run_number} ${found.name}?`))) {
797
+ out.result({ deleted: false, run_number: runNumber }, () => 'Not deleted.');
798
+ return EXIT.ok;
799
+ }
800
+ }
801
+ const result = await client.action('delete_run', { project, run_number: runNumber });
802
+ out.result(result, () => `Deleted run #${result.run_number} ${result.name}.`);
803
+ }));
804
+ waitOptions(runs
805
+ .command('wait <batch>')
806
+ .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)));
807
+ const modeOption = () => new Option('--mode <mode>', 'only problems found by tests of this mode; live traffic counts as regular').choices([
808
+ 'regular',
809
+ 'red_team',
810
+ 'bias',
811
+ ]);
812
+ const sourceOption = () => new Option('--source <source>', "test for Test Lab runs, live for the agent's real traffic").choices(['test', 'live']);
813
+ const problems = program.command('problems').description('Problems QualiLoop found.');
814
+ problems
815
+ .command('list', { isDefault: true })
816
+ .description('Problems, newest first.')
817
+ .option('--run <n>', 'only problems of this run')
818
+ .addOption(new Option('--severity <severity>', 'major or minor').choices(['major', 'minor']))
819
+ .option('--category <text>', 'only problems of a category whose title contains this')
820
+ .addOption(modeOption())
821
+ .addOption(sourceOption())
822
+ .addOption(limitOption('problems', '20', 200))
823
+ .action(run(async ({ client, out, project, opts }) => {
824
+ const result = await client.action('list_problems', {
825
+ project,
826
+ run_number: opts.run ? intArg(String(opts.run)) : undefined,
827
+ severity: opts.severity,
828
+ category: opts.category,
829
+ mode: opts.mode,
830
+ source: opts.source,
831
+ limit: limitOf(opts, 200),
832
+ });
833
+ out.result(result, () => listed(table(result.problems, [
834
+ ['id', 'ID'],
835
+ ['severity', 'Severity'],
836
+ ['title', 'Problem', 55],
837
+ ['run_number', 'Run'],
838
+ ['conversation', 'Conversation', 36],
839
+ ]), result.problems.length, result.total, 'No problems.'));
840
+ }));
841
+ const categories = problems
842
+ .command('categories')
843
+ .description('Recurring kinds of problem, biggest first, with their suggested fix.');
844
+ categories
845
+ .command('list', { isDefault: true })
846
+ .description('List the categories, biggest first, with their ids.')
847
+ .option('--solved', 'include categories marked solved')
848
+ .addOption(modeOption())
849
+ .addOption(sourceOption())
850
+ .addOption(limitOption('categories', '20', 200))
851
+ .action(run(async ({ client, out, project, opts }) => {
852
+ const result = await client.action('list_problem_categories', {
853
+ project,
854
+ include_solved: Boolean(opts.solved),
855
+ mode: opts.mode,
856
+ source: opts.source,
857
+ limit: limitOf(opts, 200),
858
+ });
859
+ out.result(result, () => listed(table(result.categories, [
860
+ ['id', 'ID'],
861
+ ['severity', 'Severity'],
862
+ ['problems', 'Problems'],
863
+ ['solved', 'Solved'],
864
+ ['title', 'Category', 50],
865
+ ['suggested_fix', 'Suggested fix', 50],
866
+ ]), result.categories.length, result.total_categories, 'No categories yet.') + (result.categories.length ? '\n\nThe whole fix: qualiloop problems categories show <id>' : ''));
867
+ }));
868
+ categories
869
+ .command('show <id>')
870
+ .description('One category in full: its description, the whole suggested fix, and its latest problems.')
871
+ .action(run(async ({ client, out, project }, id) => {
872
+ const result = await client.action('get_problem_category', {
873
+ project,
874
+ category: intArg(id),
875
+ });
876
+ out.result(result, () => [
877
+ fields([
878
+ ['Category', `${result.id} ${result.title}`],
879
+ ['Severity', result.severity],
880
+ ['Problems', result.problems],
881
+ ['Solved', result.solved],
882
+ ['Link', result.url],
883
+ ]),
884
+ '',
885
+ 'Description:',
886
+ String(result.description ?? '-'),
887
+ '',
888
+ 'Suggested fix:',
889
+ String(result.suggested_fix ?? '-'),
890
+ '',
891
+ table(result.latest_problems, [
892
+ ['severity', 'Severity'],
893
+ ['title', 'Latest problems', 55],
894
+ ['conversation', 'Conversation', 36],
895
+ ]),
896
+ ].join('\n'));
897
+ }));
898
+ categories
899
+ .command('solve <id>')
900
+ .description('Mark a category solved once its fix is deployed; the next problem in it opens it again.')
901
+ .option('--reopen', 'open it again instead')
902
+ .action(run(async ({ client, out, project, opts }, id) => {
903
+ const result = await client.action('set_category_solved', {
904
+ project,
905
+ category: intArg(id),
906
+ solved: !opts.reopen,
907
+ });
908
+ out.result(result, () => `Category ${result.id} ${result.category} is ${result.solved ? 'solved' : 'open again'}.`);
909
+ }));
910
+ problems
911
+ .command('dismiss <id>')
912
+ .description('Mark a problem a false alarm: it stops counting but stays on its conversation.')
913
+ .option('--never-flag', 'also add a do-not-flag rule written from its category or the problem')
914
+ .option('--undo', 'put a dismissed problem back')
915
+ .action(run(async ({ client, out, project, opts }, id) => {
916
+ const result = await client.action('dismiss_problem', {
917
+ project,
918
+ problem: intArg(id),
919
+ dismissed: !opts.undo,
920
+ add_to_never_flag: Boolean(opts.neverFlag),
921
+ });
922
+ out.result(result, () => `${result.dismissed ? 'Dismissed' : 'Put back'} problem ${result.id} ${result.title}.` +
923
+ (result.never_flag_rule ? `\nAdded do-not-flag rule: ${result.never_flag_rule}` : ''));
924
+ }));
925
+ const rulesRender = (result) => table(result.rules, [
926
+ ['number', '#'],
927
+ ['rule', 'Do not flag', 90],
928
+ ]) || 'No do-not-flag rules.';
929
+ const rules = problems
930
+ .command('rules')
931
+ .description('Do-not-flag rules: behaviour the judge does not report because the team decided it is correct.');
932
+ rules
933
+ .command('list', { isDefault: true })
934
+ .description('List the rules, numbered.')
935
+ .action(run(async ({ client, out, project }) => {
936
+ const result = await client.action('list_never_flag_rules', { project });
937
+ out.result(result, () => rulesRender(result));
938
+ }));
939
+ rules
940
+ .command('add [rule...]')
941
+ .description('Add a rule in your words, or write one from a problem or a problem category.')
942
+ .option('--problem <id>', 'write the rule from this problem')
943
+ .option('--category <id>', 'write the rule from this problem category')
944
+ .action(run(async ({ client, out, project, opts }, words) => {
945
+ const text = (words ?? []).join(' ').trim();
946
+ const result = await client.action('add_never_flag_rule', {
947
+ project,
948
+ rule: text || undefined,
949
+ problem: opts.problem ? intArg(String(opts.problem)) : undefined,
950
+ category: opts.category ? suiteRef(String(opts.category)) : undefined,
951
+ });
952
+ out.result(result, () => `${result.added ? 'Added' : 'Already there'}: ${result.rule}\n\n${rulesRender(result)}`);
953
+ }));
954
+ rules
955
+ .command('remove <number>')
956
+ .description('Remove a rule by its number, so the judge reports that behaviour again.')
957
+ .action(run(async ({ client, out, project }, number) => {
958
+ const result = await client.action('remove_never_flag_rule', {
959
+ project,
960
+ number: intArg(number),
961
+ });
962
+ out.result(result, () => `Removed: ${result.removed}\n\n${rulesRender(result)}`);
963
+ }));
964
+ const traceLines = (trace) => {
965
+ if (!trace)
966
+ return [];
967
+ const short = (value) => {
968
+ const text = typeof value === 'string' ? value : JSON.stringify(value);
969
+ return text === undefined ? '' : text.length > 160 ? `${text.slice(0, 157)}...` : text;
970
+ };
971
+ const calls = (trace.tool_calls ?? trace.agent_reported_steps ?? []);
972
+ return [
973
+ ...calls.map((call) => ` tool ${call.name}(${short(call.arguments)}) -> ${short(call.output)}`),
974
+ ...(trace.model_calls ?? []).map((name) => ` model call ${name}`),
975
+ ];
976
+ };
977
+ program
978
+ .command('conversation <id>')
979
+ .description("One conversation in full, with its verdict, problems and the agent's traced steps.")
980
+ .option('--no-trace', "leave out the agent's steps")
981
+ .action(run(async ({ client, out, project, opts }, id) => {
982
+ const result = await client.action('get_conversation', { project, conversation: id, include_trace: opts.trace !== false });
983
+ out.result(result, () => [
984
+ ...result.messages.flatMap((message) => [
985
+ `${message.role === 'user' ? 'User ' : 'Agent'} ${message.text}`,
986
+ ...traceLines(message.trace),
987
+ ]),
988
+ '',
989
+ `Verdict: ${result.verdict?.status ?? 'not judged'}`,
990
+ ...result.problems.map((problem) => `\n[${problem.severity}] ${problem.title}\n ${problem.explanation}${problem.suggested_fix ? `\n Fix: ${problem.suggested_fix}` : ''}`),
991
+ ].join('\n'));
992
+ }));
993
+ const gateRunRender = (result) => [
994
+ fields([
995
+ ['Gate run', `#${result.gate_run_number ?? result.org_number} ${result.gate ?? result.release_gate_name ?? ''}`],
996
+ ['Status', result.ended ? `${result.status} (${result.ended === 'timed_out' ? 'past its CI time limit' : 'cancelled'})` : result.status],
997
+ ['Decision', result.decision],
998
+ ['Passing', `${result.pass_percentage ?? 0}% (${result.required_pass_percentage}% required)`],
999
+ ['Tests', `${result.completed_tests ?? 0}/${result.total_tests ?? 0} done`],
1000
+ ]),
1001
+ ...(Array.isArray(result.tests)
1002
+ ? ['', table(result.tests, [['verdict', 'Verdict'], ['test', 'Test', 45], ['run_number', 'Run'], ['problems', 'Problems']])]
1003
+ : []),
1004
+ ...(Array.isArray(result.items)
1005
+ ? ['', table(result.items, [['verdict', 'Verdict'], ['scheduled_test_name', 'Test', 45], ['test_run_number', 'Run'], ['violation_count', 'Problems']])]
1006
+ : []),
1007
+ ].join('\n');
1008
+ const gate = program.command('gate').alias('gates').description('Release gates: a fixed set of tests that decides pass or fail before a deploy.');
1009
+ gate
1010
+ .command('list', { isDefault: true })
1011
+ .description("List the organization's release gates.")
1012
+ .action(run(async ({ client, out }) => {
1013
+ const result = await client.action('list_release_gates');
1014
+ out.result(result, () => table(result.gates, [
1015
+ ['id', 'ID'],
1016
+ ['name', 'Gate', 40],
1017
+ ['tests', 'Tests'],
1018
+ ['required_pass_percentage', 'Pass %'],
1019
+ ['active', 'Active'],
1020
+ ]) || 'No release gates.');
1021
+ }));
1022
+ gate
1023
+ .command('run [gate]')
1024
+ .description("Run a release gate. In CI, set QUALILOOP_GATE_KEY to the gate's deploy key and leave out the gate.")
1025
+ .option('--wait', 'wait for the decision; exit 1 when the gate fails')
1026
+ .option('--ref <ref>', 'what is being released, such as the commit sha')
1027
+ .option('--name <name>', 'a name for this run')
1028
+ .option('--timeout <minutes>', "most minutes to wait (default: the gate's CI time limit)")
1029
+ .action(run(async ({ client, out, opts }, gateRef) => {
1030
+ const key = process.env.QUALILOOP_GATE_KEY;
1031
+ let started;
1032
+ let follow;
1033
+ if (key && !gateRef) {
1034
+ started = await startGateWithKey(client, key, {
1035
+ name: opts.name ?? 'CI run',
1036
+ external_ref: opts.ref,
1037
+ });
1038
+ follow = (minutes) => waitForGateRunWithKey(client, key, Number(started.id), {
1039
+ timeoutMinutes: minutes,
1040
+ onProgress: (message) => out.progress(message),
1041
+ });
1042
+ }
1043
+ else {
1044
+ if (!gateRef)
1045
+ throw new ApiError('Name the gate, or set QUALILOOP_GATE_KEY in CI.', 400, EXIT.usage);
1046
+ started = await client.action('run_release_gate', {
1047
+ gate: /^\d+$/.test(gateRef) ? Number(gateRef) : gateRef,
1048
+ name: opts.name,
1049
+ external_ref: opts.ref,
1050
+ });
1051
+ follow = (minutes) => waitForGateRun(client, Number(started.gate_run_number), {
1052
+ timeoutMinutes: minutes,
1053
+ onProgress: (message) => out.progress(message),
1054
+ });
1055
+ }
1056
+ const number = started.gate_run_number ?? started.org_number;
1057
+ if (!opts.wait) {
1058
+ out.result(started, () => `Started gate run #${number}. Follow it: qualiloop gate show ${number}`);
1059
+ return EXIT.ok;
1060
+ }
1061
+ const minutes = opts.timeout ? intArg(String(opts.timeout)) : (started.ci_timeout_minutes ?? 60);
1062
+ out.progress(`Started gate run #${number}. Waiting up to ${minutes} minutes for the decision...`);
1063
+ const finished = await follow(minutes);
1064
+ out.result(finished, () => `${gateRunRender(finished)}\n\nGate ${finished.decision === 'pass' ? 'passed' : 'failed'}.`);
1065
+ return finished.decision === 'pass' ? EXIT.ok : EXIT.failed;
1066
+ }));
1067
+ gate
1068
+ .command('runs')
1069
+ .description('Recent gate runs, newest first.')
1070
+ .addOption(limitOption('gate runs', '20', 200))
1071
+ .action(run(async ({ client, out, opts }) => {
1072
+ const result = await client.action('list_gate_runs', {
1073
+ limit: limitOf(opts, 200),
1074
+ });
1075
+ out.result(result, () => listed(table(result.gate_runs, [
1076
+ ['gate_run_number', 'Run'],
1077
+ ['gate', 'Gate', 30],
1078
+ ['name', 'Name', 30],
1079
+ ['status', 'Status'],
1080
+ ['decision', 'Decision'],
1081
+ ['pass_percentage', 'Pass %'],
1082
+ ['external_ref', 'Ref', 14],
1083
+ ]), result.gate_runs.length, result.total, 'No gate runs yet.'));
1084
+ }));
1085
+ gate
1086
+ .command('show <gate-run>')
1087
+ .description('One gate run: decision and each test.')
1088
+ .action(run(async ({ client, out }, number) => {
1089
+ const result = await client.action('get_gate_run', { gate_run_number: intArg(number) });
1090
+ out.result(result, () => gateRunRender(result));
1091
+ }));
1092
+ gate
1093
+ .command('cancel <gate-run>')
1094
+ .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.')
1095
+ .action(run(async ({ client, out }, number) => {
1096
+ const result = await client.action('cancel_gate_run', { gate_run_number: intArg(number) });
1097
+ out.result(result, () => `Cancelled gate run #${result.gate_run_number}: CI treats it as not passed.`);
1098
+ }));
1099
+ const generate = program
1100
+ .command('generate')
1101
+ .description('Have QualiLoop write tests from one prompt.')
1102
+ .argument('[prompt...]', 'what to test, in plain words')
1103
+ .option('--suite <suite>', 'add the tests to this suite (id or name)')
1104
+ .option('--new-suite <name>', 'make a new suite for them')
1105
+ .option('--max <n>', 'most tests to write')
1106
+ .option('--wait', 'wait until the tests are saved')
1107
+ .option('--timeout <minutes>', 'most minutes to wait', '15')
1108
+ .action(run(async ({ client, out, project, opts }, words = []) => {
1109
+ if (!words.length)
1110
+ throw new ApiError('Say what to test: qualiloop generate "refund requests"', 400, EXIT.usage);
1111
+ const started = await startGeneration(client, {
1112
+ project,
1113
+ prompt: words.join(' '),
1114
+ suite: opts.suite,
1115
+ newSuite: opts.newSuite,
1116
+ max: opts.max ? intArg(String(opts.max)) : undefined,
1117
+ });
1118
+ if (!opts.wait) {
1119
+ out.result(started, () => `Generating tests (generation ${started.id}). Follow it: qualiloop generate status ${started.id}`);
1120
+ return EXIT.ok;
1121
+ }
1122
+ const finished = await waitForGeneration(client, Number(started.id), {
1123
+ timeoutMinutes: intArg(String(opts.timeout)),
1124
+ onProgress: (message) => out.progress(message),
1125
+ });
1126
+ const saved = finished.saved_test_ids ?? [];
1127
+ out.result(finished, () => finished.status === 'completed'
1128
+ ? `Saved ${saved.length} test(s): ${saved.join(', ') || 'none'}${finished.suite_name ? ` in ${finished.suite_name}` : ''}.
1129
+ Run them: qualiloop run ${saved.join(' ')}`
1130
+ : `Generation ${finished.status}${finished.error_message ? `: ${finished.error_message}` : ''}.`);
1131
+ return finished.status === 'completed' ? EXIT.ok : EXIT.failed;
1132
+ }));
1133
+ generate
1134
+ .command('status <id>')
1135
+ .description('Where a generation stands.')
1136
+ .action(run(async ({ client, out }, id) => {
1137
+ const result = await getGeneration(client, intArg(id));
1138
+ out.result(result, () => fields([
1139
+ ['Generation', `${result.id} ${result.status}`],
1140
+ ['Step', result.step_label ?? result.step],
1141
+ ['Written', `${result.written ?? 0}/${result.planned ?? '-'}`],
1142
+ ['Saved tests', result.saved_test_ids],
1143
+ ['Suite', result.suite_name],
1144
+ ['Error', result.error_message],
1145
+ ]));
1146
+ }));
1147
+ generate
1148
+ .command('cancel <id>')
1149
+ .description('Stop a generation that is still running. Nothing is saved.')
1150
+ .action(run(async ({ client, out }, id) => {
1151
+ const result = await cancelGeneration(client, intArg(id));
1152
+ out.result(result, () => result.status === 'cancelled'
1153
+ ? `Generation ${result.id} is cancelled. Nothing was saved.`
1154
+ : result.finished
1155
+ ? `Generation ${result.id} had already finished (${result.status}); nothing to cancel.`
1156
+ : `Cancelling generation ${result.id}. It stops at its next step and saves nothing: qualiloop generate status ${result.id}`);
1157
+ }));
1158
+ const connectCommand = program
1159
+ .command('connect')
1160
+ .argument('[project]', 'the project: its number or name')
1161
+ .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.')
1162
+ .addHelpText('after', `
1163
+ Start here:
1164
+ npx qualiloop connect 12 run in the agent's folder: signs in through the
1165
+ browser if needed, makes project 12 the default,
1166
+ writes the project key and traces address into
1167
+ .env, and prints the steps a coding agent follows
1168
+ qualiloop connect guide the steps alone
1169
+
1170
+ Project:
1171
+ With QUALILOOP_SETUP_TOKEN set, every command uses that token and its own
1172
+ project (-p only for a project the token created). Otherwise they use your
1173
+ sign-in, on the project named by the argument, -p, QUALILOOP_PROJECT or
1174
+ qualiloop projects use; with none named they stop. qualiloop connect alone
1175
+ creates a project only when you have none. Each command prints the project
1176
+ it acted on.
1177
+ `)
1178
+ .action(run(async (ctx, given) => {
1179
+ const { client, out } = ctx;
1180
+ if (!process.env.QUALILOOP_SETUP_TOKEN && !client.isSignedIn()) {
1181
+ out.progress(signedInAs(await browserLogin(client, out, true)));
1182
+ }
1183
+ const result = await connect.start(client, {
1184
+ project: given ?? ctx.opts.project,
1185
+ dir: process.cwd(),
1186
+ file: '.env',
1187
+ ask: (projects) => [
1188
+ `Name the project to connect: ${invocation()} connect <number>`,
1189
+ ...projects.map((item) => ` #${item.number} ${item.name}`),
1190
+ ].join('\n'),
1191
+ });
1192
+ let guide = null;
1193
+ let guideError = null;
1194
+ try {
1195
+ guide = await connect.skill(client);
1196
+ }
1197
+ catch (error) {
1198
+ guideError = `${error instanceof Error ? error.message : String(error)} Print the steps later with: ${invocation()} connect guide`;
1199
+ }
1200
+ const install = viaNpx() ? 'To use qualiloop directly: npm install -g qualiloop' : null;
1201
+ const mcp = viaNpx()
1202
+ ? 'Using Claude Desktop, Cursor or VS Code? After installing, run: qualiloop mcp install'
1203
+ : 'Using Claude Desktop, Cursor or VS Code? Run: qualiloop mcp install';
1204
+ out.result({ ...result, guide, guide_error: guideError, install, mcp }, () => [
1205
+ `Project #${result.project.number} ${result.project.name}` +
1206
+ (result.created ? ' (created: you had no project, so it is named after this codebase)' : ''),
1207
+ ...(result.default_set ? [`Commands now use project #${result.project.number}.`] : []),
1208
+ [
1209
+ `Wrote ${result.env.written.join(' and ')} to ${result.env.file}.`,
1210
+ connect.gitNote(result.env.file, result.env.git_ignored),
1211
+ ]
1212
+ .filter(Boolean)
1213
+ .join(' '),
1214
+ '',
1215
+ guide
1216
+ ? `Next, follow these steps.\n\n${guide.text.trimEnd()}\n\n(From ${guide.url}. The code for each step: ${guide.reference_url})`
1217
+ : String(guideError),
1218
+ ...(install ? ['', install] : []),
1219
+ '',
1220
+ mcp,
1221
+ ].join('\n'));
1222
+ }));
1223
+ const connectProject = (ctx) => ctx.opts.project;
1224
+ const actedOn = (result, text) => result.project ? `Project #${result.project.number} ${result.project.name}\n${text}` : text;
1225
+ connectCommand
1226
+ .command('guide')
1227
+ .description('Print the connect skill from QualiLoop (/connect/SKILL.md): the steps a coding agent follows.')
1228
+ .action(run(async ({ client, out }) => {
1229
+ const result = await connect.skill(client);
1230
+ out.result(result, () => `${result.text.trimEnd()}\n\n(From ${result.url}. The code for each step: ${result.reference_url})`);
1231
+ }));
1232
+ connectCommand
1233
+ .command('info')
1234
+ .description('What the agent needs: request contract, traces address, saved endpoint (key masked).')
1235
+ .action(run(async (ctx) => {
1236
+ const result = await connect.info(ctx.client, { project: connectProject(ctx) });
1237
+ ctx.out.result(result, () => [
1238
+ fields([
1239
+ ['Project', `#${result.project.number} ${result.project.name}`],
1240
+ ['Traces address', result.tracing.traces_url],
1241
+ ['Project key', `${result.tracing.project_key} (write it with: qualiloop connect env)`],
1242
+ ['Saved endpoint', result.target ? result.target.base_url : 'none yet'],
1243
+ ['Live traffic', result.project.live_data_enabled],
1244
+ ['QualiLoop calls from', result.outbound_addresses],
1245
+ ]),
1246
+ '',
1247
+ 'Request contract:',
1248
+ JSON.stringify(result.request_contract, null, 2),
1249
+ ].join('\n'));
1250
+ }));
1251
+ connectCommand
1252
+ .command('projects')
1253
+ .description('The projects you can connect agents to.')
1254
+ .action(run(async ({ client, out }) => {
1255
+ const result = await connect.projects(client);
1256
+ out.result(result, () => table(result.projects, [
1257
+ ['number', '#'],
1258
+ ['agent', 'Agent', 40],
1259
+ ['environment', 'Environment'],
1260
+ ]));
1261
+ }));
1262
+ connectCommand
1263
+ .command('env')
1264
+ .description("Write the project key and traces address into an env file (values not printed).")
1265
+ .option('--file <path>', 'the env file', '.env')
1266
+ .option('--suffix <name>', 'for a second agent: TRIAGE gives QUALILOOP_PROJECT_KEY_TRIAGE')
1267
+ .action(run(async (ctx) => {
1268
+ const result = await connect.writeEnv(ctx.client, {
1269
+ project: connectProject(ctx),
1270
+ file: String(ctx.opts.file),
1271
+ suffix: ctx.opts.suffix,
1272
+ });
1273
+ ctx.out.result(result, () => actedOn(result, [`Wrote ${result.written.join(' and ')} to ${result.file}.`, connect.gitNote(result.file, result.git_ignored)]
1274
+ .filter(Boolean)
1275
+ .join(' ')));
1276
+ }));
1277
+ connectCommand
1278
+ .command('create-project <name>')
1279
+ .description('Create a project for another agent or environment (admins).')
1280
+ .addOption(new Option('--environment <env>').choices(['local', 'dev', 'staging', 'prod']))
1281
+ .option('--description <text>')
1282
+ .action(run(async (ctx, name) => {
1283
+ const result = await connect.createProject(ctx.client, {
1284
+ name,
1285
+ environment: ctx.opts.environment,
1286
+ description: ctx.opts.description,
1287
+ });
1288
+ ctx.out.result(result, () => `Created project #${result.project.number} ${result.project.name}.`);
1289
+ }));
1290
+ connectCommand
1291
+ .command('rename')
1292
+ .description("Rename the project, describe it, or name its environment.")
1293
+ .option('--name <name>')
1294
+ .option('--description <text>')
1295
+ .addOption(new Option('--environment <env>').choices(['local', 'dev', 'staging', 'prod']))
1296
+ .action(run(async (ctx) => {
1297
+ const result = await connect.updateProject(ctx.client, { project: connectProject(ctx) }, {
1298
+ name: ctx.opts.name,
1299
+ description: ctx.opts.description,
1300
+ environment: ctx.opts.environment,
1301
+ });
1302
+ ctx.out.result(result, () => actedOn(result, 'Project updated.'));
1303
+ }));
1304
+ connectCommand
1305
+ .command('target')
1306
+ .description('Save the endpoint QualiLoop calls, from a JSON file (or - for stdin).')
1307
+ .requiredOption('--file <path>', 'the body of PUT /v1/setup/target')
1308
+ .option('--auth-header <Name=VARIABLE>', 'send header Name with the value of VARIABLE, read from the environment or --env-file')
1309
+ .option('--auth-prefix <prefix>', 'put this before the value, such as "Bearer "')
1310
+ .option('--env-file <path>', 'where to read VARIABLE when the environment lacks it', '.env')
1311
+ .action(run(async (ctx) => {
1312
+ const body = connect.readJson(String(ctx.opts.file));
1313
+ if (ctx.opts.authHeader) {
1314
+ const [name, variable] = String(ctx.opts.authHeader).split('=');
1315
+ if (!name || !variable)
1316
+ throw new ApiError('--auth-header takes Name=VARIABLE.', 400, EXIT.usage);
1317
+ body.auth_header_name = name;
1318
+ body.auth_header_env = variable;
1319
+ body.auth_header_prefix = ctx.opts.authPrefix;
1320
+ body.env_file = String(ctx.opts.envFile);
1321
+ }
1322
+ const result = await connect.saveTarget(ctx.client, { project: connectProject(ctx) }, body);
1323
+ ctx.out.result(result, () => actedOn(result, `Saved the endpoint ${String(result.target?.base_url ?? '')}.`));
1324
+ }));
1325
+ connectCommand
1326
+ .command('knowledge')
1327
+ .alias('context')
1328
+ .description("Fill the agent's system knowledge: its system prompts, tools, documentation and General, from a JSON file.")
1329
+ .requiredOption('--file <path>', 'the body of PUT /v1/setup/knowledge (or - for stdin)')
1330
+ .option('--overwrite', "write General over what is there; only when the user asked for it")
1331
+ .action(run(async (ctx) => {
1332
+ const result = await connect.saveKnowledge(ctx.client, { project: connectProject(ctx) }, connect.readJson(String(ctx.opts.file)), Boolean(ctx.opts.overwrite));
1333
+ ctx.out.result(result, () => actedOn(result, connect.knowledgeRender(result)));
1334
+ }));
1335
+ connectCommand
1336
+ .command('trace-fields', { hidden: true })
1337
+ .option('--file <path>')
1338
+ .action(run(async ({ out }) => {
1339
+ out.result({ status: 'no_longer_needed', detail: connect.TRACE_FIELDS_GONE }, () => connect.TRACE_FIELDS_GONE);
1340
+ }));
1341
+ connectCommand
1342
+ .command('live <on|off>')
1343
+ .description("Turn the project's live traffic on or off (admins). It sends real users' data.")
1344
+ .action(run(async (ctx, state) => {
1345
+ if (!['on', 'off'].includes(state))
1346
+ throw new ApiError('Say on or off.', 400, EXIT.usage);
1347
+ const result = await connect.setLive(ctx.client, { project: connectProject(ctx) }, { enabled: state === 'on' });
1348
+ ctx.out.result(result, () => actedOn(result, `Live traffic is ${result.live_data_enabled ? 'on' : 'off'}.`));
1349
+ }));
1350
+ const checkRender = (result) => {
1351
+ const items = (result.items ?? result.checks);
1352
+ const lines = [`ok: ${result.ok ? 'yes' : 'no'}`];
1353
+ if (Array.isArray(items)) {
1354
+ for (const item of items)
1355
+ lines.push(`${item.ok ? 'pass' : item.required === false ? 'want' : 'FAIL'} ${item.key ?? item.name} ${item.message ?? item.detail ?? ''}`);
1356
+ }
1357
+ return lines.join('\n');
1358
+ };
1359
+ connectCommand
1360
+ .command('check-traces <session-id>')
1361
+ .description('Check QualiLoop tracing from one session you produced on this machine.')
1362
+ .action(run(async (ctx, session) => {
1363
+ const result = await connect.checkTraces(ctx.client, { project: connectProject(ctx) }, session);
1364
+ ctx.out.result(result, () => actedOn(result, checkRender(result)));
1365
+ return result.ok ? EXIT.ok : EXIT.failed;
1366
+ }));
1367
+ connectCommand
1368
+ .command('check')
1369
+ .description('Send one real test message to the saved endpoint and report what arrived.')
1370
+ .action(run(async (ctx) => {
1371
+ ctx.out.progress('Sending one test message; this can take up to a minute...');
1372
+ const result = await connect.check(ctx.client, { project: connectProject(ctx) });
1373
+ ctx.out.result(result, () => actedOn(result, checkRender(result)));
1374
+ return result.ok ? EXIT.ok : EXIT.failed;
1375
+ }));
1376
+ connectCommand
1377
+ .command('disconnect')
1378
+ .description('Forget the saved endpoint and turn live data off. Past results stay.')
1379
+ .action(run(async (ctx) => {
1380
+ const result = await connect.disconnect(ctx.client, { project: connectProject(ctx) });
1381
+ ctx.out.result(result, () => actedOn(result, 'Disconnected.'));
1382
+ }));
1383
+ const mcp = program
1384
+ .command('mcp')
1385
+ .description('Run the QualiLoop MCP server over stdio, for chat apps and agents that cannot run commands. It uses your qualiloop login.')
1386
+ .action(async (_options, command) => {
1387
+ const opts = command.optsWithGlobals();
1388
+ await serveStdio(new QualiloopClient({ url: opts.url }));
1389
+ });
1390
+ mcp
1391
+ .command('install')
1392
+ .description('Add the MCP server to Claude Desktop, or to the clients given with --client.')
1393
+ .addOption(new Option('--client <client...>', 'which clients; all for every one')
1394
+ .choices([...CLIENTS, 'all'])
1395
+ .default(DEFAULT_CLIENTS))
1396
+ .addOption(new Option('--scope <scope>', 'for you everywhere, or for this project only').choices(['user', 'project']).default('user'))
1397
+ .option('--print', 'print the configuration to paste instead of writing it (every client, or those of --client)')
1398
+ .action(run(async ({ client, out, opts, command }) => {
1399
+ const chosen = opts.client.includes('all') ? [...CLIENTS] : opts.client;
1400
+ if (opts.print) {
1401
+ const given = command.getOptionValueSource('client') !== 'default';
1402
+ const text = snippets(client.url, given ? chosen : CLIENTS);
1403
+ out.result({ snippets: text }, () => text);
1404
+ return EXIT.ok;
1405
+ }
1406
+ const results = install(chosen, { scope: opts.scope, url: client.url });
1407
+ out.result(results, () => [
1408
+ ...results.map((item) => `${item.done ? 'Added to' : 'Not added to'} ${item.client}: ${item.where}`),
1409
+ '',
1410
+ client.isSignedIn() ? 'Restart the agent to load it.' : 'Sign in first: qualiloop login. Then restart the agent.',
1411
+ ].join('\n'));
1412
+ return results.every((item) => item.done) ? EXIT.ok : EXIT.failed;
1413
+ }));
1414
+ program
1415
+ .command('guide')
1416
+ .description('How to use QualiLoop well: the guide the MCP server gives agents as its instructions.')
1417
+ .action(run(async ({ out }) => {
1418
+ const guide = bundledGuide();
1419
+ out.result({ guide }, () => guide);
1420
+ }));
1421
+ program
1422
+ .command('actions')
1423
+ .description('List the actions you may run, as the MCP server offers them.')
1424
+ .action(run(async ({ client, out }) => {
1425
+ const catalog = await loadCatalog(client);
1426
+ out.result(catalog, () => table(catalog.map((item) => ({ ...item, kind: item.read_only ? 'read' : 'write' })), [
1427
+ ['name', 'Action', 26],
1428
+ ['kind', 'Kind'],
1429
+ ['cli', 'Command', 60],
1430
+ ]));
1431
+ }));
1432
+ program
1433
+ .command('action <name>')
1434
+ .description('Run one action with JSON arguments, as the MCP server would: qualiloop action list_runs --args \'{"limit": 5}\'')
1435
+ .option('--args <json>', 'the arguments as a JSON object', '{}')
1436
+ .action(run(async ({ client, out, project, opts }, name) => {
1437
+ let args;
1438
+ try {
1439
+ args = JSON.parse(String(opts.args ?? '{}'));
1440
+ }
1441
+ catch {
1442
+ throw new ApiError('--args must be a JSON object.', 400, EXIT.usage);
1443
+ }
1444
+ const spec = bundledCatalog().find((item) => item.name === name) ??
1445
+ (await loadCatalog(client)).find((item) => item.name === name);
1446
+ const properties = (spec?.input_schema.properties ?? {});
1447
+ if ('project' in properties && args.project === undefined && project !== undefined)
1448
+ args.project = project;
1449
+ const result = await client.action(name, args);
1450
+ out.result(result, () => JSON.stringify(result, null, 2));
1451
+ }));
1452
+ const urlArg = (args) => {
1453
+ const index = args.indexOf('--url');
1454
+ if (index >= 0)
1455
+ return args[index + 1];
1456
+ return args.find((arg) => arg.startsWith('--url='))?.slice('--url='.length);
1457
+ };
1458
+ const showKnowledgeAdminCommands = async (args) => {
1459
+ if (!args.includes('knowledge') || !args.some((arg) => arg === '--help' || arg === '-h' || arg === 'help')) {
1460
+ return;
1461
+ }
1462
+ const catalog = await loadCatalog(new QualiloopClient({ url: urlArg(args), kind: 'cli' }));
1463
+ const names = new Set(catalog.map((item) => item.name));
1464
+ for (const [command, action] of Object.entries(SUPER_ADMIN_KNOWLEDGE)) {
1465
+ if (names.has(action))
1466
+ knowledgeAdminShown.add(command);
1467
+ }
1468
+ };
1469
+ export const main = async (argv = process.argv) => {
1470
+ await showKnowledgeAdminCommands(argv.slice(2));
1471
+ await program.parseAsync(argv);
1472
+ };
1473
+ main().catch((error) => {
1474
+ if (error instanceof CommanderError) {
1475
+ process.exitCode = error.exitCode === 0 ? EXIT.ok : EXIT.usage;
1476
+ return;
1477
+ }
1478
+ process.stderr.write(`qualiloop: ${error instanceof Error ? error.message : String(error)}\n`);
1479
+ process.exitCode = EXIT.server;
1480
+ });