qualiloop 0.1.0 → 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/dist/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'node:fs';
2
+ import { readFileSync, writeFileSync } from 'node:fs';
3
+ import { basename, resolve as resolvePath } from 'node:path';
3
4
  import { createInterface } from 'node:readline/promises';
4
5
  import { Command, CommanderError, Help, Option } from 'commander';
5
6
  import { ApiError, EXIT, QualiloopClient, VERSION } from './api.js';
@@ -7,6 +8,7 @@ import { login } from './auth.js';
7
8
  import { bundledCatalog, bundledGuide, loadCatalog } from './catalog.js';
8
9
  import { credentialsPath, forgetCredentials, resolveProject, setDefaultProject, storedCredentials, } from './config.js';
9
10
  import * as connect from './connect.js';
11
+ import { EXPORT_FORMATS, dateOr, exportFormat, fetchCorrectedPairs } from './export.js';
10
12
  import { CLIENTS, DEFAULT_CLIENTS, install, snippets } from './mcp/install.js';
11
13
  import { serveStdio } from './mcp/server.js';
12
14
  import { fields, output, table } from './output.js';
@@ -92,6 +94,14 @@ const intArg = (value) => {
92
94
  throw new ApiError(`${value} is not a number.`, 400, EXIT.usage);
93
95
  return parsed;
94
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
+ };
95
105
  const limitOption = (what, fallback, most) => new Option('--limit <n>', `most ${what} to show (up to ${most})`).default(fallback);
96
106
  const limitOf = (opts, most) => {
97
107
  const limit = intArg(String(opts.limit));
@@ -129,10 +139,11 @@ const failOnOption = () => new Option('--fail-on <severity>', 'with --wait, exit
129
139
  .default('major');
130
140
  const browserLogin = (client, out, browser) => login(client, {
131
141
  browser,
132
- onStarted: ({ url, code, opened }) => {
142
+ onStarted: ({ url, code, opened, expiresIn }) => {
133
143
  out.progress(`${opened ? 'Opened' : 'Open'} ${url}\n` +
134
144
  `Check that the page shows ${code}, then approve. No account yet? Create one from that page.`);
135
- out.progress('Waiting for approval...');
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...`);
136
147
  },
137
148
  });
138
149
  const signedInAs = (result) => `Signed in to ${result.url} as ${result.user?.email ?? 'you'}` +
@@ -241,6 +252,110 @@ projects
241
252
  setDefaultProject(client.url, String(result.number));
242
253
  out.result({ project: result.number, name: result.name }, () => `Commands now use project #${result.number} ${result.name}.`);
243
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
+ }));
244
359
  const knowledge = program
245
360
  .command('knowledge')
246
361
  .description('System knowledge: what QualiLoop knows of the agent, its coverage, and exploring it.');
@@ -265,7 +380,7 @@ knowledge
265
380
  out.result(result, () => [
266
381
  fields([
267
382
  ['Project', result.project],
268
- ['Coverage', result.coverage ? `${result.coverage.percent}% (${result.coverage.covered}/${result.coverage.total})` : '-'],
383
+ ['Coverage', result.coverage && result.coverage.percent != null ? `${result.coverage.percent}% (${result.coverage.covered}/${result.coverage.total})` : 'not measured yet'],
269
384
  ['Sources', sources.length ? sources.map((row) => row.name).join(', ') : 'none (qualiloop connect knowledge)'],
270
385
  ['Exploring now', result.exploring],
271
386
  ['Link', result.url],
@@ -372,7 +487,7 @@ knowledge
372
487
  }));
373
488
  knowledge
374
489
  .command('explore')
375
- .description('Explore the agent: 3 rounds of up to 8 conversations, up to 24 conversation credits, not judged.')
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.")
376
491
  .option('--note <text>', 'what to look at more closely')
377
492
  .action(run(async (ctx) => {
378
493
  const { client, out, project, opts } = ctx;
@@ -380,7 +495,11 @@ knowledge
380
495
  project,
381
496
  note: opts.note,
382
497
  });
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)}`);
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)}`);
384
503
  }));
