qualiloop 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,523 @@
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. Once connect_check passes, go on with the steps' next steps: connect_set_limits fitted to the agent, the free first exploration, then offer to generate and run the Core suite.
15
+ - If a tool says you are not signed in, call sign_in and ask the user to approve it in the browser. Do not ask them to tell you when they are done: call qualiloop_status, which waits for the approval, until it shows them signed in.`;
16
+ export const INSTRUCTIONS = [bundledGuide(), '## On this machine', LOCAL_INSTRUCTIONS]
17
+ .filter(Boolean)
18
+ .join('\n\n');
19
+ const STATUS_WAIT_SECONDS = 60;
20
+ const STATUS_WAIT_MAX_SECONDS = 300;
21
+ const LOCAL_TOOLS = [
22
+ {
23
+ name: 'qualiloop_status',
24
+ description: 'Who is signed in to which QualiLoop, and the default project. Call it first if a tool says you are not signed in, and after sign_in to wait for the approval: while a sign-in waits, it waits with it (up to wait_seconds) and answers once the user has approved.',
25
+ inputSchema: {
26
+ type: 'object',
27
+ properties: {
28
+ wait_seconds: {
29
+ type: 'integer',
30
+ minimum: 0,
31
+ maximum: STATUS_WAIT_MAX_SECONDS,
32
+ default: STATUS_WAIT_SECONDS,
33
+ description: 'While a sign-in waits for approval, most seconds to wait for it.',
34
+ },
35
+ },
36
+ additionalProperties: false,
37
+ },
38
+ annotations: { readOnlyHint: true },
39
+ },
40
+ {
41
+ name: 'sign_in',
42
+ 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 (a new user creates an account from that page first); then call qualiloop_status, which waits for the approval, until it shows them signed in. Do not ask the user to say when they are done.",
43
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
44
+ },
45
+ {
46
+ name: 'wait_for_runs',
47
+ 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.',
48
+ inputSchema: {
49
+ type: 'object',
50
+ properties: {
51
+ project: { type: ['integer', 'string'], description: 'The project number or name.' },
52
+ batch: { type: 'string', description: 'The batch_id run_tests or run_suite returned.' },
53
+ minutes: { type: 'integer', minimum: 1, maximum: 10, default: 5, description: 'Most minutes to wait.' },
54
+ },
55
+ required: ['batch'],
56
+ additionalProperties: false,
57
+ },
58
+ annotations: { readOnlyHint: true },
59
+ },
60
+ {
61
+ name: 'connect_agent',
62
+ 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.",
63
+ inputSchema: {
64
+ type: 'object',
65
+ properties: {
66
+ project: { type: ['integer', 'string'], description: "The project's number or name, as the user gave it." },
67
+ file: { type: 'string', default: '.env', description: 'The env file, inside this workspace.' },
68
+ },
69
+ additionalProperties: false,
70
+ },
71
+ },
72
+ {
73
+ name: 'connect_info',
74
+ 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.',
75
+ inputSchema: {
76
+ type: 'object',
77
+ properties: { project: { type: 'integer', description: "The project's number." } },
78
+ additionalProperties: false,
79
+ },
80
+ annotations: { readOnlyHint: true },
81
+ },
82
+ {
83
+ name: 'connect_projects',
84
+ 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.',
85
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
86
+ annotations: { readOnlyHint: true },
87
+ },
88
+ {
89
+ name: 'connect_create_project',
90
+ 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.',
91
+ inputSchema: {
92
+ type: 'object',
93
+ properties: {
94
+ name: { type: 'string', minLength: 2, description: "The agent's name, without the environment." },
95
+ environment: { type: 'string', enum: ['local', 'dev', 'staging', 'prod'] },
96
+ description: { type: 'string' },
97
+ },
98
+ required: ['name'],
99
+ additionalProperties: false,
100
+ },
101
+ },
102
+ {
103
+ name: 'connect_write_env',
104
+ 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.",
105
+ inputSchema: {
106
+ type: 'object',
107
+ properties: {
108
+ project: { type: 'integer', description: "The project's number." },
109
+ file: { type: 'string', default: '.env', description: 'Path inside this workspace.' },
110
+ suffix: { type: 'string', description: 'For a second agent: TRIAGE gives QUALILOOP_PROJECT_KEY_TRIAGE.' },
111
+ },
112
+ additionalProperties: false,
113
+ },
114
+ },
115
+ {
116
+ name: 'connect_save_target',
117
+ description: "Save how QualiLoop reaches the agent, and where it reads traces. mode: endpoint (the default when base_url is given), dify (the app's Dify preset: Dify's chat address unless base_url names a self-hosted one, its request body, the API key as auth header Authorization), async_session (a session endpoint: async_session holds the protocol, with operations init and send), browser (QualiLoop types into the chat page: browser.chat_page_url and browser.input_selector), elevenlabs (elevenlabs.api_key and agent_id; QualiLoop reads the agent's prompt and success criteria) or gohighlevel (gohighlevel.private_token and location_id). Only the endpoint mode reads a trace source. Never put a secret in the arguments: give auth_header_name and auth_header_env for the header, and <field>_env in a block for its secret (elevenlabs.api_key_env, gohighlevel.private_token_env, browser.browserbase_context_id_env, observability.secret_key_env, observability.api_key_env), the variable holding it, read here from the environment or env_file. system_prompt and grounding_documentation (async_session and browser, which carry no trace) become the project's Connection settings sources. The other fields are those of PUT /v1/setup/target in the skill. Fields left out keep what is saved; with no mode and no base_url the saved connection's settings change.",
118
+ inputSchema: {
119
+ type: 'object',
120
+ properties: {
121
+ project: { type: 'integer', description: "The project's number." },
122
+ mode: { type: 'string', enum: ['endpoint', 'dify', 'async_session', 'browser', 'elevenlabs', 'gohighlevel'] },
123
+ base_url: { type: 'string', description: 'The full address of the endpoint, reachable from the internet.' },
124
+ auth_header_name: { type: 'string', description: 'Such as X-Agent-Secret or Authorization.' },
125
+ auth_header_env: { type: 'string', description: 'The variable holding the header value, such as QUALILOOP_AGENT_SECRET.' },
126
+ auth_header_prefix: { type: 'string', description: 'Put before the value, such as "Bearer ".' },
127
+ env_file: { type: 'string', default: '.env', description: 'Where to read a variable when the environment lacks it.' },
128
+ response_text_path: { type: 'string' },
129
+ payload_template: { type: 'string' },
130
+ variables: { type: 'object', additionalProperties: { type: 'array', items: { type: 'string' } } },
131
+ unique_variables: { type: 'array', items: { type: 'string' } },
132
+ start_conversation: { type: ['object', 'null'] },
133
+ observability: {
134
+ type: 'object',
135
+ description: 'Endpoint mode only. Where traces are read: provider otel (QualiLoop tracing, the default), langfuse (host, public_key, secret_key_env), langsmith (api_key_env, host, project) or none (no traces); session_id_path optional.',
136
+ },
137
+ max_parallel_conversations: { type: 'integer' },
138
+ reply_timeout_seconds: { type: 'integer' },
139
+ name: { type: 'string', minLength: 3, description: "The agent's name, as the connection settings show it." },
140
+ trace_fetch_delay_seconds: { type: 'integer', minimum: 0, maximum: 120 },
141
+ trace_fetch_interval_seconds: { type: 'integer', minimum: 1, maximum: 60 },
142
+ trace_fetch_max_wait_seconds: { type: 'integer', minimum: 0, maximum: 600 },
143
+ async_session: { type: 'object', description: 'async_session mode: the session protocol, with operations init and send.' },
144
+ system_prompt: { type: 'string', description: "async_session and browser modes: the agent's system prompt, verbatim." },
145
+ grounding_documentation: { type: 'string', description: 'async_session and browser modes: the documents the agent answers from.' },
146
+ browser: {
147
+ type: 'object',
148
+ description: 'browser mode: chat_page_url, input_selector, send_button_selector, submit_method (auto, enter_key, button), wait_timeout_seconds (5 to 300), browserbase_context_id_env.',
149
+ },
150
+ elevenlabs: {
151
+ type: 'object',
152
+ description: 'elevenlabs mode: api_key_env, agent_id, region (global, us, eu, in, sg), default_voice_id, max_reply_ms (0 turns the slow reply check off). Giving agent_id again reads the agent afresh.',
153
+ },
154
+ gohighlevel: {
155
+ type: 'object',
156
+ description: 'gohighlevel mode: private_token_env, location_id, channel (Live_Chat, WhatsApp, SMS, Instagram, Facebook), agent_id, reply_timeout_seconds (10 to 300), poll_interval_seconds (1 to 30), observability_enabled.',
157
+ },
158
+ },
159
+ additionalProperties: false,
160
+ },
161
+ },
162
+ {
163
+ name: 'connect_set_limits',
164
+ description: "Set how hard QualiLoop drives the saved endpoint, to fit what the agent can take: max_parallel_conversations, the most conversations at once (0 removes the limit), and reply_timeout_seconds, the most seconds one reply may take. Give one or both; every other setting of the endpoint stays. Give neither to read the saved values. Set them before the first exploration or tests.",
165
+ inputSchema: {
166
+ type: 'object',
167
+ properties: {
168
+ project: { type: 'integer', description: "The project's number." },
169
+ max_parallel_conversations: { type: 'integer', minimum: 0, maximum: 100 },
170
+ reply_timeout_seconds: { type: 'integer', minimum: 1, maximum: 600 },
171
+ },
172
+ additionalProperties: false,
173
+ },
174
+ },
175
+ {
176
+ name: 'connect_set_traces',
177
+ description: "Whether scoring uses the agent's traces, and how long QualiLoop waits for a conversation's traces once its last turn is done. enabled false scores without traces (admins). The timing changes the saved endpoint only: the first look after delay_seconds, then one every interval_seconds, stopping after max_wait_seconds. Give any of them; the rest stays.",
178
+ inputSchema: {
179
+ type: 'object',
180
+ properties: {
181
+ project: { type: 'integer', description: "The project's number." },
182
+ enabled: { type: 'boolean' },
183
+ delay_seconds: { type: 'integer', minimum: 0, maximum: 120 },
184
+ interval_seconds: { type: 'integer', minimum: 1, maximum: 60 },
185
+ max_wait_seconds: { type: 'integer', minimum: 0, maximum: 600 },
186
+ },
187
+ additionalProperties: false,
188
+ },
189
+ },
190
+ {
191
+ name: 'connect_save_agent_context',
192
+ 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.",
193
+ inputSchema: {
194
+ type: 'object',
195
+ properties: {
196
+ project: { type: 'integer', description: "The project's number." },
197
+ file: { type: 'string', description: 'A JSON file in this workspace with the body.' },
198
+ system_prompts: {
199
+ type: 'array',
200
+ description: 'Every system prompt, verbatim; a template as written.',
201
+ items: {
202
+ type: 'object',
203
+ properties: {
204
+ name: { type: 'string', description: 'Where it is in the code, such as a path and a variable.' },
205
+ text: { type: 'string' },
206
+ placeholders: {
207
+ type: 'array',
208
+ items: { type: 'string' },
209
+ description: 'Every part filled at run time, exactly as it appears in the text.',
210
+ },
211
+ agent: { type: 'string', description: 'The agent or subagent this prompt instructs, as the code names it.' },
212
+ },
213
+ required: ['name', 'text'],
214
+ },
215
+ },
216
+ tools: {
217
+ type: 'array',
218
+ description: "Every tool the agent can call, with its description and argument schema.",
219
+ items: {
220
+ type: 'object',
221
+ properties: { name: { type: 'string' }, description: { type: 'string' }, parameters: { type: 'object' } },
222
+ required: ['name'],
223
+ },
224
+ },
225
+ documentation: {
226
+ type: 'array',
227
+ description: 'One entry per document in the repository the agent answers from, named by its path, verbatim.',
228
+ items: {
229
+ type: 'object',
230
+ properties: { name: { type: 'string' }, text: { type: 'string' } },
231
+ required: ['name', 'text'],
232
+ },
233
+ },
234
+ ui_tools: { type: 'array', items: { type: 'string' } },
235
+ general: {
236
+ type: 'object',
237
+ 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.',
238
+ properties: { name: { type: 'string' }, summary: { type: 'string' }, description: { type: 'string' } },
239
+ additionalProperties: false,
240
+ },
241
+ overwrite: {
242
+ type: 'boolean',
243
+ description: 'Write General over what is there. Only when the user explicitly asked; otherwise only empty fields are filled.',
244
+ },
245
+ },
246
+ additionalProperties: false,
247
+ },
248
+ },
249
+ {
250
+ name: 'connect_check_traces',
251
+ 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.",
252
+ inputSchema: {
253
+ type: 'object',
254
+ properties: {
255
+ project: { type: 'integer', description: "The project's number." },
256
+ session_id: { type: 'string' },
257
+ },
258
+ required: ['session_id'],
259
+ additionalProperties: false,
260
+ },
261
+ annotations: { readOnlyHint: true },
262
+ },
263
+ {
264
+ name: 'connect_check',
265
+ 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.',
266
+ inputSchema: {
267
+ type: 'object',
268
+ properties: { project: { type: 'integer', description: "The project's number." } },
269
+ additionalProperties: false,
270
+ },
271
+ },
272
+ {
273
+ name: 'connect_set_live',
274
+ 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. Only when the user asks about how much is stored or scored: collect_percent, scoring_enabled, score_percent, and limits per day, week or month (turn_limit for stored turns, score_limit for scored conversations; null removes a limit). Left out, what is saved stays.",
275
+ inputSchema: {
276
+ type: 'object',
277
+ properties: {
278
+ project: { type: 'integer', description: "The project's number." },
279
+ enabled: { type: 'boolean' },
280
+ collect_percent: { type: 'integer', minimum: 0, maximum: 100, description: 'Share of new live conversations stored.' },
281
+ scoring_enabled: { type: 'boolean', description: 'Score stored live conversations.' },
282
+ score_percent: { type: 'integer', minimum: 0, maximum: 100, description: 'Share of stored live conversations scored.' },
283
+ turn_limit: { type: ['integer', 'null'], minimum: 0, description: 'The most live turns stored per period; null removes the limit.' },
284
+ turn_limit_period: { type: 'string', enum: ['day', 'week', 'month'] },
285
+ score_limit: { type: ['integer', 'null'], minimum: 0, description: 'The most live conversations scored per period; null removes the limit.' },
286
+ score_limit_period: { type: 'string', enum: ['day', 'week', 'month'] },
287
+ },
288
+ required: ['enabled'],
289
+ additionalProperties: false,
290
+ },
291
+ },
292
+ ];
293
+ const workspaceRoot = () => path.resolve(process.env.QUALILOOP_WORKSPACE || process.cwd());
294
+ export const insideWorkspace = (file, root = workspaceRoot()) => {
295
+ const resolved = path.resolve(root, file);
296
+ const relative = path.relative(root, resolved);
297
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
298
+ throw new ApiError(`${file} is outside the workspace ${root}.`, 400, 2);
299
+ }
300
+ return resolved;
301
+ };
302
+ export const actionTool = (spec) => ({
303
+ name: spec.name,
304
+ description: spec.description,
305
+ inputSchema: spec.input_schema,
306
+ annotations: {
307
+ title: spec.title,
308
+ readOnlyHint: spec.read_only,
309
+ destructiveHint: !spec.read_only && spec.confirm === 'always',
310
+ openWorldHint: spec.launches_work,
311
+ },
312
+ });
313
+ const text = (value) => ({
314
+ content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }],
315
+ });
316
+ const failure = (message) => ({ ...text(message), isError: true });
317
+ export const createServer = (client = new QualiloopClient()) => {
318
+ const server = new Server({ name: 'qualiloop', version: VERSION }, { capabilities: { tools: { listChanged: true } }, instructions: INSTRUCTIONS });
319
+ let catalog;
320
+ let pendingSignIn;
321
+ const actions = async () => {
322
+ catalog = catalog ?? (await loadCatalog(client));
323
+ return catalog;
324
+ };
325
+ const reloadTools = () => {
326
+ catalog = undefined;
327
+ server.sendToolListChanged().catch(() => undefined);
328
+ };
329
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
330
+ const specs = await actions();
331
+ const tools = specs
332
+ .filter((spec) => spec.available)
333
+ .map(actionTool);
334
+ return { tools: [...tools, ...LOCAL_TOOLS] };
335
+ });
336
+ const withProject = (args, spec) => {
337
+ const properties = (spec?.input_schema.properties ?? { project: {} });
338
+ if (!('project' in properties) || args.project !== undefined)
339
+ return args;
340
+ const project = resolveProject(client.url);
341
+ return project === undefined ? args : { ...args, project };
342
+ };
343
+ const local = async (name, args) => {
344
+ const project = (args.project ?? resolveProject(client.url));
345
+ const named = args.project;
346
+ switch (name) {
347
+ case 'qualiloop_status': {
348
+ const waiting = pendingSignIn;
349
+ if (!client.isSignedIn() && waiting?.settled && !waiting.error) {
350
+ const seconds = Math.min(STATUS_WAIT_MAX_SECONDS, Math.max(0, Number(args.wait_seconds ?? STATUS_WAIT_SECONDS)));
351
+ let timer;
352
+ await Promise.race([
353
+ waiting.settled,
354
+ new Promise((resolve) => {
355
+ timer = setTimeout(resolve, seconds * 1000);
356
+ }),
357
+ ]);
358
+ clearTimeout(timer);
359
+ }
360
+ const stored = storedCredentials(client.url);
361
+ if (!client.isSignedIn()) {
362
+ return {
363
+ signed_in: false,
364
+ url: client.url,
365
+ sign_in: pendingSignIn?.error
366
+ ? `The last sign-in failed: ${pendingSignIn.error}`
367
+ : pendingSignIn
368
+ ? `Waiting for approval at ${pendingSignIn.url} (code ${pendingSignIn.code}). Call qualiloop_status again; do not ask the user to say when they are done.`
369
+ : 'Call sign_in.',
370
+ };
371
+ }
372
+ const me = await client.request('GET', '/v1/auth/me');
373
+ reloadTools();
374
+ return {
375
+ signed_in: true,
376
+ url: client.url,
377
+ email: me.email,
378
+ role: me.role,
379
+ organization: stored?.user?.organization_name ?? null,
380
+ default_project: resolveProject(client.url) ?? null,
381
+ };
382
+ }
383
+ case 'sign_in': {
384
+ if (client.isSignedIn())
385
+ return { signed_in: true, url: client.url };
386
+ pendingSignIn = {};
387
+ let settled = Promise.resolve();
388
+ const started = new Promise((resolve) => {
389
+ settled = login(client, {
390
+ client: 'mcp',
391
+ again: 'Call sign_in again.',
392
+ onStarted: ({ url, code }) => {
393
+ pendingSignIn = { url, code, settled };
394
+ resolve(pendingSignIn);
395
+ },
396
+ }).then(() => {
397
+ pendingSignIn = undefined;
398
+ reloadTools();
399
+ }, (error) => {
400
+ pendingSignIn = { error: error instanceof Error ? error.message : String(error) };
401
+ resolve(pendingSignIn);
402
+ });
403
+ });
404
+ const pending = await started;
405
+ if (pending.error)
406
+ throw new Error(pending.error);
407
+ return {
408
+ approve_at: pending.url,
409
+ code: pending.code,
410
+ next_step: 'Tell the user to open the link (it opened in their browser if one is available), check that the page shows this code, and approve; with no account yet, they create one from that page. Do not ask them to tell you when they are done: call qualiloop_status now, which waits up to a minute for the approval, and again each time it answers signed_in false.',
411
+ };
412
+ }
413
+ case 'wait_for_runs': {
414
+ const minutes = Math.min(10, Math.max(1, Number(args.minutes ?? 5)));
415
+ try {
416
+ const runs = await waitForBatch(client, project, String(args.batch), {
417
+ timeoutMinutes: minutes,
418
+ });
419
+ const comparison = await compareBatch(client, project, String(args.batch)).catch((error) => ({ error: `Could not compare with the previous runs: ${error.message}` }));
420
+ return { all_finished: true, runs, comparison };
421
+ }
422
+ catch (error) {
423
+ if (error instanceof ApiError && error.exitCode === 5) {
424
+ const listed = await client.action('list_runs', { project, batch: args.batch, limit: 500 });
425
+ return { ...listed, note: `Not finished after ${minutes} minutes. Call wait_for_runs again.` };
426
+ }
427
+ throw error;
428
+ }
429
+ }
430
+ case 'connect_agent': {
431
+ const started = await connect.start(client, {
432
+ project: named === undefined ? undefined : String(named),
433
+ dir: workspaceRoot(),
434
+ file: insideWorkspace(String(args.file ?? '.env')),
435
+ ask: (projects) => `Ask the user which project to connect, then call connect_agent with its number: ${projects
436
+ .map((item) => `#${item.number} ${item.name}`)
437
+ .join(', ')}.`,
438
+ });
439
+ let steps;
440
+ try {
441
+ steps = (await connect.skill(client)).text;
442
+ }
443
+ catch (error) {
444
+ steps = `${error instanceof Error ? error.message : String(error)} Read ${client.url}/connect/SKILL.md for the steps.`;
445
+ }
446
+ return { ...started, git_note: connect.gitNote(started.env.file, started.env.git_ignored) || null, steps };
447
+ }
448
+ case 'connect_info':
449
+ return connect.info(client, { project: named });
450
+ case 'connect_projects':
451
+ return connect.projects(client);
452
+ case 'connect_create_project':
453
+ return connect.createProject(client, {
454
+ name: String(args.name),
455
+ environment: args.environment,
456
+ description: args.description,
457
+ });
458
+ case 'connect_write_env':
459
+ return connect.writeEnv(client, {
460
+ project: named,
461
+ file: insideWorkspace(String(args.file ?? '.env')),
462
+ suffix: args.suffix,
463
+ });
464
+ case 'connect_save_target': {
465
+ const { project: _ignored, env_file, ...rest } = args;
466
+ return connect.saveTarget(client, { project: named }, {
467
+ ...rest,
468
+ env_file: insideWorkspace(String(env_file ?? '.env')),
469
+ });
470
+ }
471
+ case 'connect_set_limits':
472
+ return connect.setLimits(client, { project: named }, {
473
+ max_parallel_conversations: args.max_parallel_conversations,
474
+ reply_timeout_seconds: args.reply_timeout_seconds,
475
+ });
476
+ case 'connect_save_agent_context': {
477
+ const { project: _ignored, file, overwrite, ...inline } = args;
478
+ const body = file ? connect.readJson(insideWorkspace(String(file))) : inline;
479
+ return connect.saveKnowledge(client, { project: named }, body, Boolean(overwrite));
480
+ }
481
+ case 'connect_check_traces':
482
+ return connect.checkTraces(client, { project: named }, String(args.session_id));
483
+ case 'connect_check':
484
+ return connect.check(client, { project: named });
485
+ case 'connect_set_live': {
486
+ const { project: _ignored, enabled, ...limits } = args;
487
+ return connect.setLive(client, { project: named }, {
488
+ ...limits,
489
+ enabled: Boolean(enabled),
490
+ });
491
+ }
492
+ case 'connect_set_traces':
493
+ return connect.setTraces(client, { project: named }, {
494
+ enabled: args.enabled,
495
+ delay_seconds: args.delay_seconds,
496
+ interval_seconds: args.interval_seconds,
497
+ max_wait_seconds: args.max_wait_seconds,
498
+ });
499
+ default:
500
+ throw new Error(`Unknown tool ${name}.`);
501
+ }
502
+ };
503
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
504
+ const name = request.params.name;
505
+ const args = (request.params.arguments ?? {});
506
+ try {
507
+ if (LOCAL_TOOLS.some((tool) => tool.name === name))
508
+ return text(await local(name, args));
509
+ const spec = (await actions()).find((item) => item.name === name);
510
+ if (!spec)
511
+ return failure(`Unknown tool ${name}.`);
512
+ return text(await client.action(name, withProject(args, spec)));
513
+ }
514
+ catch (error) {
515
+ return failure(error instanceof Error ? error.message : String(error));
516
+ }
517
+ });
518
+ return server;
519
+ };
520
+ export const serveStdio = async (client = new QualiloopClient()) => {
521
+ const server = createServer(client);
522
+ await server.connect(new StdioServerTransport());
523
+ };
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
+ });