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.
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;
@@ -0,0 +1,357 @@
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(client.kind === 'cli'
22
+ ? 'Sign in with `qualiloop login`, or set QUALILOOP_SETUP_TOKEN from the project\'s Coding agent settings.'
23
+ : 'Not signed in: call sign_in, then qualiloop_status until it shows the user signed in. Or set QUALILOOP_SETUP_TOKEN from the project\'s Coding agent settings.', 401, EXIT.auth);
24
+ }
25
+ if (!forProject)
26
+ return { token };
27
+ const project = options.project ?? resolveProject(client.url);
28
+ if (project === undefined || project === '') {
29
+ throw new ApiError(client.kind === 'cli'
30
+ ? 'Name the project: -p <number>, QUALILOOP_PROJECT, or `qualiloop projects use <number>` (`qualiloop connect projects` lists them).'
31
+ : 'Name the project by its number in the project argument (connect_projects lists them).', 400, EXIT.usage);
32
+ }
33
+ return { token, project };
34
+ };
35
+ const call = (client, method, path, options = {}) => {
36
+ const { token, project } = credential(client, options, !path.startsWith('/projects'));
37
+ return client.request(method, `/v1/setup${path}`, {
38
+ token,
39
+ body: options.body,
40
+ headers: projectHeader(project),
41
+ });
42
+ };
43
+ const mask = (value) => typeof value === 'string' && value.length > 8 ? `${value.slice(0, 4)}…${value.slice(-4)}` : '***';
44
+ export const info = async (client, options) => {
45
+ const body = await call(client, 'GET', '/project', options);
46
+ return {
47
+ ...body,
48
+ tracing: { ...body.tracing, project_key: mask(body.tracing.project_key) },
49
+ note: 'The project key is masked. Write it to the .env file with `qualiloop connect env`.',
50
+ };
51
+ };
52
+ export const projects = (client) => call(client, 'GET', '/projects');
53
+ export const createProject = (client, body) => call(client, 'POST', '/projects', { body }).then((created) => ({
54
+ ...created,
55
+ tracing: { ...created.tracing, project_key: mask(created.tracing.project_key) },
56
+ }));
57
+ export const updateProject = (client, options, body) => call(client, 'PATCH', '/project', { ...options, body });
58
+ export const upsertEnv = (file, values) => {
59
+ const lines = existsSync(file) ? readFileSync(file, 'utf8').split(/\r?\n/) : [];
60
+ const written = [];
61
+ for (const [name, value] of Object.entries(values)) {
62
+ const line = `${name}=${value}`;
63
+ const index = lines.findIndex((item) => item.replace(/^export\s+/, '').startsWith(`${name}=`));
64
+ if (index >= 0)
65
+ lines[index] = line;
66
+ else {
67
+ if (lines.length && lines[lines.length - 1] === '')
68
+ lines.pop();
69
+ lines.push(line);
70
+ }
71
+ written.push(name);
72
+ }
73
+ writeFileSync(file, `${lines.join('\n').replace(/\n+$/, '')}\n`, { mode: 0o600 });
74
+ return written;
75
+ };
76
+ export const readEnvValue = (name, file) => {
77
+ if (process.env[name])
78
+ return process.env[name];
79
+ if (file && existsSync(file)) {
80
+ for (const raw of readFileSync(file, 'utf8').split(/\r?\n/)) {
81
+ const line = raw.replace(/^export\s+/, '');
82
+ if (line.startsWith(`${name}=`)) {
83
+ return line.slice(name.length + 1).trim().replace(/^(['"])(.*)\1$/, '$2');
84
+ }
85
+ }
86
+ }
87
+ return undefined;
88
+ };
89
+ export const gitIgnored = (file) => {
90
+ const absolute = path.resolve(file);
91
+ const checked = spawnSync('git', ['check-ignore', '-q', absolute], {
92
+ cwd: path.dirname(absolute),
93
+ stdio: 'ignore',
94
+ });
95
+ if (checked.status === 0)
96
+ return true;
97
+ if (checked.status === 1)
98
+ return false;
99
+ return null;
100
+ };
101
+ export const gitNote = (file, ignored) => ignored === false
102
+ ? `${file} is not git-ignored. Add it to .gitignore before you commit.`
103
+ : ignored === null
104
+ ? 'Keep the file out of git.'
105
+ : '';
106
+ export const writeEnv = async (client, options) => {
107
+ const body = await call(client, 'GET', '/project', options);
108
+ const suffix = options.suffix ? `_${options.suffix.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}` : '';
109
+ const values = {};
110
+ if (body.tracing.project_key)
111
+ values[`QUALILOOP_PROJECT_KEY${suffix}`] = String(body.tracing.project_key);
112
+ if (body.tracing.traces_url)
113
+ values[`QUALILOOP_OTLP_TRACES_URL${suffix}`] = String(body.tracing.traces_url);
114
+ const written = upsertEnv(options.file, values);
115
+ return { file: options.file, written, git_ignored: gitIgnored(options.file), project: body.project };
116
+ };
117
+ export const codebaseName = (dir) => {
118
+ const read = (file) => {
119
+ try {
120
+ return readFileSync(path.join(dir, file), 'utf8');
121
+ }
122
+ catch {
123
+ return undefined;
124
+ }
125
+ };
126
+ let name;
127
+ try {
128
+ const parsed = JSON.parse(read('package.json') ?? 'null');
129
+ if (typeof parsed?.name === 'string')
130
+ name = parsed.name;
131
+ }
132
+ catch {
133
+ }
134
+ name ??= read('pyproject.toml')?.match(/^\s*name\s*=\s*["']([^"']+)["']/m)?.[1];
135
+ const cleaned = (name ?? path.basename(path.resolve(dir))).replace(/^@[^/]+\//, '').trim().slice(0, 240);
136
+ return cleaned.length >= 2 ? cleaned : 'My agent';
137
+ };
138
+ export const start = async (client, options) => {
139
+ if (process.env.QUALILOOP_SETUP_TOKEN) {
140
+ const env = await writeEnv(client, { project: options.project, file: options.file });
141
+ return { project: env.project, created: false, default_set: false, env };
142
+ }
143
+ const named = options.project || resolveProject(client.url);
144
+ let project;
145
+ let created = false;
146
+ if (named) {
147
+ const found = await client.action('get_project', { project: named, window_days: 1 });
148
+ project = { number: found.number, name: found.name };
149
+ }
150
+ else {
151
+ const listed = await client.action('list_projects', { limit: 500 });
152
+ if (listed.total > 0)
153
+ throw new ApiError(options.ask(listed.projects), 400, EXIT.usage);
154
+ const made = await client.action('create_project', {
155
+ name: codebaseName(options.dir),
156
+ });
157
+ project = { number: made.project_number, name: made.name };
158
+ created = true;
159
+ }
160
+ const default_set = Boolean(storedCredentials(client.url));
161
+ if (default_set)
162
+ setDefaultProject(client.url, String(project.number));
163
+ const env = await writeEnv(client, { project: project.number, file: options.file });
164
+ return { project, created, default_set, env };
165
+ };
166
+ export const MODES = ['endpoint', 'dify', 'async_session', 'browser', 'elevenlabs', 'gohighlevel'];
167
+ export const SECRET_FIELDS = {
168
+ observability: ['public_key', 'secret_key', 'api_key'],
169
+ elevenlabs: ['api_key'],
170
+ gohighlevel: ['private_token'],
171
+ browser: ['browserbase_context_id'],
172
+ };
173
+ export const resolveSecrets = (body, envFile) => {
174
+ for (const [block, names] of Object.entries(SECRET_FIELDS)) {
175
+ const section = body[block];
176
+ if (!section || typeof section !== 'object')
177
+ continue;
178
+ const fields = section;
179
+ for (const name of names) {
180
+ const variable = fields[`${name}_env`];
181
+ if (variable === undefined)
182
+ continue;
183
+ delete fields[`${name}_env`];
184
+ if (typeof variable !== 'string' || !variable) {
185
+ throw new ApiError(`${block}.${name}_env names the variable that holds ${block}.${name}.`, 400, EXIT.usage);
186
+ }
187
+ const value = readEnvValue(variable, envFile);
188
+ if (!value) {
189
+ throw new ApiError(`${variable} is not set in the environment${envFile ? ` or in ${envFile}` : ''}.`, 400, EXIT.usage);
190
+ }
191
+ fields[name] = value;
192
+ }
193
+ }
194
+ };
195
+ export const saveTarget = async (client, options, input) => {
196
+ const { auth_header_name, auth_header_env, auth_header_prefix, env_file, ...body } = input;
197
+ resolveSecrets(body, env_file);
198
+ if (auth_header_name && auth_header_env) {
199
+ const value = readEnvValue(auth_header_env, env_file);
200
+ if (!value) {
201
+ throw new ApiError(`${auth_header_env} is not set in the environment${env_file ? ` or in ${env_file}` : ''}.`, 400, EXIT.usage);
202
+ }
203
+ body.auth_header = `${auth_header_name}: ${auth_header_prefix ?? ''}${value}`;
204
+ }
205
+ const saved = await call(client, 'PUT', '/target', {
206
+ ...options,
207
+ body,
208
+ });
209
+ return saved;
210
+ };
211
+ export const updateTarget = async (client, options, settings, nothingGiven = 'Give at least one setting to change.') => {
212
+ const body = Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined));
213
+ if (!Object.keys(body).length)
214
+ throw new ApiError(nothingGiven, 400, EXIT.usage);
215
+ const current = await call(client, 'GET', '/project', options);
216
+ if (!current.target) {
217
+ throw new ApiError('No connection is saved for this project yet. Save it first, with these settings in the same request if you like.', 400, EXIT.usage);
218
+ }
219
+ return call(client, 'PUT', '/target', { ...options, body });
220
+ };
221
+ export const targetAddress = (target) => {
222
+ if (!target)
223
+ return 'none yet';
224
+ const block = (name) => (target[name] ?? {});
225
+ switch (target.mode) {
226
+ case 'browser':
227
+ return `browser, ${String(block('browser').chat_page_url ?? '')}`;
228
+ case 'elevenlabs': {
229
+ const agent = block('elevenlabs');
230
+ return `ElevenLabs agent ${String(agent.agent_name || agent.agent_id || '')}`.trim();
231
+ }
232
+ case 'gohighlevel':
233
+ return `GoHighLevel location ${String(block('gohighlevel').location_id ?? '')}`;
234
+ case 'async_session':
235
+ return 'session endpoint';
236
+ case 'dify':
237
+ return `Dify, ${String(target.base_url ?? '')}`;
238
+ default:
239
+ return String(target.base_url ?? '');
240
+ }
241
+ };
242
+ export const setLimits = async (client, options, limits) => {
243
+ if (limits.max_parallel_conversations === undefined && limits.reply_timeout_seconds === undefined) {
244
+ const current = await call(client, 'GET', '/project', options);
245
+ return { project: current.project, target: current.target ?? null };
246
+ }
247
+ return updateTarget(client, options, { max_parallel_conversations: limits.max_parallel_conversations, reply_timeout_seconds: limits.reply_timeout_seconds }, 'Give the conversations at once, the reply timeout, or both.');
248
+ };
249
+ export const setTraces = async (client, options, settings) => {
250
+ const timing = {
251
+ trace_fetch_delay_seconds: settings.delay_seconds,
252
+ trace_fetch_interval_seconds: settings.interval_seconds,
253
+ trace_fetch_max_wait_seconds: settings.max_wait_seconds,
254
+ };
255
+ const timingGiven = Object.values(timing).some((value) => value !== undefined);
256
+ if (settings.enabled === undefined && !timingGiven) {
257
+ throw new ApiError('Say on or off, or give the delay, the interval or the max wait.', 400, EXIT.usage);
258
+ }
259
+ const result = {};
260
+ if (settings.enabled !== undefined) {
261
+ const updated = await updateProject(client, options, { traces_disabled: !settings.enabled });
262
+ const project = updated.project;
263
+ result.project = { number: project.number, name: project.name };
264
+ result.traces_disabled = project.traces_disabled ?? !settings.enabled;
265
+ }
266
+ if (timingGiven) {
267
+ const saved = await updateTarget(client, options, timing);
268
+ result.project = saved.project;
269
+ result.target = saved.target;
270
+ }
271
+ return result;
272
+ };
273
+ export const saveKnowledge = (client, options, body, overwrite) => {
274
+ const payload = overwrite && body && typeof body === 'object' ? { ...body, overwrite: true } : body;
275
+ return call(client, 'PUT', '/knowledge', { ...options, body: payload });
276
+ };
277
+ const KIND_LABEL = {
278
+ system_prompt: 'system prompt',
279
+ tools: 'tools',
280
+ documentation: 'document',
281
+ };
282
+ const OUTCOME_LABEL = {
283
+ new: 'new',
284
+ unchanged: 'unchanged',
285
+ new_version: 'new version',
286
+ restored: 'restored',
287
+ };
288
+ export const knowledgeRender = (result) => {
289
+ const named = (item) => `${KIND_LABEL[item.kind] ?? item.kind}: ${item.name}`;
290
+ const lines = [];
291
+ const sources = result.sources ?? [];
292
+ lines.push(sources.length ? 'Sources:' : 'No sources sent.');
293
+ for (const item of sources) {
294
+ const version = item.version ? ` (version ${item.version})` : '';
295
+ lines.push(` ${(OUTCOME_LABEL[item.outcome] ?? item.outcome).padEnd(12)}${named(item)}${version}`);
296
+ }
297
+ if (result.retired?.length) {
298
+ lines.push('Retired, no longer in the code:', ...result.retired.map((item) => ` ${named(item)}`));
299
+ }
300
+ if (result.kept?.length) {
301
+ lines.push('Kept, added by a person (review them in System Knowledge, Sources):', ...result.kept.map((item) => ` ${named(item)}`));
302
+ }
303
+ if (result.skipped?.length) {
304
+ lines.push('Skipped:', ...result.skipped.map((item) => ` ${named(item)}${item.reason ? `: ${item.reason}` : ''}`));
305
+ }
306
+ const general = Object.entries(result.general ?? {});
307
+ if (general.length) {
308
+ lines.push(`General: ${general.map(([field, state]) => `${field} ${state}`).join(', ')}`);
309
+ }
310
+ if (result.ui_tools?.length)
311
+ lines.push(`UI tools: ${result.ui_tools.join(', ')}`);
312
+ lines.push(result.fill_queued
313
+ ? 'QualiLoop reads them into the system knowledge now.'
314
+ : result.change_queued
315
+ ? `Recorded as one change${result.change_id ? ` (${result.change_id})` : ''}; QualiLoop reads what changed into the system knowledge.`
316
+ : 'Nothing changed in the system knowledge.');
317
+ if (result.exploration_note)
318
+ lines.push(result.exploration_note);
319
+ return lines.join('\n');
320
+ };
321
+ 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>`.';
322
+ export const setLive = (client, options, settings) => call(client, 'PUT', '/live', {
323
+ ...options,
324
+ body: Object.fromEntries(Object.entries(settings).filter(([, value]) => value !== undefined)),
325
+ });
326
+ export const checkTraces = (client, options, sessionId) => call(client, 'POST', '/check-traces', {
327
+ ...options,
328
+ body: { session_id: sessionId },
329
+ });
330
+ export const check = (client, options) => call(client, 'POST', '/check', options);
331
+ export const disconnect = (client, options) => call(client, 'DELETE', '/target', options);
332
+ export const readJson = (file) => {
333
+ const raw = file === '-' ? readFileSync(0, 'utf8') : readFileSync(file, 'utf8');
334
+ try {
335
+ return JSON.parse(raw);
336
+ }
337
+ catch (error) {
338
+ throw new ApiError(`${file} is not valid JSON: ${error.message}`, 400, EXIT.usage);
339
+ }
340
+ };
341
+ export const skill = async (client) => {
342
+ const url = `${client.url}/connect/SKILL.md`;
343
+ const reference = `${client.url}/connect/reference.md`;
344
+ 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).`;
345
+ let text;
346
+ try {
347
+ text = await client.request('GET', '/connect/SKILL.md', { anonymous: true, headers: { Accept: 'text/markdown, text/plain' } });
348
+ }
349
+ catch (error) {
350
+ if (error instanceof ApiError && error.status === 404)
351
+ throw new ApiError(missing, 404, EXIT.notFound);
352
+ throw error;
353
+ }
354
+ if (typeof text !== 'string' || /^\s*</.test(text))
355
+ throw new ApiError(missing, 404, EXIT.notFound);
356
+ return { url, reference_url: reference, text: text.replaceAll('{QUALILOOP_URL}', client.url) };
357
+ };
package/dist/export.js ADDED
@@ -0,0 +1,114 @@
1
+ import { ApiError, EXIT } from './api.js';
2
+ const lines = (items, row) => items.map((item) => JSON.stringify(row(item))).join('\n');
3
+ const quoted = (value) => `"${value.replace(/"/g, '""')}"`;
4
+ export const EXPORT_FORMATS = [
5
+ {
6
+ id: 'openai-chat-jsonl',
7
+ label: 'OpenAI Chat JSONL',
8
+ extension: 'jsonl',
9
+ render: (items) => lines(items, (item) => ({
10
+ messages: [
11
+ { role: 'user', content: item.user_msg },
12
+ { role: 'assistant', content: item.human_gold_answer },
13
+ ],
14
+ metadata: {
15
+ conversation_id: item.conversation_id,
16
+ turn_index: item.turn_index,
17
+ guardrails_violation: item.guardrails_violation,
18
+ },
19
+ })),
20
+ },
21
+ {
22
+ id: 'openai-completion-jsonl',
23
+ label: 'OpenAI Completion JSONL',
24
+ extension: 'jsonl',
25
+ render: (items) => lines(items, (item) => ({ prompt: `${item.user_msg}\nAI:`, completion: ` ${item.human_gold_answer}\n` })),
26
+ },
27
+ {
28
+ id: 'anthropic-jsonl',
29
+ label: 'Anthropic Claude JSONL',
30
+ extension: 'jsonl',
31
+ render: (items) => lines(items, (item) => ({
32
+ system: 'You are a helpful assistant.',
33
+ input: item.user_msg,
34
+ output: item.human_gold_answer,
35
+ metadata: { conversation_id: item.conversation_id },
36
+ })),
37
+ },
38
+ {
39
+ id: 'csv',
40
+ label: 'CSV (prompt, completion)',
41
+ extension: 'csv',
42
+ render: (items) => [
43
+ 'conversation_id,turn_index,prompt,completion',
44
+ ...items.map((item) => [quoted(item.conversation_id), item.turn_index, quoted(item.user_msg), quoted(item.human_gold_answer)].join(',')),
45
+ ].join('\n'),
46
+ },
47
+ {
48
+ id: 'tsv',
49
+ label: 'TSV (prompt, completion)',
50
+ extension: 'tsv',
51
+ render: (items) => [
52
+ 'conversation_id\tturn_index\tprompt\tcompletion',
53
+ ...items.map((item) => `${item.conversation_id}\t${item.turn_index}\t${item.user_msg}\t${item.human_gold_answer}`),
54
+ ].join('\n'),
55
+ },
56
+ {
57
+ id: 'qa-json',
58
+ label: 'QA JSON array',
59
+ extension: 'json',
60
+ render: (items) => JSON.stringify(items.map((item) => ({ question: item.user_msg, answer: item.human_gold_answer })), null, 2),
61
+ },
62
+ {
63
+ id: 'prompt-completion',
64
+ label: 'Prompt + Completion plain text',
65
+ extension: 'txt',
66
+ render: (items) => items.map((item) => `Prompt:\n${item.user_msg}\n\nCompletion:\n${item.human_gold_answer}\n----`).join('\n'),
67
+ },
68
+ {
69
+ id: 'instruction-json',
70
+ label: 'Instruction JSON (instruction/input/output)',
71
+ extension: 'jsonl',
72
+ render: (items) => lines(items, (item) => ({ instruction: item.user_msg, input: '', output: item.human_gold_answer })),
73
+ },
74
+ {
75
+ id: 'cot-jsonl',
76
+ label: 'Chain-of-thought JSONL',
77
+ extension: 'jsonl',
78
+ render: (items) => lines(items, (item) => ({
79
+ question: item.user_msg,
80
+ answer: item.human_gold_answer,
81
+ reasoning: '[[ADD_REASONING_HERE]]',
82
+ })),
83
+ },
84
+ {
85
+ id: 'json-batching',
86
+ label: 'Batch JSON',
87
+ extension: 'json',
88
+ render: (items) => JSON.stringify({ generated_at: new Date().toISOString(), total: items.length, pairs: items }, null, 2),
89
+ },
90
+ ];
91
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
92
+ export const dateOr = (given, daysBack) => {
93
+ if (given !== undefined) {
94
+ if (!DATE.test(given))
95
+ throw new ApiError(`${given} is not a date like 2026-11-17.`, 400, EXIT.usage);
96
+ return given;
97
+ }
98
+ const day = new Date();
99
+ day.setUTCDate(day.getUTCDate() - daysBack);
100
+ return day.toISOString().slice(0, 10);
101
+ };
102
+ export const exportFormat = (id) => {
103
+ const found = EXPORT_FORMATS.find((item) => item.id === id);
104
+ if (!found) {
105
+ throw new ApiError(`Unknown format ${id}. Formats: ${EXPORT_FORMATS.map((item) => item.id).join(', ')}.`, 400, EXIT.usage);
106
+ }
107
+ return found;
108
+ };
109
+ export const fetchCorrectedPairs = async (client, project, from, to) => {
110
+ const shown = await client.action('get_project', { project });
111
+ const found = await client.request('GET', `/v1/projects/by-number/${shown.number}`);
112
+ const data = await client.request('GET', `/v1/export/project/${found.id}?start_date=${from}&end_date=${to}`);
113
+ return { number: shown.number, name: shown.name, items: data.items ?? [] };
114
+ };