385
504
  knowledge
386
505
  .command('explorations')
@@ -436,12 +555,28 @@ knowledge
436
555
  .command('source <id>')
437
556
  .description('One source: its current text, versions, and what it states.')
438
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')
439
560
  .action(run(async ({ client, out, project, opts }, id) => {
440
561
  const result = await client.action('get_source', {
441
562
  project,
442
563
  source: intArg(id),
443
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)),
444
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
+ ];
445
580
  out.result(result, () => [
446
581
  fields([
447
582
  ['Source', `${result.id} ${result.name}`],
@@ -451,12 +586,12 @@ knowledge
451
586
  ['Agent', result.component],
452
587
  ['Placeholders', result.placeholders],
453
588
  ['Seen at steps', result.trace_steps],
454
- ['Versions', result.versions.length],
589
+ ['Versions', result.versions.map((row) => row.number).join(', ')],
455
590
  ['Link', result.url],
456
591
  ]),
457
592
  '',
458
- String(result.text ?? ''),
459
- ...(result.text_cut ? [`\n(${result.text_chars} characters; more with --max-chars)`] : []),
593
+ ...shown,
594
+ ...body,
460
595
  ...(result.states.length
461
596
  ? ['', table(result.states, [['node_id', 'Item'], ['section', 'Section'], ['name', 'It states', 60]])]
462
597
  : []),
@@ -464,27 +599,130 @@ knowledge
464
599
  }));
465
600
  knowledge
466
601
  .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).')
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).')
468
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']))
469
606
  .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 });
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
+ });
479
614
  out.result(result, () => `Saved ${result.source.name} as source ${result.source.id}, version ${result.source.version}.` +
480
615
  (result.fill_queued || result.change_queued ? ' QualiLoop reads it into the system knowledge.' : ''));
481
616
  }));
482
617
  knowledge
483
618
  .command('retire-source <id>')
484
619
  .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) => {
620
+ .action(run(async (ctx, id) => {
621
+ const { client, out, project } = ctx;
486
622
  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.`);
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}.`);
488
726
  }));
489
727
  program
490
728
  .command('change <description...>')
@@ -502,6 +740,7 @@ const testColumns = [
502
740
  ['id', 'ID'],
503
741
  ['name', 'Name', 45],
504
742
  ['mode', 'Mode'],
743
+ ['category', 'Category', 25],
505
744
  ['last', 'Last run'],
506
745
  ['suites', 'Suites'],
507
746
  ];
@@ -515,15 +754,29 @@ tests
515
754
  .description('List the saved tests of the project.')
516
755
  .option('--suite <suite>', 'only the tests of this suite (id or name)')
517
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']))
518
762
  .addOption(limitOption('tests', '100', 1000))
519
763
  .action(run(async ({ client, out, project, opts }) => {
520
764
  const result = await client.action('list_tests', {
521
765
  project,
522
766
  suite: opts.suite,
523
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,
524
772
  limit: limitOf(opts, 1000),
525
773
  });
526
- out.result(result, () => listed(table(result.tests.map((row) => ({ ...row, last: lastRun(row) })), testColumns), result.tests.length, result.total, 'No tests.'));
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.'));
527
780
  }));
528
781
  tests
529
782
  .command('show <id>')
@@ -533,29 +786,92 @@ tests
533
786
  out.result(result, () => fields([
534
787
  ['Test', `${result.id} ${result.name}`],
535
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]] : []),
536
794
  ['Instructions', result.instructions],
537
795
  ['Persona', result.persona],
538
796
  ['Steps', result.steps],
797
+ ...(result.send_steps_literally ? [['Steps sent', 'exactly as written']] : []),
539
798
  ['Turns', result.max_turns],
540
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
+ : []),
541
813
  ['Suites', result.suites],
542
814
  ['Last run', lastRun(result)],
543
815
  ]));
