qualiloop 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +211 -3
- package/dist/api.js +121 -0
- package/dist/auth.js +68 -0
- package/dist/catalog.js +24 -0
- package/dist/catalog.json +3912 -0
- package/dist/cli.js +1480 -0
- package/dist/config.js +76 -0
- package/dist/connect.js +260 -0
- package/dist/mcp/install.js +142 -0
- package/dist/mcp/server.js +422 -0
- package/dist/output.js +43 -0
- package/dist/workflows.js +147 -0
- package/package.json +48 -6
package/dist/config.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
export const DEFAULT_URL = 'https://app.qualiloop.com';
|
|
5
|
+
export const configDir = () => {
|
|
6
|
+
if (process.env.QUALILOOP_CONFIG_DIR)
|
|
7
|
+
return process.env.QUALILOOP_CONFIG_DIR;
|
|
8
|
+
if (process.platform === 'win32') {
|
|
9
|
+
const base = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
|
|
10
|
+
return path.join(base, 'qualiloop');
|
|
11
|
+
}
|
|
12
|
+
const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
|
|
13
|
+
return path.join(base, 'qualiloop');
|
|
14
|
+
};
|
|
15
|
+
export const credentialsPath = () => path.join(configDir(), 'credentials.json');
|
|
16
|
+
export const normalizeUrl = (url) => {
|
|
17
|
+
const trimmed = url.trim().replace(/\/+$/, '');
|
|
18
|
+
return trimmed.replace(/\/v1$/, '');
|
|
19
|
+
};
|
|
20
|
+
const read = () => {
|
|
21
|
+
const file = credentialsPath();
|
|
22
|
+
if (!existsSync(file))
|
|
23
|
+
return { hosts: {} };
|
|
24
|
+
try {
|
|
25
|
+
const parsed = JSON.parse(readFileSync(file, 'utf8'));
|
|
26
|
+
return { default_url: parsed.default_url, hosts: parsed.hosts || {} };
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return { hosts: {} };
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
const write = (data) => {
|
|
33
|
+
const dir = configDir();
|
|
34
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
35
|
+
const file = credentialsPath();
|
|
36
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
37
|
+
writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
|
|
38
|
+
renameSync(temp, file);
|
|
39
|
+
try {
|
|
40
|
+
chmodSync(file, 0o600);
|
|
41
|
+
chmodSync(dir, 0o700);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
export const resolveUrl = (flag) => {
|
|
47
|
+
const chosen = flag || process.env.QUALILOOP_URL || read().default_url || DEFAULT_URL;
|
|
48
|
+
return normalizeUrl(chosen);
|
|
49
|
+
};
|
|
50
|
+
export const storedCredentials = (url) => read().hosts[normalizeUrl(url)];
|
|
51
|
+
export const saveCredentials = (url, credentials) => {
|
|
52
|
+
const data = read();
|
|
53
|
+
const key = normalizeUrl(url);
|
|
54
|
+
data.hosts[key] = { ...data.hosts[key], ...credentials };
|
|
55
|
+
data.default_url = key;
|
|
56
|
+
write(data);
|
|
57
|
+
};
|
|
58
|
+
export const forgetCredentials = (url) => {
|
|
59
|
+
const data = read();
|
|
60
|
+
const key = normalizeUrl(url);
|
|
61
|
+
if (!data.hosts[key])
|
|
62
|
+
return false;
|
|
63
|
+
delete data.hosts[key];
|
|
64
|
+
write(data);
|
|
65
|
+
return true;
|
|
66
|
+
};
|
|
67
|
+
export const setDefaultProject = (url, project) => {
|
|
68
|
+
const data = read();
|
|
69
|
+
const key = normalizeUrl(url);
|
|
70
|
+
const current = data.hosts[key];
|
|
71
|
+
if (!current)
|
|
72
|
+
throw new Error('Sign in first: qualiloop login');
|
|
73
|
+
data.hosts[key] = { ...current, project };
|
|
74
|
+
write(data);
|
|
75
|
+
};
|
|
76
|
+
export const resolveProject = (url, flag) => flag || process.env.QUALILOOP_PROJECT || storedCredentials(url)?.project || undefined;
|
package/dist/connect.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { ApiError, EXIT } from './api.js';
|
|
5
|
+
import { resolveProject, setDefaultProject, storedCredentials } from './config.js';
|
|
6
|
+
const projectHeader = (project) => {
|
|
7
|
+
if (project === undefined || project === '')
|
|
8
|
+
return {};
|
|
9
|
+
const number = String(project).replace(/^#/, '').trim();
|
|
10
|
+
if (!/^\d+$/.test(number)) {
|
|
11
|
+
throw new ApiError('Name the project by its number here (qualiloop projects shows them).', 400, EXIT.usage);
|
|
12
|
+
}
|
|
13
|
+
return { 'X-Qualiloop-Project': number };
|
|
14
|
+
};
|
|
15
|
+
const credential = (client, options, forProject) => {
|
|
16
|
+
const setupToken = process.env.QUALILOOP_SETUP_TOKEN;
|
|
17
|
+
if (setupToken)
|
|
18
|
+
return { token: setupToken, project: forProject ? options.project : undefined };
|
|
19
|
+
const token = client.token();
|
|
20
|
+
if (!token) {
|
|
21
|
+
throw new ApiError('Sign in with `qualiloop login`, or set QUALILOOP_SETUP_TOKEN from the project\'s Coding agent settings.', 401, EXIT.auth);
|
|
22
|
+
}
|
|
23
|
+
if (!forProject)
|
|
24
|
+
return { token };
|
|
25
|
+
const project = options.project ?? resolveProject(client.url);
|
|
26
|
+
if (project === undefined || project === '') {
|
|
27
|
+
throw new ApiError(client.kind === 'cli'
|
|
28
|
+
? 'Name the project: -p <number>, QUALILOOP_PROJECT, or `qualiloop projects use <number>` (`qualiloop connect projects` lists them).'
|
|
29
|
+
: 'Name the project by its number in the project argument (connect_projects lists them).', 400, EXIT.usage);
|
|
30
|
+
}
|
|
31
|
+
return { token, project };
|
|
32
|
+
};
|
|
33
|
+
const call = (client, method, path, options = {}) => {
|
|
34
|
+
const { token, project } = credential(client, options, !path.startsWith('/projects'));
|
|
35
|
+
return client.request(method, `/v1/setup${path}`, {
|
|
36
|
+
token,
|
|
37
|
+
body: options.body,
|
|
38
|
+
headers: projectHeader(project),
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
const mask = (value) => typeof value === 'string' && value.length > 8 ? `${value.slice(0, 4)}…${value.slice(-4)}` : '***';
|
|
42
|
+
export const info = async (client, options) => {
|
|
43
|
+
const body = await call(client, 'GET', '/project', options);
|
|
44
|
+
return {
|
|
45
|
+
...body,
|
|
46
|
+
tracing: { ...body.tracing, project_key: mask(body.tracing.project_key) },
|
|
47
|
+
note: 'The project key is masked. Write it to the .env file with `qualiloop connect env`.',
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
export const projects = (client) => call(client, 'GET', '/projects');
|
|
51
|
+
export const createProject = (client, body) => call(client, 'POST', '/projects', { body }).then((created) => ({
|
|
52
|
+
...created,
|
|
53
|
+
tracing: { ...created.tracing, project_key: mask(created.tracing.project_key) },
|
|
54
|
+
}));
|
|
55
|
+
export const updateProject = (client, options, body) => call(client, 'PATCH', '/project', { ...options, body });
|
|
56
|
+
export const upsertEnv = (file, values) => {
|
|
57
|
+
const lines = existsSync(file) ? readFileSync(file, 'utf8').split(/\r?\n/) : [];
|
|
58
|
+
const written = [];
|
|
59
|
+
for (const [name, value] of Object.entries(values)) {
|
|
60
|
+
const line = `${name}=${value}`;
|
|
61
|
+
const index = lines.findIndex((item) => item.replace(/^export\s+/, '').startsWith(`${name}=`));
|
|
62
|
+
if (index >= 0)
|
|
63
|
+
lines[index] = line;
|
|
64
|
+
else {
|
|
65
|
+
if (lines.length && lines[lines.length - 1] === '')
|
|
66
|
+
lines.pop();
|
|
67
|
+
lines.push(line);
|
|
68
|
+
}
|
|
69
|
+
written.push(name);
|
|
70
|
+
}
|
|
71
|
+
writeFileSync(file, `${lines.join('\n').replace(/\n+$/, '')}\n`, { mode: 0o600 });
|
|
72
|
+
return written;
|
|
73
|
+
};
|
|
74
|
+
export const readEnvValue = (name, file) => {
|
|
75
|
+
if (process.env[name])
|
|
76
|
+
return process.env[name];
|
|
77
|
+
if (file && existsSync(file)) {
|
|
78
|
+
for (const raw of readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
79
|
+
const line = raw.replace(/^export\s+/, '');
|
|
80
|
+
if (line.startsWith(`${name}=`)) {
|
|
81
|
+
return line.slice(name.length + 1).trim().replace(/^(['"])(.*)\1$/, '$2');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
};
|
|
87
|
+
export const gitIgnored = (file) => {
|
|
88
|
+
const absolute = path.resolve(file);
|
|
89
|
+
const checked = spawnSync('git', ['check-ignore', '-q', absolute], {
|
|
90
|
+
cwd: path.dirname(absolute),
|
|
91
|
+
stdio: 'ignore',
|
|
92
|
+
});
|
|
93
|
+
if (checked.status === 0)
|
|
94
|
+
return true;
|
|
95
|
+
if (checked.status === 1)
|
|
96
|
+
return false;
|
|
97
|
+
return null;
|
|
98
|
+
};
|
|
99
|
+
export const gitNote = (file, ignored) => ignored === false
|
|
100
|
+
? `${file} is not git-ignored. Add it to .gitignore before you commit.`
|
|
101
|
+
: ignored === null
|
|
102
|
+
? 'Keep the file out of git.'
|
|
103
|
+
: '';
|
|
104
|
+
export const writeEnv = async (client, options) => {
|
|
105
|
+
const body = await call(client, 'GET', '/project', options);
|
|
106
|
+
const suffix = options.suffix ? `_${options.suffix.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}` : '';
|
|
107
|
+
const values = {};
|
|
108
|
+
if (body.tracing.project_key)
|
|
109
|
+
values[`QUALILOOP_PROJECT_KEY${suffix}`] = String(body.tracing.project_key);
|
|
110
|
+
if (body.tracing.traces_url)
|
|
111
|
+
values[`QUALILOOP_OTLP_TRACES_URL${suffix}`] = String(body.tracing.traces_url);
|
|
112
|
+
const written = upsertEnv(options.file, values);
|
|
113
|
+
return { file: options.file, written, git_ignored: gitIgnored(options.file), project: body.project };
|
|
114
|
+
};
|
|
115
|
+
export const codebaseName = (dir) => {
|
|
116
|
+
const read = (file) => {
|
|
117
|
+
try {
|
|
118
|
+
return readFileSync(path.join(dir, file), 'utf8');
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
let name;
|
|
125
|
+
try {
|
|
126
|
+
const parsed = JSON.parse(read('package.json') ?? 'null');
|
|
127
|
+
if (typeof parsed?.name === 'string')
|
|
128
|
+
name = parsed.name;
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
}
|
|
132
|
+
name ??= read('pyproject.toml')?.match(/^\s*name\s*=\s*["']([^"']+)["']/m)?.[1];
|
|
133
|
+
const cleaned = (name ?? path.basename(path.resolve(dir))).replace(/^@[^/]+\//, '').trim().slice(0, 240);
|
|
134
|
+
return cleaned.length >= 2 ? cleaned : 'My agent';
|
|
135
|
+
};
|
|
136
|
+
export const start = async (client, options) => {
|
|
137
|
+
if (process.env.QUALILOOP_SETUP_TOKEN) {
|
|
138
|
+
const env = await writeEnv(client, { project: options.project, file: options.file });
|
|
139
|
+
return { project: env.project, created: false, default_set: false, env };
|
|
140
|
+
}
|
|
141
|
+
const named = options.project || resolveProject(client.url);
|
|
142
|
+
let project;
|
|
143
|
+
let created = false;
|
|
144
|
+
if (named) {
|
|
145
|
+
const found = await client.action('get_project', { project: named, window_days: 1 });
|
|
146
|
+
project = { number: found.number, name: found.name };
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
const listed = await client.action('list_projects', { limit: 500 });
|
|
150
|
+
if (listed.total > 0)
|
|
151
|
+
throw new ApiError(options.ask(listed.projects), 400, EXIT.usage);
|
|
152
|
+
const made = await client.action('create_project', {
|
|
153
|
+
name: codebaseName(options.dir),
|
|
154
|
+
});
|
|
155
|
+
project = { number: made.project_number, name: made.name };
|
|
156
|
+
created = true;
|
|
157
|
+
}
|
|
158
|
+
const default_set = Boolean(storedCredentials(client.url));
|
|
159
|
+
if (default_set)
|
|
160
|
+
setDefaultProject(client.url, String(project.number));
|
|
161
|
+
const env = await writeEnv(client, { project: project.number, file: options.file });
|
|
162
|
+
return { project, created, default_set, env };
|
|
163
|
+
};
|
|
164
|
+
export const saveTarget = async (client, options, input) => {
|
|
165
|
+
const { auth_header_name, auth_header_env, auth_header_prefix, env_file, ...body } = input;
|
|
166
|
+
if (auth_header_name && auth_header_env) {
|
|
167
|
+
const value = readEnvValue(auth_header_env, env_file);
|
|
168
|
+
if (!value) {
|
|
169
|
+
throw new ApiError(`${auth_header_env} is not set in the environment${env_file ? ` or in ${env_file}` : ''}.`, 400, EXIT.usage);
|
|
170
|
+
}
|
|
171
|
+
body.auth_header = `${auth_header_name}: ${auth_header_prefix ?? ''}${value}`;
|
|
172
|
+
}
|
|
173
|
+
const saved = await call(client, 'PUT', '/target', {
|
|
174
|
+
...options,
|
|
175
|
+
body,
|
|
176
|
+
});
|
|
177
|
+
return saved;
|
|
178
|
+
};
|
|
179
|
+
export const saveKnowledge = (client, options, body, overwrite) => {
|
|
180
|
+
const payload = overwrite && body && typeof body === 'object' ? { ...body, overwrite: true } : body;
|
|
181
|
+
return call(client, 'PUT', '/knowledge', { ...options, body: payload });
|
|
182
|
+
};
|
|
183
|
+
const KIND_LABEL = {
|
|
184
|
+
system_prompt: 'system prompt',
|
|
185
|
+
tools: 'tools',
|
|
186
|
+
documentation: 'document',
|
|
187
|
+
};
|
|
188
|
+
const OUTCOME_LABEL = {
|
|
189
|
+
new: 'new',
|
|
190
|
+
unchanged: 'unchanged',
|
|
191
|
+
new_version: 'new version',
|
|
192
|
+
restored: 'restored',
|
|
193
|
+
};
|
|
194
|
+
export const knowledgeRender = (result) => {
|
|
195
|
+
const named = (item) => `${KIND_LABEL[item.kind] ?? item.kind}: ${item.name}`;
|
|
196
|
+
const lines = [];
|
|
197
|
+
const sources = result.sources ?? [];
|
|
198
|
+
lines.push(sources.length ? 'Sources:' : 'No sources sent.');
|
|
199
|
+
for (const item of sources) {
|
|
200
|
+
const version = item.version ? ` (version ${item.version})` : '';
|
|
201
|
+
lines.push(` ${(OUTCOME_LABEL[item.outcome] ?? item.outcome).padEnd(12)}${named(item)}${version}`);
|
|
202
|
+
}
|
|
203
|
+
if (result.retired?.length) {
|
|
204
|
+
lines.push('Retired, no longer in the code:', ...result.retired.map((item) => ` ${named(item)}`));
|
|
205
|
+
}
|
|
206
|
+
if (result.kept?.length) {
|
|
207
|
+
lines.push('Kept, added by a person (review them in System Knowledge, Sources):', ...result.kept.map((item) => ` ${named(item)}`));
|
|
208
|
+
}
|
|
209
|
+
if (result.skipped?.length) {
|
|
210
|
+
lines.push('Skipped:', ...result.skipped.map((item) => ` ${named(item)}${item.reason ? `: ${item.reason}` : ''}`));
|
|
211
|
+
}
|
|
212
|
+
const general = Object.entries(result.general ?? {});
|
|
213
|
+
if (general.length) {
|
|
214
|
+
lines.push(`General: ${general.map(([field, state]) => `${field} ${state}`).join(', ')}`);
|
|
215
|
+
}
|
|
216
|
+
if (result.ui_tools?.length)
|
|
217
|
+
lines.push(`UI tools: ${result.ui_tools.join(', ')}`);
|
|
218
|
+
lines.push(result.fill_queued
|
|
219
|
+
? 'QualiLoop reads them into the system knowledge now.'
|
|
220
|
+
: result.change_queued
|
|
221
|
+
? `Recorded as one change${result.change_id ? ` (${result.change_id})` : ''}; QualiLoop reads what changed into the system knowledge.`
|
|
222
|
+
: 'Nothing changed in the system knowledge.');
|
|
223
|
+
if (result.exploration_note)
|
|
224
|
+
lines.push(result.exploration_note);
|
|
225
|
+
return lines.join('\n');
|
|
226
|
+
};
|
|
227
|
+
export const TRACE_FIELDS_GONE = 'Trace fields are no longer needed: QualiLoop reads the system prompts and tools from each trace by their role. Send the prompts with `qualiloop connect knowledge --file <json>`.';
|
|
228
|
+
export const setLive = (client, options, body) => call(client, 'PUT', '/live', { ...options, body });
|
|
229
|
+
export const checkTraces = (client, options, sessionId) => call(client, 'POST', '/check-traces', {
|
|
230
|
+
...options,
|
|
231
|
+
body: { session_id: sessionId },
|
|
232
|
+
});
|
|
233
|
+
export const check = (client, options) => call(client, 'POST', '/check', options);
|
|
234
|
+
export const disconnect = (client, options) => call(client, 'DELETE', '/target', options);
|
|
235
|
+
export const readJson = (file) => {
|
|
236
|
+
const raw = file === '-' ? readFileSync(0, 'utf8') : readFileSync(file, 'utf8');
|
|
237
|
+
try {
|
|
238
|
+
return JSON.parse(raw);
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
throw new ApiError(`${file} is not valid JSON: ${error.message}`, 400, EXIT.usage);
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
export const skill = async (client) => {
|
|
245
|
+
const url = `${client.url}/connect/SKILL.md`;
|
|
246
|
+
const reference = `${client.url}/connect/reference.md`;
|
|
247
|
+
const missing = `${url} did not return the guide. Open it in a browser, or pass the app's address with --url (the address you open QualiLoop at).`;
|
|
248
|
+
let text;
|
|
249
|
+
try {
|
|
250
|
+
text = await client.request('GET', '/connect/SKILL.md', { anonymous: true, headers: { Accept: 'text/markdown, text/plain' } });
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
if (error instanceof ApiError && error.status === 404)
|
|
254
|
+
throw new ApiError(missing, 404, EXIT.notFound);
|
|
255
|
+
throw error;
|
|
256
|
+
}
|
|
257
|
+
if (typeof text !== 'string' || /^\s*</.test(text))
|
|
258
|
+
throw new ApiError(missing, 404, EXIT.notFound);
|
|
259
|
+
return { url, reference_url: reference, text: text.replaceAll('{QUALILOOP_URL}', client.url) };
|
|
260
|
+
};
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { DEFAULT_URL } from '../config.js';
|
|
7
|
+
export const CLIENTS = ['claude-code', 'cursor', 'vscode', 'windsurf', 'claude-desktop', 'codex'];
|
|
8
|
+
export const DEFAULT_CLIENTS = ['claude-desktop'];
|
|
9
|
+
export const serverCommand = (url) => {
|
|
10
|
+
const cli = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'cli.js');
|
|
11
|
+
const command = { command: process.execPath, args: [cli, 'mcp'] };
|
|
12
|
+
if (url !== DEFAULT_URL)
|
|
13
|
+
command.env = { QUALILOOP_URL: url };
|
|
14
|
+
return command;
|
|
15
|
+
};
|
|
16
|
+
const home = os.homedir();
|
|
17
|
+
const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming');
|
|
18
|
+
export const configFile = (client, scope, cwd) => {
|
|
19
|
+
switch (client) {
|
|
20
|
+
case 'claude-code':
|
|
21
|
+
return scope === 'project' ? path.join(cwd, '.mcp.json') : null;
|
|
22
|
+
case 'cursor':
|
|
23
|
+
return scope === 'project' ? path.join(cwd, '.cursor', 'mcp.json') : path.join(home, '.cursor', 'mcp.json');
|
|
24
|
+
case 'vscode':
|
|
25
|
+
return path.join(cwd, '.vscode', 'mcp.json');
|
|
26
|
+
case 'windsurf':
|
|
27
|
+
return path.join(home, '.codeium', 'windsurf', 'mcp_config.json');
|
|
28
|
+
case 'claude-desktop':
|
|
29
|
+
return process.platform === 'win32'
|
|
30
|
+
? path.join(appData, 'Claude', 'claude_desktop_config.json')
|
|
31
|
+
: process.platform === 'darwin'
|
|
32
|
+
? path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
|
|
33
|
+
: path.join(home, '.config', 'Claude', 'claude_desktop_config.json');
|
|
34
|
+
case 'codex':
|
|
35
|
+
return path.join(home, '.codex', 'config.toml');
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
const readJsonFile = (file) => {
|
|
39
|
+
if (!existsSync(file))
|
|
40
|
+
return {};
|
|
41
|
+
const raw = readFileSync(file, 'utf8').trim();
|
|
42
|
+
if (!raw)
|
|
43
|
+
return {};
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(raw);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
throw new Error(`${file} is not valid JSON; fix it or add the server by hand (qualiloop mcp install --print).`);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
export const entryFor = (client, command) => client === 'vscode' ? { type: 'stdio', ...command } : { ...command };
|
|
52
|
+
const writeJsonConfig = (client, file, command) => {
|
|
53
|
+
const config = readJsonFile(file);
|
|
54
|
+
const key = client === 'vscode' ? 'servers' : 'mcpServers';
|
|
55
|
+
const servers = config[key] ?? {};
|
|
56
|
+
servers.qualiloop = entryFor(client, command);
|
|
57
|
+
config[key] = servers;
|
|
58
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
59
|
+
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
|
|
60
|
+
};
|
|
61
|
+
const tomlString = (value) => JSON.stringify(value);
|
|
62
|
+
export const codexSection = (command) => {
|
|
63
|
+
const lines = [
|
|
64
|
+
'[mcp_servers.qualiloop]',
|
|
65
|
+
`command = ${tomlString(command.command)}`,
|
|
66
|
+
`args = [${command.args.map(tomlString).join(', ')}]`,
|
|
67
|
+
];
|
|
68
|
+
if (command.env) {
|
|
69
|
+
lines.push(`env = { ${Object.entries(command.env)
|
|
70
|
+
.map(([key, value]) => `${key} = ${tomlString(value)}`)
|
|
71
|
+
.join(', ')} }`);
|
|
72
|
+
}
|
|
73
|
+
return lines.join('\n');
|
|
74
|
+
};
|
|
75
|
+
const writeCodex = (file, command) => {
|
|
76
|
+
const existing = existsSync(file) ? readFileSync(file, 'utf8') : '';
|
|
77
|
+
const without = existing.replace(/\n?\[mcp_servers\.qualiloop\][\s\S]*?(?=\n\[|$)/, '').trimEnd();
|
|
78
|
+
mkdirSync(path.dirname(file), { recursive: true });
|
|
79
|
+
writeFileSync(file, `${without ? `${without}\n\n` : ''}${codexSection(command)}\n`);
|
|
80
|
+
};
|
|
81
|
+
export const install = (clients, options) => {
|
|
82
|
+
const cwd = options.cwd ?? process.cwd();
|
|
83
|
+
const command = serverCommand(options.url);
|
|
84
|
+
return clients.map((client) => {
|
|
85
|
+
if (client === 'claude-code' && options.scope === 'user') {
|
|
86
|
+
const args = claudeAddArgs(command);
|
|
87
|
+
const ran = spawnSync('claude', args, { stdio: 'pipe', shell: process.platform === 'win32' });
|
|
88
|
+
if (ran.status === 0)
|
|
89
|
+
return { client, done: true, where: 'claude mcp add --scope user' };
|
|
90
|
+
const byHand = `Run: claude ${args.map((arg) => (/\s/.test(arg) ? JSON.stringify(arg) : arg)).join(' ')}`;
|
|
91
|
+
const output = `${ran.stderr ?? ''}`.trim() || `${ran.stdout ?? ''}`.trim();
|
|
92
|
+
const missing = Boolean(ran.error) || ran.status === 127 || /not recognized|not found/i.test(output);
|
|
93
|
+
return {
|
|
94
|
+
client,
|
|
95
|
+
done: false,
|
|
96
|
+
where: missing
|
|
97
|
+
? `Claude Code CLI not found. ${byHand}`
|
|
98
|
+
: `claude mcp add failed: ${output || `exit code ${ran.status}`}. ${byHand}`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const file = configFile(client, options.scope, cwd);
|
|
102
|
+
if (!file)
|
|
103
|
+
return { client, done: false, where: 'not supported' };
|
|
104
|
+
if (client === 'codex')
|
|
105
|
+
writeCodex(file, command);
|
|
106
|
+
else
|
|
107
|
+
writeJsonConfig(client, file, command);
|
|
108
|
+
return { client, done: true, where: file };
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
export const claudeAddArgs = (command) => {
|
|
112
|
+
const args = ['mcp', 'add', '--scope', 'user'];
|
|
113
|
+
for (const [key, value] of Object.entries(command.env ?? {}))
|
|
114
|
+
args.push('-e', `${key}=${value}`);
|
|
115
|
+
args.push('qualiloop', '--', command.command, ...command.args);
|
|
116
|
+
return args;
|
|
117
|
+
};
|
|
118
|
+
const LABELS = {
|
|
119
|
+
'claude-code': 'Claude Code',
|
|
120
|
+
cursor: 'Cursor (~/.cursor/mcp.json)',
|
|
121
|
+
windsurf: 'Windsurf (~/.codeium/windsurf/mcp_config.json)',
|
|
122
|
+
'claude-desktop': 'Claude Desktop (claude_desktop_config.json)',
|
|
123
|
+
vscode: 'VS Code (.vscode/mcp.json)',
|
|
124
|
+
codex: 'Codex (~/.codex/config.toml)',
|
|
125
|
+
};
|
|
126
|
+
export const snippets = (url, clients = CLIENTS) => {
|
|
127
|
+
const command = serverCommand(url);
|
|
128
|
+
const quote = (part) => (/^[\w./:=@-]+$/.test(part) ? part : JSON.stringify(part));
|
|
129
|
+
const one = (client) => {
|
|
130
|
+
switch (client) {
|
|
131
|
+
case 'claude-code':
|
|
132
|
+
return ` claude ${claudeAddArgs(command).map(quote).join(' ')}`;
|
|
133
|
+
case 'vscode':
|
|
134
|
+
return JSON.stringify({ servers: { qualiloop: entryFor('vscode', command) } }, null, 2);
|
|
135
|
+
case 'codex':
|
|
136
|
+
return codexSection(command);
|
|
137
|
+
default:
|
|
138
|
+
return JSON.stringify({ mcpServers: { qualiloop: entryFor(client, command) } }, null, 2);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
return clients.map((client) => `${LABELS[client]}:\n${one(client)}`).join('\n\n');
|
|
142
|
+
};
|