qualiloop 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,422 @@
1
+ import path from 'node:path';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
+ import { ApiError, QualiloopClient, VERSION } from '../api.js';
6
+ import { login } from '../auth.js';
7
+ import { bundledGuide, loadCatalog } from '../catalog.js';
8
+ import { resolveProject, storedCredentials } from '../config.js';
9
+ import * as connect from '../connect.js';
10
+ import { compareBatch, waitForBatch } from '../workflows.js';
11
+ export const LOCAL_INSTRUCTIONS = `Use these tools when the user asks to test their agent, read why a test or a release gate failed, look at the problems QualiLoop found, write or run tests, report a change to the agent, or connect an agent in this codebase to QualiLoop.
12
+
13
+ - After changing the agent's system prompts, tools or documentation in the code: connect_save_agent_context with the new texts, which records the change; after changing anything else: report_change. Then run_suite (or run_tests), then wait_for_runs, then list_problems for the runs that failed, then get_conversation to read the evidence.
14
+ - To connect an agent: connect_agent with the project the user named (it writes the key into .env and returns the steps), then follow the steps; use connect_write_env for keys, never print a key. Give every connect tool the project number (connect_projects lists them); each answer names the project it acted on. With QUALILOOP_SETUP_TOKEN set, the tools use that token's own project.
15
+ - If a tool says you are not signed in, call sign_in and ask the user to approve it in the browser.`;
16
+ export const INSTRUCTIONS = [bundledGuide(), '## On this machine', LOCAL_INSTRUCTIONS]
17
+ .filter(Boolean)
18
+ .join('\n\n');
19
+ const LOCAL_TOOLS = [
20
+ {
21
+ name: 'qualiloop_status',
22
+ description: 'Who is signed in to which QualiLoop, and the default project. Call it first if a tool says you are not signed in, or to check that a sign_in finished.',
23
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
24
+ annotations: { readOnlyHint: true },
25
+ },
26
+ {
27
+ name: 'sign_in',
28
+ description: 'Sign this MCP server (and the qualiloop CLI) in to QualiLoop. Opens the approval page in the user\'s browser and returns the link and a code. Tell the user to approve it there and check the code; then call qualiloop_status until it shows them signed in.',
29
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
30
+ },
31
+ {
32
+ name: 'wait_for_runs',
33
+ description: 'Wait until the runs one run_tests or run_suite call started have finished (judged, problems sorted), up to the given minutes, and return them. Finished runs say whether the test passed and how many major and minor problems each found. Once all have finished, comparison holds each test against its previous run (fixed, regressed, still failing, new) and the major and minor problems before and now, as compare_batch returns it. Call it again if it returns before they finish.',
34
+ inputSchema: {
35
+ type: 'object',
36
+ properties: {
37
+ project: { type: ['integer', 'string'], description: 'The project number or name.' },
38
+ batch: { type: 'string', description: 'The batch_id run_tests or run_suite returned.' },
39
+ minutes: { type: 'integer', minimum: 1, maximum: 10, default: 5, description: 'Most minutes to wait.' },
40
+ },
41
+ required: ['batch'],
42
+ additionalProperties: false,
43
+ },
44
+ annotations: { readOnlyHint: true },
45
+ },
46
+ {
47
+ name: 'connect_agent',
48
+ description: "Start connecting the agent in this codebase, in one call: takes the project the user named (number or name), or with none named creates one named after the codebase when the account has no project, and otherwise lists the projects so you can ask the user which. Makes it the default project, writes the project key and traces address into .env (values never returned; says whether git ignores the file), and returns the setup steps (the connect skill) to follow next.",
49
+ inputSchema: {
50
+ type: 'object',
51
+ properties: {
52
+ project: { type: ['integer', 'string'], description: "The project's number or name, as the user gave it." },
53
+ file: { type: 'string', default: '.env', description: 'The env file, inside this workspace.' },
54
+ },
55
+ additionalProperties: false,
56
+ },
57
+ },
58
+ {
59
+ name: 'connect_info',
60
+ description: 'Everything needed to connect the agent in this codebase to a QualiLoop project: the request contract of the endpoint QualiLoop calls, the OpenTelemetry traces address, the endpoint saved so far, and the addresses QualiLoop calls from. The project key is masked; write it with connect_write_env. Follow /connect/SKILL.md on the QualiLoop address for the steps.',
61
+ inputSchema: {
62
+ type: 'object',
63
+ properties: { project: { type: 'integer', description: "The project's number." } },
64
+ additionalProperties: false,
65
+ },
66
+ annotations: { readOnlyHint: true },
67
+ },
68
+ {
69
+ name: 'connect_projects',
70
+ description: 'The projects you can connect agents to, each with its agent name and environment (local, dev, staging, prod), and whether you may create more.',
71
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
72
+ annotations: { readOnlyHint: true },
73
+ },
74
+ {
75
+ name: 'connect_create_project',
76
+ description: 'Create a project for another agent in this codebase, or for another environment of an agent: one project per agent and environment, named "<agent> (<environment>)". Admins only. Ask the user before creating projects.',
77
+ inputSchema: {
78
+ type: 'object',
79
+ properties: {
80
+ name: { type: 'string', minLength: 2, description: "The agent's name, without the environment." },
81
+ environment: { type: 'string', enum: ['local', 'dev', 'staging', 'prod'] },
82
+ description: { type: 'string' },
83
+ },
84
+ required: ['name'],
85
+ additionalProperties: false,
86
+ },
87
+ },
88
+ {
89
+ name: 'connect_write_env',
90
+ description: "Write the project's key and traces address into an env file of this codebase (QUALILOOP_PROJECT_KEY and QUALILOOP_OTLP_TRACES_URL, with a suffix for a second agent). The values are never returned. Make sure the file is git-ignored.",
91
+ inputSchema: {
92
+ type: 'object',
93
+ properties: {
94
+ project: { type: 'integer', description: "The project's number." },
95
+ file: { type: 'string', default: '.env', description: 'Path inside this workspace.' },
96
+ suffix: { type: 'string', description: 'For a second agent: TRIAGE gives QUALILOOP_PROJECT_KEY_TRIAGE.' },
97
+ },
98
+ additionalProperties: false,
99
+ },
100
+ },
101
+ {
102
+ name: 'connect_save_target',
103
+ description: 'Save the endpoint QualiLoop calls to test the agent, and where it reads traces. Never put a secret in the arguments: give auth_header_name and auth_header_env, the variable holding its value (read here from the environment or env_file). The other fields are those of PUT /v1/setup/target in the skill: response_text_path, payload_template, variables, unique_variables, start_conversation, observability, max_parallel_conversations, reply_timeout_seconds.',
104
+ inputSchema: {
105
+ type: 'object',
106
+ properties: {
107
+ project: { type: 'integer', description: "The project's number." },
108
+ base_url: { type: 'string', description: 'The full address of the endpoint, reachable from the internet.' },
109
+ auth_header_name: { type: 'string', description: 'Such as X-Agent-Secret or Authorization.' },
110
+ auth_header_env: { type: 'string', description: 'The variable holding the header value, such as QUALILOOP_AGENT_SECRET.' },
111
+ auth_header_prefix: { type: 'string', description: 'Put before the value, such as "Bearer ".' },
112
+ env_file: { type: 'string', default: '.env', description: 'Where to read the variable when the environment lacks it.' },
113
+ response_text_path: { type: 'string' },
114
+ payload_template: { type: 'string' },
115
+ variables: { type: 'object', additionalProperties: { type: 'array', items: { type: 'string' } } },
116
+ unique_variables: { type: 'array', items: { type: 'string' } },
117
+ start_conversation: { type: ['object', 'null'] },
118
+ observability: { type: 'object' },
119
+ max_parallel_conversations: { type: 'integer' },
120
+ reply_timeout_seconds: { type: 'integer' },
121
+ },
122
+ required: ['base_url'],
123
+ additionalProperties: false,
124
+ },
125
+ },
126
+ {
127
+ name: 'connect_save_agent_context',
128
+ description: "Fill the agent's system knowledge from the code: its system prompts, tools and documentation, verbatim, become the sources QualiLoop reads and judges against, and General describes the agent. Give them inline, or as `file`, a JSON file in this workspace with the same fields (better for long prompts). The answer lists each source as new, unchanged or a new version, the ones retired, the ones a person keeps, and the General fields written or kept. Send it again after changing a prompt, a tool or a document. Set overwrite only when the user asked to replace General.",
129
+ inputSchema: {
130
+ type: 'object',
131
+ properties: {
132
+ project: { type: 'integer', description: "The project's number." },
133
+ file: { type: 'string', description: 'A JSON file in this workspace with the body.' },
134
+ system_prompts: {
135
+ type: 'array',
136
+ description: 'Every system prompt, verbatim; a template as written.',
137
+ items: {
138
+ type: 'object',
139
+ properties: {
140
+ name: { type: 'string', description: 'Where it is in the code, such as a path and a variable.' },
141
+ text: { type: 'string' },
142
+ placeholders: {
143
+ type: 'array',
144
+ items: { type: 'string' },
145
+ description: 'Every part filled at run time, exactly as it appears in the text.',
146
+ },
147
+ agent: { type: 'string', description: 'The agent or subagent this prompt instructs, as the code names it.' },
148
+ },
149
+ required: ['name', 'text'],
150
+ },
151
+ },
152
+ tools: {
153
+ type: 'array',
154
+ description: "Every tool the agent can call, with its description and argument schema.",
155
+ items: {
156
+ type: 'object',
157
+ properties: { name: { type: 'string' }, description: { type: 'string' }, parameters: { type: 'object' } },
158
+ required: ['name'],
159
+ },
160
+ },
161
+ documentation: {
162
+ type: 'array',
163
+ description: 'One entry per document in the repository the agent answers from, named by its path, verbatim.',
164
+ items: {
165
+ type: 'object',
166
+ properties: { name: { type: 'string' }, text: { type: 'string' } },
167
+ required: ['name', 'text'],
168
+ },
169
+ },
170
+ ui_tools: { type: 'array', items: { type: 'string' } },
171
+ general: {
172
+ type: 'object',
173
+ description: 'From the code and README only: the agent\'s name, a one-sentence summary, and a description of what it is, who uses it and what matters most.',
174
+ properties: { name: { type: 'string' }, summary: { type: 'string' }, description: { type: 'string' } },
175
+ additionalProperties: false,
176
+ },
177
+ overwrite: {
178
+ type: 'boolean',
179
+ description: 'Write General over what is there. Only when the user explicitly asked; otherwise only empty fields are filled.',
180
+ },
181
+ },
182
+ additionalProperties: false,
183
+ },
184
+ },
185
+ {
186
+ name: 'connect_check_traces',
187
+ description: "Check QualiLoop tracing from one session you produced yourself on this machine (a request marked as a QualiLoop test, with your own session id): whether its spans arrived and what they carry. Calls nothing and records nothing.",
188
+ inputSchema: {
189
+ type: 'object',
190
+ properties: {
191
+ project: { type: 'integer', description: "The project's number." },
192
+ session_id: { type: 'string' },
193
+ },
194
+ required: ['session_id'],
195
+ additionalProperties: false,
196
+ },
197
+ annotations: { readOnlyHint: true },
198
+ },
199
+ {
200
+ name: 'connect_check',
201
+ description: 'Send one real test message to the saved endpoint and report, item by item, what arrived (endpoint reached, reply found, trace matched, spans, model, tokens, steps). Takes up to a minute. Only once the address runs the changes: never against an address that is not deployed yet.',
202
+ inputSchema: {
203
+ type: 'object',
204
+ properties: { project: { type: 'integer', description: "The project's number." } },
205
+ additionalProperties: false,
206
+ },
207
+ },
208
+ {
209
+ name: 'connect_set_live',
210
+ description: "Turn the project's live traffic on or off: real users' conversations, sent through QualiLoop tracing, recorded and judged. Ask the user first; it sends real users' data. Admins only.",
211
+ inputSchema: {
212
+ type: 'object',
213
+ properties: {
214
+ project: { type: 'integer', description: "The project's number." },
215
+ enabled: { type: 'boolean' },
216
+ },
217
+ required: ['enabled'],
218
+ additionalProperties: false,
219
+ },
220
+ },
221
+ ];
222
+ const workspaceRoot = () => path.resolve(process.env.QUALILOOP_WORKSPACE || process.cwd());
223
+ export const insideWorkspace = (file, root = workspaceRoot()) => {
224
+ const resolved = path.resolve(root, file);
225
+ const relative = path.relative(root, resolved);
226
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
227
+ throw new ApiError(`${file} is outside the workspace ${root}.`, 400, 2);
228
+ }
229
+ return resolved;
230
+ };
231
+ export const actionTool = (spec) => ({
232
+ name: spec.name,
233
+ description: spec.description,
234
+ inputSchema: spec.input_schema,
235
+ annotations: {
236
+ title: spec.title,
237
+ readOnlyHint: spec.read_only,
238
+ destructiveHint: !spec.read_only && spec.confirm === 'always',
239
+ openWorldHint: spec.launches_work,
240
+ },
241
+ });
242
+ const text = (value) => ({
243
+ content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
244
+ });
245
+ const failure = (message) => ({ ...text(message), isError: true });
246
+ export const createServer = (client = new QualiloopClient()) => {
247
+ const server = new Server({ name: 'qualiloop', version: VERSION }, { capabilities: { tools: { listChanged: true } }, instructions: INSTRUCTIONS });
248
+ let catalog;
249
+ let pendingSignIn;
250
+ const actions = async () => {
251
+ catalog = catalog ?? (await loadCatalog(client));
252
+ return catalog;
253
+ };
254
+ const reloadTools = () => {
255
+ catalog = undefined;
256
+ server.sendToolListChanged().catch(() => undefined);
257
+ };
258
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
259
+ const specs = await actions();
260
+ const tools = specs
261
+ .filter((spec) => spec.available)
262
+ .map(actionTool);
263
+ return { tools: [...tools, ...LOCAL_TOOLS] };
264
+ });
265
+ const withProject = (args, spec) => {
266
+ const properties = (spec?.input_schema.properties ?? { project: {} });
267
+ if (!('project' in properties) || args.project !== undefined)
268
+ return args;
269
+ const project = resolveProject(client.url);
270
+ return project === undefined ? args : { ...args, project };
271
+ };
272
+ const local = async (name, args) => {
273
+ const project = (args.project ?? resolveProject(client.url));
274
+ const named = args.project;
275
+ switch (name) {
276
+ case 'qualiloop_status': {
277
+ const stored = storedCredentials(client.url);
278
+ if (!client.isSignedIn()) {
279
+ return {
280
+ signed_in: false,
281
+ url: client.url,
282
+ sign_in: pendingSignIn?.error
283
+ ? `The last sign-in failed: ${pendingSignIn.error}`
284
+ : pendingSignIn
285
+ ? `Waiting for approval at ${pendingSignIn.url} (code ${pendingSignIn.code}).`
286
+ : 'Call sign_in.',
287
+ };
288
+ }
289
+ const me = await client.request('GET', '/v1/auth/me');
290
+ reloadTools();
291
+ return {
292
+ signed_in: true,
293
+ url: client.url,
294
+ email: me.email,
295
+ role: me.role,
296
+ organization: stored?.user?.organization_name ?? null,
297
+ default_project: resolveProject(client.url) ?? null,
298
+ };
299
+ }
300
+ case 'sign_in': {
301
+ if (client.isSignedIn())
302
+ return { signed_in: true, url: client.url };
303
+ pendingSignIn = {};
304
+ const started = new Promise((resolve) => {
305
+ login(client, {
306
+ client: 'mcp',
307
+ again: 'Call sign_in again.',
308
+ onStarted: ({ url, code }) => {
309
+ pendingSignIn = { url, code };
310
+ resolve(pendingSignIn);
311
+ },
312
+ }).then(() => {
313
+ pendingSignIn = undefined;
314
+ reloadTools();
315
+ }, (error) => {
316
+ pendingSignIn = { error: error instanceof Error ? error.message : String(error) };
317
+ resolve(pendingSignIn);
318
+ });
319
+ });
320
+ const pending = await started;
321
+ if (pending.error)
322
+ throw new Error(pending.error);
323
+ return {
324
+ approve_at: pending.url,
325
+ code: pending.code,
326
+ next_step: 'Ask the user to open the link (it opened in their browser if one is available), check that the page shows this code, and approve. Then call qualiloop_status.',
327
+ };
328
+ }
329
+ case 'wait_for_runs': {
330
+ const minutes = Math.min(10, Math.max(1, Number(args.minutes ?? 5)));
331
+ try {
332
+ const runs = await waitForBatch(client, project, String(args.batch), {
333
+ timeoutMinutes: minutes,
334
+ });
335
+ const comparison = await compareBatch(client, project, String(args.batch)).catch((error) => ({ error: `Could not compare with the previous runs: ${error.message}` }));
336
+ return { all_finished: true, runs, comparison };
337
+ }
338
+ catch (error) {
339
+ if (error instanceof ApiError && error.exitCode === 5) {
340
+ const listed = await client.action('list_runs', { project, batch: args.batch, limit: 500 });
341
+ return { ...listed, note: `Not finished after ${minutes} minutes. Call wait_for_runs again.` };
342
+ }
343
+ throw error;
344
+ }
345
+ }
346
+ case 'connect_agent': {
347
+ const started = await connect.start(client, {
348
+ project: named === undefined ? undefined : String(named),
349
+ dir: workspaceRoot(),
350
+ file: insideWorkspace(String(args.file ?? '.env')),
351
+ ask: (projects) => `Ask the user which project to connect, then call connect_agent with its number: ${projects
352
+ .map((item) => `#${item.number} ${item.name}`)
353
+ .join(', ')}.`,
354
+ });
355
+ let steps;
356
+ try {
357
+ steps = (await connect.skill(client)).text;
358
+ }
359
+ catch (error) {
360
+ steps = `${error instanceof Error ? error.message : String(error)} Read ${client.url}/connect/SKILL.md for the steps.`;
361
+ }
362
+ return { ...started, git_note: connect.gitNote(started.env.file, started.env.git_ignored) || null, steps };
363
+ }
364
+ case 'connect_info':
365
+ return connect.info(client, { project: named });
366
+ case 'connect_projects':
367
+ return connect.projects(client);
368
+ case 'connect_create_project':
369
+ return connect.createProject(client, {
370
+ name: String(args.name),
371
+ environment: args.environment,
372
+ description: args.description,
373
+ });
374
+ case 'connect_write_env':
375
+ return connect.writeEnv(client, {
376
+ project: named,
377
+ file: insideWorkspace(String(args.file ?? '.env')),
378
+ suffix: args.suffix,
379
+ });
380
+ case 'connect_save_target': {
381
+ const { project: _ignored, env_file, ...rest } = args;
382
+ return connect.saveTarget(client, { project: named }, {
383
+ ...rest,
384
+ env_file: insideWorkspace(String(env_file ?? '.env')),
385
+ });
386
+ }
387
+ case 'connect_save_agent_context': {
388
+ const { project: _ignored, file, overwrite, ...inline } = args;
389
+ const body = file ? connect.readJson(insideWorkspace(String(file))) : inline;
390
+ return connect.saveKnowledge(client, { project: named }, body, Boolean(overwrite));
391
+ }
392
+ case 'connect_check_traces':
393
+ return connect.checkTraces(client, { project: named }, String(args.session_id));
394
+ case 'connect_check':
395
+ return connect.check(client, { project: named });
396
+ case 'connect_set_live':
397
+ return connect.setLive(client, { project: named }, { enabled: Boolean(args.enabled) });
398
+ default:
399
+ throw new Error(`Unknown tool ${name}.`);
400
+ }
401
+ };
402
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
403
+ const name = request.params.name;
404
+ const args = (request.params.arguments ?? {});
405
+ try {
406
+ if (LOCAL_TOOLS.some((tool) => tool.name === name))
407
+ return text(await local(name, args));
408
+ const spec = (await actions()).find((item) => item.name === name);
409
+ if (!spec)
410
+ return failure(`Unknown tool ${name}.`);
411
+ return text(await client.action(name, withProject(args, spec)));
412
+ }
413
+ catch (error) {
414
+ return failure(error instanceof Error ? error.message : String(error));
415
+ }
416
+ });
417
+ return server;
418
+ };
419
+ export const serveStdio = async (client = new QualiloopClient()) => {
420
+ const server = createServer(client);
421
+ await server.connect(new StdioServerTransport());
422
+ };
package/dist/output.js ADDED
@@ -0,0 +1,43 @@
1
+ const text = (value) => {
2
+ if (value === null || value === undefined || value === '')
3
+ return '-';
4
+ if (typeof value === 'boolean')
5
+ return value ? 'yes' : 'no';
6
+ if (Array.isArray(value))
7
+ return value.length ? value.map(text).join(', ') : '-';
8
+ if (typeof value === 'object')
9
+ return JSON.stringify(value);
10
+ return String(value).replace(/\s+/g, ' ');
11
+ };
12
+ const clip = (value, width) => value.length <= width ? value : `${value.slice(0, Math.max(1, width - 1))}…`;
13
+ export const table = (rows, columns) => {
14
+ if (!rows.length)
15
+ return '';
16
+ const cells = rows.map((row) => columns.map(([key, , width]) => clip(text(row[key]), width ?? 60)));
17
+ const widths = columns.map(([, label], index) => Math.max(label.length, ...cells.map((line) => line[index].length)));
18
+ const line = (values) => values.map((value, index) => value.padEnd(widths[index])).join(' ').trimEnd();
19
+ return [line(columns.map(([, label]) => label)), ...cells.map(line)].join('\n');
20
+ };
21
+ export const fields = (pairs) => {
22
+ const width = Math.max(...pairs.map(([label]) => label.length));
23
+ return pairs.map(([label, value]) => `${label.padEnd(width)} ${text(value)}`).join('\n');
24
+ };
25
+ export const output = (json) => ({
26
+ json,
27
+ say(message) {
28
+ if (!json)
29
+ process.stdout.write(`${message}\n`);
30
+ },
31
+ progress(message) {
32
+ process.stderr.write(`${message}\n`);
33
+ },
34
+ result(data, render) {
35
+ if (json) {
36
+ process.stdout.write(`${JSON.stringify(data, null, 2)}\n`);
37
+ return;
38
+ }
39
+ const rendered = render();
40
+ if (rendered)
41
+ process.stdout.write(`${rendered}\n`);
42
+ },
43
+ });
@@ -0,0 +1,147 @@
1
+ import { ApiError, EXIT } from './api.js';
2
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3
+ export const isTransient = (error) => error instanceof ApiError &&
4
+ (error.status === 0 || error.status === 408 || error.status === 429 || error.status >= 500);
5
+ export const READ_TRIES = 5;
6
+ export const readPatiently = async (read, pauseMs = 2000) => {
7
+ for (let attempt = 1;; attempt += 1) {
8
+ try {
9
+ return await read();
10
+ }
11
+ catch (error) {
12
+ if (attempt >= READ_TRIES || !isTransient(error))
13
+ throw error;
14
+ await sleep(pauseMs * 2 ** (attempt - 1));
15
+ }
16
+ }
17
+ };
18
+ export const batchProgress = (runs) => {
19
+ const done = runs.filter((run) => run.finished).length;
20
+ const working = new Map();
21
+ for (const run of runs) {
22
+ if (run.finished)
23
+ continue;
24
+ const label = (run.status_label ?? run.status).toLowerCase();
25
+ working.set(label, (working.get(label) ?? 0) + 1);
26
+ }
27
+ const doing = [...working].map(([label, count]) => `${count} ${label}`).join(', ');
28
+ return `${done} of ${runs.length} runs finished${doing ? `; ${doing}` : ''}`;
29
+ };
30
+ export const waitForBatch = async (client, project, batchId, waiting) => {
31
+ const deadline = Date.now() + waiting.timeoutMinutes * 60_000;
32
+ let errors = 0;
33
+ for (;;) {
34
+ try {
35
+ const listed = await client.action('list_runs', {
36
+ project,
37
+ batch: batchId,
38
+ limit: 500,
39
+ });
40
+ errors = 0;
41
+ if (!listed.runs.length) {
42
+ throw new ApiError(`No runs in batch ${batchId}${project ? ` of project ${project}` : ''}. A run --wait or suites run --wait prints its batch.`, 404, EXIT.notFound);
43
+ }
44
+ waiting.onProgress?.(batchProgress(listed.runs));
45
+ if (listed.all_finished)
46
+ return listed.runs;
47
+ }
48
+ catch (error) {
49
+ if (error instanceof ApiError && error.exitCode === EXIT.notFound)
50
+ throw error;
51
+ errors += 1;
52
+ if (errors >= 10 || (error instanceof ApiError && error.exitCode === EXIT.auth))
53
+ throw error;
54
+ }
55
+ if (Date.now() > deadline) {
56
+ throw new ApiError(`The runs did not finish within ${waiting.timeoutMinutes} minutes. They keep running in QualiLoop.`, 408, EXIT.timeout);
57
+ }
58
+ await sleep((waiting.pollSeconds ?? 10) * 1000);
59
+ }
60
+ };
61
+ export const runsExitCode = (runs, failOn) => {
62
+ if (failOn === 'none')
63
+ return EXIT.ok;
64
+ const failed = runs.some((run) => {
65
+ if (run.test_passed === false)
66
+ return true;
67
+ if (['failed', 'stopped'].includes(run.status))
68
+ return true;
69
+ return failOn === 'minor' && (run.minor_problems ?? 0) > 0;
70
+ });
71
+ return failed ? EXIT.failed : EXIT.ok;
72
+ };
73
+ export const compareBatch = (client, project, batchId) => client.action('compare_batch', { project, batch: batchId });
74
+ const CHANGE_WORDS = [
75
+ ['fixed', 'fixed'],
76
+ ['regressed', 'regressed'],
77
+ ['still_failing', 'still failing'],
78
+ ['still_passing', 'still passing'],
79
+ ['new', 'new'],
80
+ ['unfinished', 'unfinished'],
81
+ ];
82
+ export const comparisonText = (comparison, projectFlag = '') => {
83
+ const counts = CHANGE_WORDS.filter(([change]) => comparison.counts[change])
84
+ .map(([change, words]) => `${comparison.counts[change]} ${words}`)
85
+ .join(', ');
86
+ const compared = ['fixed', 'regressed', 'still_failing', 'still_passing'].some((change) => comparison.counts[change]);
87
+ const { major, minor } = comparison.problems;
88
+ const lines = [
89
+ `vs previous: ${counts || 'nothing to compare'}` +
90
+ (compared ? `; major problems ${major.previous} -> ${major.now}, minor ${minor.previous} -> ${minor.now}` : ''),
91
+ ];
92
+ const regressed = comparison.tests.filter((test) => test.change === 'regressed');
93
+ if (regressed.length) {
94
+ lines.push('Regressed (passed last time):');
95
+ for (const test of regressed) {
96
+ lines.push(` #${test.run_number} ${test.name} (was #${test.previous_run_number}): qualiloop problems --run ${test.run_number}${projectFlag}`);
97
+ }
98
+ }
99
+ return lines.join('\n');
100
+ };
101
+ const waitForGate = async (read, waiting) => {
102
+ const deadline = Date.now() + waiting.timeoutMinutes * 60_000;
103
+ let errors = 0;
104
+ for (;;) {
105
+ try {
106
+ const run = await read();
107
+ errors = 0;
108
+ waiting.onProgress?.(`${run.status}: ${run.completed_tests ?? 0}/${run.total_tests ?? 0} tests done, ${run.pass_percentage ?? 0}% passing`);
109
+ if (run.status === 'completed')
110
+ return run;
111
+ }
112
+ catch (error) {
113
+ errors += 1;
114
+ if (errors >= 20 || (error instanceof ApiError && error.exitCode === EXIT.auth))
115
+ throw error;
116
+ }
117
+ if (Date.now() > deadline) {
118
+ throw new ApiError(`No gate decision within ${waiting.timeoutMinutes} minutes. Failing, as the gate's CI time limit says.`, 408, EXIT.timeout);
119
+ }
120
+ await sleep((waiting.pollSeconds ?? 15) * 1000);
121
+ }
122
+ };
123
+ export const waitForGateRun = (client, number, waiting) => waitForGate(() => client.action('get_gate_run', { gate_run_number: number }), waiting);
124
+ export const startGateWithKey = (client, key, body) => client.request('POST', '/v1/release-gates/hooks/runs', { token: key, body });
125
+ export const waitForGateRunWithKey = (client, key, runId, waiting) => waitForGate(() => client.request('GET', `/v1/release-gates/hooks/runs/${runId}`, { token: key }), waiting);
126
+ export const startGeneration = (client, options) => client.action('generate_tests', {
127
+ project: options.project,
128
+ prompt: options.prompt,
129
+ suite: options.suite === undefined ? undefined : /^\d+$/.test(options.suite) ? Number(options.suite) : options.suite,
130
+ new_suite_name: options.newSuite,
131
+ max_count: options.max,
132
+ });
133
+ export const getGeneration = (client, id) => client.action('get_generation', { generation: id });
134
+ export const cancelGeneration = (client, id) => client.action('cancel_generation', { generation: id });
135
+ export const waitForGeneration = async (client, id, waiting) => {
136
+ const deadline = Date.now() + waiting.timeoutMinutes * 60_000;
137
+ for (;;) {
138
+ const generation = await readPatiently(() => getGeneration(client, id));
139
+ waiting.onProgress?.(`${generation.step_label ?? generation.step ?? generation.status}${generation.planned ? `: ${generation.written ?? 0}/${generation.planned} written` : ''}`);
140
+ if (generation.finished)
141
+ return generation;
142
+ if (Date.now() > deadline) {
143
+ throw new ApiError(`The generation did not finish within ${waiting.timeoutMinutes} minutes. It keeps going in QualiLoop.`, 408, EXIT.timeout);
144
+ }
145
+ await sleep((waiting.pollSeconds ?? 5) * 1000);
146
+ }
147
+ };
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
- {
2
- "name": "qualiloop",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "qualiloop",
3
+ "version": "0.1.0",
4
+ "description": "QualiLoop from the terminal, scripts, CI and coding agents: run tests and release gates, read problems, write tests. The qualiloop CLI and its MCP server.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://www.qualiloop.com",
7
+ "keywords": [
8
+ "qualiloop",
9
+ "ai-agent",
10
+ "llm",
11
+ "testing",
12
+ "evaluation",
13
+ "release-gate",
14
+ "ci",
15
+ "cli",
16
+ "mcp",
17
+ "mcp-server"
18
+ ],
19
+ "type": "module",
20
+ "bin": {
21
+ "qualiloop": "dist/cli.js",
22
+ "ql": "dist/cli.js"
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "scripts": {
30
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
31
+ "build": "npm run clean && tsc -p tsconfig.json && node scripts/copy-catalog.mjs",
32
+ "type-check": "tsc -p tsconfig.json --noEmit",
33
+ "test": "npm run build && node --test test/unit.test.mjs test/smoke.test.mjs",
34
+ "start": "node dist/cli.js",
35
+ "prepack": "npm run build"
36
+ },
37
+ "engines": {
38
+ "node": ">=20"
39
+ },
40
+ "dependencies": {
41
+ "@modelcontextprotocol/sdk": "1.32.1",
42
+ "commander": "14.0.3"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "22.20.5",
46
+ "typescript": "5.9.3"
47
+ }
48
+ }