544
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
+ };
545
835
  const testFieldOptions = (command) => command
546
836
  .option('--instructions <text>', 'what the simulated user wants and how they behave')
547
837
  .option('--persona <text>', 'who the simulated user is')
548
- .option('--step <text>', 'a scripted step, in order (repeat)', (value, all = []) => [...all, value])
838
+ .option('--step <text>', 'a scripted step, in order (repeat)', repeat)
549
839
  .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');
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
+ });
552
868
  testFieldOptions(tests
553
869
  .command('create')
554
870
  .description('Write a new saved test.')
555
871
  .requiredOption('--name <name>', 'a short name for the test'))
556
872
  .option('--red-team <attack>', 'make it an attack of this type (prompt_injection, jailbreak, data_leak, ...)')
557
873
  .option('--single', 'one message per prompt instead of a conversation')
558
- .option('--suite <suite>', 'add it to this suite (repeat)', (value, all = []) => [...all, value])
874
+ .option('--suite <suite>', 'add it to this suite (repeat)', repeat)
559
875
  .action(run(async (ctx) => {
560
876
  const { client, out, project, opts } = ctx;
561
877
  if (!opts.instructions)
@@ -563,13 +879,9 @@ testFieldOptions(tests
563
879
  const result = await client.action('create_test', {
564
880
  project,
565
881
  name: opts.name,
566
- instructions: opts.instructions,
567
- persona: opts.persona,
882
+ ...testFields(opts),
568
883
  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',
884
+ mode: opts.redTeam ? 'red_team' : opts.bias ? 'bias' : 'regular',
573
885
  attack_type: opts.redTeam,
574
886
  shape: opts.single ? 'single' : 'conversation',
575
887
  suites: opts.suite,
@@ -592,26 +904,83 @@ tests
592
904
  const result = await client.action('delete_test', { project, test });
593
905
  out.result(result, () => `Deleted test ${result.id} ${result.name}.`);
594
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
+ }));
595
921
  testFieldOptions(tests.command('edit <id>').description('Change a saved test; only what you give changes.').option('--name <name>', 'a new name'))
596
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')
597
927
  .action(run(async ({ client, out, project, opts }, id) => {
598
928
  const result = await client.action('update_test', {
599
929
  project,
600
930
  test: intArg(id),
601
931
  name: opts.name,
602
- instructions: opts.instructions,
603
- persona: opts.persona,
932
+ ...testFields(opts),
604
933
  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,
934
+ mode: opts.redTeam ? 'red_team' : opts.bias ? 'bias' : opts.regular ? 'regular' : undefined,
935
+ attack_type: opts.redTeam,
936
+ shape: opts.shape,
608
937
  });
609
938
  out.result(result, () => `Updated test ${result.id}: ${result.updated.join(', ')}.`);
610
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
+ }));
611
978
  const launched = async (ctx, result) => {
612
979
  const { out, project, opts } = ctx;
613
- for (const item of result.failed)
614
- out.progress(`Test ${item.test_id} did not start: ${item.reason}`);
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
+ }
615
984
  if (!result.batch_id || !result.started.length) {
616
985
  out.result(result, () => 'Nothing started.');
617
986
  return EXIT.failed;
@@ -665,10 +1034,19 @@ const waitOptions = (command, waitFlag = true) => {
665
1034
  return command.addOption(failOnOption()).option('--timeout <minutes>', 'most minutes to wait', '60');
666
1035
  };
667
1036
  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 });
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
+ });
672
1050
  return launched(ctx, result);
673
1051
  }));
674
1052
  const suites = program.command('suites').description('Suites of saved tests.');
@@ -718,6 +1096,20 @@ suites
718
1096
  out.result(result, () => `Added ${result.added} test(s) to suite ${result.suite.id} ${result.suite.name}` +
719
1097
  (Number(result.added) < ids.length ? '; the others were in it already.' : '.'));
720
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
+ }));
721
1113
  waitOptions(suites.command('run <suite>').description('Run every test of a suite (id, name, or core).')).action(run(async (ctx, suite) => {
722
1114
  const result = await ctx.client.action('run_suite', { project: ctx.project, suite: suiteRef(suite) });
723
1115
  return launched(ctx, result);
@@ -746,45 +1138,134 @@ suites
746
1138
  out.result(result, () => `Deleted suite ${result.id} ${result.name}` + (result.tests_deleted ? ` and its ${result.tests} test(s).` : '.'));
747
1139
  }));
748
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
+ };
749
1158
  runs
750
1159
  .command('list', { isDefault: true })
751
- .description('Recent runs, newest first.')
1160
+ .description('Recent runs, newest first, filtered as Test Results filters them.')
752
1161
  .option('--batch <id>', 'only the runs of one launch')
753
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')
754
1172
  .addOption(limitOption('runs', '20', 500))
1173
+ .addOption(offsetOption())
755
1174
  .action(run(async ({ client, out, project, opts }) => {
1175
+ const offset = offsetOf(opts);
756
1176
  const result = await client.action('list_runs', {
757
1177
  project,
758
1178
  batch: opts.batch,
759
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,
760
1189
  limit: limitOf(opts, 500),
1190
+ offset,
761
1191
  });
762
- out.result(result, () => listed(table(result.runs, [
1192
+ out.result(result, () => paged(table(result.runs, [
763
1193
  ['run_number', 'Run'],
764
1194
  ['name', 'Test', 40],
1195
+ ['mode', 'Mode'],
765
1196
  ['status_label', 'Status'],
766
1197
  ['outcome', 'Outcome'],
767
1198
  ['major_problems', 'Major'],
768
1199
  ['minor_problems', 'Minor'],
769
- ]), result.runs.length, result.total, 'No runs.'));
1200
+ ]), result.runs.length, result.total, offset, 'No runs.'));
770
1201
  }));
771
1202
  runs
772
1203
  .command('show <run>')
773
- .description('One run: status, outcome and problems found.')
1204
+ .description('One run: status, outcome, problems found and quality scores.')
774
1205
  .action(run(async ({ client, out, project }, number) => {
775
- const result = await client.action('get_run', { project, run_number: intArg(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);
776
1212
  out.result(result, () => fields([
777
1213
  ['Run', `#${result.run_number} ${result.name}`],
778
1214
  ['Status', result.status_label],
779
1215
  ['Outcome', result.outcome],
780
1216
  ['Passed', result.test_passed],
1217
+ ['Summary', summary?.headline],
781
1218
  ['Conversations', result.conversations],
1219
+ ['Not reviewed', summary?.unjudged_conversations],
782
1220
  ['Major problems', result.major_problems],
783
1221
  ['Minor problems', result.minor_problems],
1222
+ ['Quality (1-5)', summary?.quality_average],
1223
+ ...scores.map((item) => [` ${item.label}`, item.average]),
784
1224
  ['Error', result.error_message],
785
1225
  ['Link', result.url],
786
1226
  ]));
787
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
+ }));
788
1269
  runs
789
1270
  .command('delete <run>')
790
1271
  .description('Delete a run with its conversations and problems. A run still working is stopped first.')
@@ -801,6 +1282,63 @@ runs
801
1282
  const result = await client.action('delete_run', { project, run_number: runNumber });
802
1283
  out.result(result, () => `Deleted run #${result.run_number} ${result.name}.`);
803
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
+ }));
804
1342
  waitOptions(runs
805
1343
  .command('wait <batch>')
806
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)));
@@ -816,7 +1354,8 @@ problems
816
1354
  .description('Problems, newest first.')
817
1355
  .option('--run <n>', 'only problems of this run')
818
1356
  .addOption(new Option('--severity <severity>', 'major or minor').choices(['major', 'minor']))
819
- .option('--category <text>', 'only problems of a category whose title contains this')
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')
820
1359
  .addOption(modeOption())
821
1360
  .addOption(sourceOption())
822
1361
  .addOption(limitOption('problems', '20', 200))
@@ -826,6 +1365,7 @@ problems
826
1365
  run_number: opts.run ? intArg(String(opts.run)) : undefined,
827
1366
  severity: opts.severity,
828
1367
  category: opts.category,
1368
+ unsorted: opts.unsorted ? true : undefined,
829
1369
  mode: opts.mode,
830
1370
  source: opts.source,
831
1371
  limit: limitOf(opts, 200),
@@ -907,6 +1447,149 @@ categories
907
1447
  });
908
1448
  out.result(result, () => `Category ${result.id} ${result.category} is ${result.solved ? 'solved' : 'open again'}.`);
909
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
+ }));
910
1593
  problems
911
1594
  .command('dismiss <id>')
912
1595
  .description('Mark a problem a false alarm: it stops counting but stays on its conversation.')
@@ -961,6 +1644,52 @@ rules
961
1644
  });
962
1645
  out.result(result, () => `Removed: ${result.removed}\n\n${rulesRender(result)}`);
963
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'})`);
964
1693
  const traceLines = (trace) => {
965
1694
  if (!trace)
966
1695
  return [];
@@ -987,9 +1716,181 @@ program
987
1716
  ]),
988
1717
  '',
989
1718
  `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}` : ''}`),
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
+ : []),
991
1780
  ].join('\n'));
992
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
+ }));
993
1894
  const gateRunRender = (result) => [
994
1895
  fields([
995
1896
  ['Gate run', `#${result.gate_run_number ?? result.org_number} ${result.gate ?? result.release_gate_name ?? ''}`],
@@ -1096,13 +1997,261 @@ gate
1096
1997
  const result = await client.action('cancel_gate_run', { gate_run_number: intArg(number) });
1097
1998
  out.result(result, () => `Cancelled gate run #${result.gate_run_number}: CI treats it as not passed.`);
1098
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 }}`;
1099
2248
  const generate = program
1100
2249
  .command('generate')
1101
2250
  .description('Have QualiLoop write tests from one prompt.')
1102
2251
  .argument('[prompt...]', 'what to test, in plain words')
1103
2252
  .option('--suite <suite>', 'add the tests to this suite (id or name)')
1104
2253
  .option('--new-suite <name>', 'make a new suite for them')
1105
- .option('--max <n>', 'most tests to write')
2254
+ .option('--max <n>', 'most tests to write, up to 300')
1106
2255
  .option('--wait', 'wait until the tests are saved')
1107
2256
  .option('--timeout <minutes>', 'most minutes to wait', '15')
1108
2257
  .action(run(async ({ client, out, project, opts }, words = []) => {
@@ -1155,6 +2304,49 @@ generate
1155
2304
  ? `Generation ${result.id} had already finished (${result.status}); nothing to cancel.`
1156
2305
  : `Cancelling generation ${result.id}. It stops at its next step and saves nothing: qualiloop generate status ${result.id}`);
1157
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
+ }));
1158
2350
  const connectCommand = program
1159
2351
  .command('connect')
1160
2352
  .argument('[project]', 'the project: its number or name')
@@ -1239,7 +2431,9 @@ connectCommand
1239
2431
  ['Project', `#${result.project.number} ${result.project.name}`],
1240
2432
  ['Traces address', result.tracing.traces_url],
1241
2433
  ['Project key', `${result.tracing.project_key} (write it with: qualiloop connect env)`],
1242
- ['Saved endpoint', result.target ? result.target.base_url : 'none yet'],
2434
+ ['Saved connection', connect.targetAddress(result.target)],
2435
+ ...(result.target ? [['Agent name', result.target.name]] : []),
2436
+ ['Scoring with traces', !result.project.traces_disabled],
1243
2437
  ['Live traffic', result.project.live_data_enabled],
1244
2438
  ['QualiLoop calls from', result.outbound_addresses],
1245
2439
  ]),
@@ -1289,27 +2483,48 @@ connectCommand
1289
2483
  }));
1290
2484
  connectCommand
1291
2485
  .command('rename')
1292
- .description("Rename the project, describe it, or name its environment.")
2486
+ .description("Rename the project, describe it, name its environment, or name the agent on the saved endpoint.")
1293
2487
  .option('--name <name>')
1294
2488
  .option('--description <text>')
1295
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")
1296
2491
  .action(run(async (ctx) => {
1297
- const result = await connect.updateProject(ctx.client, { project: connectProject(ctx) }, {
2492
+ const options = { project: connectProject(ctx) };
2493
+ const project = {
1298
2494
  name: ctx.opts.name,
1299
2495
  description: ctx.opts.description,
1300
2496
  environment: ctx.opts.environment,
1301
- });
1302
- ctx.out.result(result, () => actedOn(result, 'Project updated.'));
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')));
1303
2514
  }));
1304
2515
  connectCommand
1305
2516
  .command('target')
1306
- .description('Save the endpoint QualiLoop calls, from a JSON file (or - for stdin).')
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).')
1307
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]))
1308
2520
  .option('--auth-header <Name=VARIABLE>', 'send header Name with the value of VARIABLE, read from the environment or --env-file')
1309
2521
  .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')
2522
+ .option('--env-file <path>', 'where to read a VARIABLE when the environment lacks it', '.env')
1311
2523
  .action(run(async (ctx) => {
1312
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);
1313
2528
  if (ctx.opts.authHeader) {
1314
2529
  const [name, variable] = String(ctx.opts.authHeader).split('=');
1315
2530
  if (!name || !variable)
@@ -1317,10 +2532,29 @@ connectCommand
1317
2532
  body.auth_header_name = name;
1318
2533
  body.auth_header_env = variable;
1319
2534
  body.auth_header_prefix = ctx.opts.authPrefix;
1320
- body.env_file = String(ctx.opts.envFile);
1321
2535
  }
1322
2536
  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 ?? '')}.`));
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'}.`));
1324
2558
  }));
1325
2559
  connectCommand
1326
2560
  .command('knowledge')
@@ -1338,14 +2572,73 @@ connectCommand
1338
2572
  .action(run(async ({ out }) => {
1339
2573
  out.result({ status: 'no_longer_needed', detail: connect.TRACE_FIELDS_GONE }, () => connect.TRACE_FIELDS_GONE);
1340
2574
  }));
2575
+ const limitArg = (value) => (value.toLowerCase() === 'none' ? null : intArg(value));
2576
+ const PERIODS = ['day', 'week', 'month'];
1341
2577
  connectCommand
1342
2578
  .command('live <on|off>')
1343
- .description("Turn the project's live traffic on or off (admins). It sends real users' data.")
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))
1344
2587
  .action(run(async (ctx, state) => {
1345
2588
  if (!['on', 'off'].includes(state))
1346
2589
  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'}.`));
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')));
1349
2642
  }));
1350
2643
  const checkRender = (result) => {
1351
2644
  const items = (result.items ?? result.checks);
@@ -1433,6 +2726,7 @@ program
1433
2726
  .command('action <name>')
1434
2727
  .description('Run one action with JSON arguments, as the MCP server would: qualiloop action list_runs --args \'{"limit": 5}\'')
1435
2728
  .option('--args <json>', 'the arguments as a JSON object', '{}')
2729
+ .option('--yes', 'answer yes to the question an action that deletes asks first')
1436
2730
  .action(run(async ({ client, out, project, opts }, name) => {
1437
2731
  let args;
1438
2732
  try {
@@ -1446,6 +2740,9 @@ program
1446
2740
  const properties = (spec?.input_schema.properties ?? {});
1447
2741
  if ('project' in properties && args.project === undefined && project !== undefined)
1448
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
+ }
1449
2746
  const result = await client.action(name, args);
1450
2747
  out.result(result, () => JSON.stringify(result, null, 2));
1451
2748
  }));