@vespermcp/mcp-server 1.2.21 → 1.2.24

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.
Files changed (47) hide show
  1. package/README.md +49 -0
  2. package/build/cache/service.js +7 -0
  3. package/build/cloud/adapters/supabase.js +49 -0
  4. package/build/cloud/storage-manager.js +6 -0
  5. package/build/export/exporter.js +22 -9
  6. package/build/gateway/unified-dataset-gateway.js +441 -0
  7. package/build/index.js +1815 -839
  8. package/build/ingestion/ingestor.js +7 -4
  9. package/build/install/install-service.js +11 -6
  10. package/build/lib/supabase.js +3 -0
  11. package/build/metadata/arxiv-source.js +229 -0
  12. package/build/metadata/circuit-breaker.js +62 -0
  13. package/build/metadata/github-source.js +203 -0
  14. package/build/metadata/hackernews-source.js +123 -0
  15. package/build/metadata/quality.js +27 -0
  16. package/build/metadata/scraper.js +85 -14
  17. package/build/metadata/semantic-scholar-source.js +138 -0
  18. package/build/python/asset_downloader_engine.py +2 -0
  19. package/build/python/convert_engine.py +92 -0
  20. package/build/python/export_engine.py +45 -0
  21. package/build/python/kaggle_engine.py +77 -5
  22. package/build/python/normalize_engine.py +83 -0
  23. package/build/python/vesper/core/asset_downloader.py +5 -1
  24. package/build/scripts/test-phase1-webcore-quality.js +104 -0
  25. package/build/search/engine.js +45 -6
  26. package/build/search/jit-orchestrator.js +18 -14
  27. package/build/search/query-intent.js +509 -0
  28. package/build/tools/formatter.js +6 -3
  29. package/build/utils/python-runtime.js +130 -0
  30. package/build/web/extract-web.js +297 -0
  31. package/build/web/fusion-engine.js +457 -0
  32. package/build/web/types.js +1 -0
  33. package/build/web/web-core.js +242 -0
  34. package/package.json +12 -5
  35. package/scripts/postinstall.cjs +87 -31
  36. package/scripts/wizard.cjs +652 -0
  37. package/scripts/wizard.js +338 -12
  38. package/src/python/__pycache__/config.cpython-312.pyc +0 -0
  39. package/src/python/__pycache__/kaggle_engine.cpython-312.pyc +0 -0
  40. package/src/python/asset_downloader_engine.py +2 -0
  41. package/src/python/convert_engine.py +92 -0
  42. package/src/python/export_engine.py +45 -0
  43. package/src/python/kaggle_engine.py +77 -5
  44. package/src/python/normalize_engine.py +83 -0
  45. package/src/python/requirements.txt +12 -0
  46. package/src/python/vesper/core/asset_downloader.py +5 -1
  47. package/wizard.cjs +3 -0
package/scripts/wizard.js CHANGED
@@ -10,11 +10,15 @@ const path = require('path');
10
10
  const os = require('os');
11
11
  const crypto = require('crypto');
12
12
  const { execSync, spawnSync } = require('child_process');
13
+ const http = require('http');
14
+ const https = require('https');
15
+ const readline = require('readline');
13
16
 
14
17
  // ── Paths ────────────────────────────────────────────────────
15
18
  const HOME = os.homedir();
16
19
  const VESPER_DIR = path.join(HOME, '.vesper');
17
20
  const CONFIG_TOML = path.join(VESPER_DIR, 'config.toml');
21
+ const CONFIG_JSON = path.join(VESPER_DIR, 'config.json');
18
22
  const DATA_DIR = path.join(VESPER_DIR, 'data');
19
23
  const IS_WIN = process.platform === 'win32';
20
24
  const APPDATA = process.env.APPDATA || path.join(HOME, 'AppData', 'Roaming');
@@ -46,6 +50,32 @@ function writeToml(filePath, data) {
46
50
  fs.writeFileSync(filePath, lines.join('\n') + '\n', 'utf8');
47
51
  }
48
52
 
53
+ function readWizardState() {
54
+ if (!fs.existsSync(CONFIG_JSON)) return {};
55
+ try {
56
+ const content = fs.readFileSync(CONFIG_JSON, 'utf8').trim();
57
+ return content ? JSON.parse(content) : {};
58
+ } catch {
59
+ return {};
60
+ }
61
+ }
62
+
63
+ function writeWizardState(state) {
64
+ ensureDir(path.dirname(CONFIG_JSON));
65
+ fs.writeFileSync(CONFIG_JSON, JSON.stringify(state, null, 2), 'utf8');
66
+ }
67
+
68
+ function hasCompletedOnboarding() {
69
+ const state = readWizardState();
70
+ return state.onboardingCompleted === true;
71
+ }
72
+
73
+ function markOnboardingCompleted() {
74
+ const state = readWizardState();
75
+ state.onboardingCompleted = true;
76
+ writeWizardState(state);
77
+ }
78
+
49
79
  function dim(text) { return `\x1b[2m${text}\x1b[0m`; }
50
80
  function bold(text) { return `\x1b[1m${text}\x1b[0m`; }
51
81
  function green(text) { return `\x1b[32m${text}\x1b[0m`; }
@@ -54,6 +84,276 @@ function yellow(text) { return `\x1b[33m${text}\x1b[0m`; }
54
84
  function red(text) { return `\x1b[31m${text}\x1b[0m`; }
55
85
  function magenta(text) { return `\x1b[35m${text}\x1b[0m`; }
56
86
 
87
+ // ── Vesper API URL resolution ────────────────────────────────
88
+ const VESPER_API_URL = process.env.VESPER_API_URL || '';
89
+ const DEFAULT_VESPER_API_CANDIDATES = [
90
+ 'https://getvesper.dev',
91
+ 'http://localhost:3000',
92
+ 'http://127.0.0.1:3000',
93
+ ];
94
+
95
+ // ── Device Auth Helpers ──────────────────────────────────────
96
+ function httpJson(method, url, body) {
97
+ return new Promise((resolve, reject) => {
98
+ const parsed = new URL(url);
99
+ const lib = parsed.protocol === 'https:' ? https : http;
100
+ const opts = {
101
+ method,
102
+ hostname: parsed.hostname,
103
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
104
+ path: parsed.pathname + parsed.search,
105
+ headers: { 'Content-Type': 'application/json' },
106
+ };
107
+ const req = lib.request(opts, (res) => {
108
+ let data = '';
109
+ res.on('data', (chunk) => (data += chunk));
110
+ res.on('end', () => {
111
+ try { resolve({ status: res.statusCode, body: JSON.parse(data) }); }
112
+ catch { resolve({ status: res.statusCode, body: data }); }
113
+ });
114
+ });
115
+ req.on('error', reject);
116
+ if (body) req.write(JSON.stringify(body));
117
+ req.end();
118
+ });
119
+ }
120
+
121
+ async function probeDeviceAuth(baseUrl) {
122
+ try {
123
+ const res = await httpJson('POST', `${baseUrl}/api/auth/device/start`);
124
+ if (res.status === 201 && !!res.body && !!res.body.code) {
125
+ return { baseUrl, status: 'ready', response: res.body };
126
+ }
127
+
128
+ if (res.status === 503 && res.body && res.body.requiresSetup) {
129
+ return {
130
+ baseUrl,
131
+ status: 'setup-required',
132
+ response: res.body,
133
+ message: res.body.error || 'Auth storage is not initialized.',
134
+ };
135
+ }
136
+
137
+ return {
138
+ baseUrl,
139
+ status: 'unreachable',
140
+ response: res.body,
141
+ message: typeof res.body === 'string' ? res.body : JSON.stringify(res.body),
142
+ };
143
+ } catch (error) {
144
+ return {
145
+ baseUrl,
146
+ status: 'unreachable',
147
+ message: error && error.message ? error.message : 'Request failed',
148
+ };
149
+ }
150
+ }
151
+
152
+ async function resolveVesperApiBaseUrl() {
153
+ const candidates = VESPER_API_URL
154
+ ? [VESPER_API_URL]
155
+ : DEFAULT_VESPER_API_CANDIDATES;
156
+
157
+ let setupRequiredProbe = null;
158
+
159
+ for (const candidate of candidates) {
160
+ const probe = await probeDeviceAuth(candidate);
161
+ if (probe.status === 'ready') {
162
+ return probe;
163
+ }
164
+
165
+ if (!setupRequiredProbe && probe.status === 'setup-required') {
166
+ setupRequiredProbe = probe;
167
+ }
168
+ }
169
+
170
+ return setupRequiredProbe;
171
+ }
172
+
173
+ function openBrowser(url) {
174
+ try {
175
+ if (process.platform === 'win32') {
176
+ spawnSync('cmd', ['/c', 'start', '', url], { stdio: 'ignore' });
177
+ } else if (process.platform === 'darwin') {
178
+ spawnSync('open', [url], { stdio: 'ignore' });
179
+ } else {
180
+ spawnSync('xdg-open', [url], { stdio: 'ignore' });
181
+ }
182
+ } catch { /* browser open is best-effort */ }
183
+ }
184
+
185
+ function askYesNo(question) {
186
+ return new Promise((resolve) => {
187
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
188
+ rl.question(` ${question} ${dim('[Y/n]')} `, (answer) => {
189
+ rl.close();
190
+ resolve(!answer || answer.toLowerCase().startsWith('y'));
191
+ });
192
+ });
193
+ }
194
+
195
+ function askInput(question) {
196
+ return new Promise((resolve) => {
197
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
198
+ rl.question(` ${question} `, (answer) => {
199
+ rl.close();
200
+ resolve(String(answer || '').trim());
201
+ });
202
+ });
203
+ }
204
+
205
+ async function askChoice(question, choices, defaultValue) {
206
+ console.log(` ${question}`);
207
+ choices.forEach((choice, index) => {
208
+ console.log(` ${dim(String(index + 1) + ')')} ${choice.label}`);
209
+ });
210
+
211
+ const prompt = defaultValue ? `${dim('[default: ' + defaultValue + ']')}` : '';
212
+ const answer = await askInput(`${prompt} ${cyan('→')} Choose an option:`);
213
+ if (!answer && defaultValue) {
214
+ return defaultValue;
215
+ }
216
+
217
+ const numeric = Number(answer);
218
+ if (Number.isFinite(numeric) && numeric >= 1 && numeric <= choices.length) {
219
+ return choices[numeric - 1].value;
220
+ }
221
+
222
+ const matched = choices.find((choice) => choice.value === answer);
223
+ return matched ? matched.value : defaultValue;
224
+ }
225
+
226
+ function isCloudApiKey(value) {
227
+ return !!value && value.startsWith('vesper_sk_') && !value.startsWith('vesper_sk_local_');
228
+ }
229
+
230
+ async function promptForManualApiKey() {
231
+ console.log(`\n ${cyan('■')} ${bold('Manual API Key')}`);
232
+ console.log(` ${dim('Paste a Vesper cloud API key. It will be stored locally in config.toml.\n')}`);
233
+
234
+ while (true) {
235
+ const value = await askInput(`${cyan('→')} Vesper API key:`);
236
+ if (isCloudApiKey(value)) {
237
+ return value;
238
+ }
239
+ console.log(` ${yellow('!')} ${yellow('Expected a Vesper key starting with vesper_sk_')}`);
240
+ }
241
+ }
242
+
243
+ async function chooseAuthMode(existingKey, existingAuthMode) {
244
+ const hasExistingKey = !!existingKey;
245
+ if (hasExistingKey) {
246
+ console.log(` ${dim('Current key:')} ${dim(existingKey.slice(0, 24) + '...')}`);
247
+ console.log(` ${dim('Current mode:')} ${dim(existingAuthMode || (isCloudApiKey(existingKey) ? 'cloud' : 'local_unified'))}`);
248
+ }
249
+
250
+ const choices = [];
251
+ choices.push({ value: 'browser', label: 'Sign in through the browser' });
252
+ choices.push({ value: 'manual', label: 'Provide Vesper API key manually' });
253
+
254
+ return await askChoice(`${cyan('→')} How do you want to authenticate Vesper?`, choices, 'browser');
255
+ }
256
+
257
+ async function deviceAuthFlow() {
258
+ console.log(`\n ${cyan('■')} ${bold('Device Authentication')}`);
259
+ console.log(` ${dim('Link your CLI to a Vesper account for cloud features\n')}`);
260
+
261
+ const resolvedApiBaseUrl = await resolveVesperApiBaseUrl();
262
+ if (!resolvedApiBaseUrl) {
263
+ console.log(` ${red('✗')} ${red('Could not reach any Vesper auth endpoint.')}`);
264
+ console.log(` ${dim('Tried:')} ${dim((VESPER_API_URL ? [VESPER_API_URL] : DEFAULT_VESPER_API_CANDIDATES).join(', '))}`);
265
+ console.log(` ${dim('If your landing app is running locally, start it on http://localhost:3000 or set VESPER_API_URL.')}`);
266
+ console.log(` ${dim('Falling back to manual key entry.\n')}`);
267
+ return null;
268
+ }
269
+
270
+ if (resolvedApiBaseUrl.status === 'setup-required') {
271
+ console.log(` ${yellow('!')} ${yellow('Reached Vesper auth endpoint, but local auth storage is not initialized.')}`);
272
+ console.log(` ${dim('Endpoint:')} ${dim(resolvedApiBaseUrl.baseUrl)}`);
273
+ console.log(` ${dim('Reason:')} ${dim(resolvedApiBaseUrl.message || 'Apply Supabase migrations first.')}`);
274
+ console.log(` ${dim('Run the SQL in supabase/migrations/001_device_auth.sql and 002_rate_limits.sql, then retry.')}`);
275
+ console.log(` ${dim('Falling back to manual key entry.\n')}`);
276
+ return null;
277
+ }
278
+
279
+ console.log(` ${dim('Auth endpoint:')} ${dim(resolvedApiBaseUrl.baseUrl)}\n`);
280
+
281
+ // Step 1: Call /api/auth/device/start
282
+ process.stdout.write(` ${dim('Requesting device code...')}`);
283
+ let startRes;
284
+ try {
285
+ startRes = await httpJson('POST', `${resolvedApiBaseUrl.baseUrl}/api/auth/device/start`);
286
+ } catch (err) {
287
+ console.log(` ${red('✗')}`);
288
+ console.log(` ${red('Could not reach Vesper API at')} ${dim(resolvedApiBaseUrl.baseUrl)}`);
289
+ console.log(` ${dim('Falling back to manual key entry.\n')}`);
290
+ return null;
291
+ }
292
+
293
+ if (startRes.status !== 201 || !startRes.body.code) {
294
+ console.log(` ${red('✗')}`);
295
+ console.log(` ${red('Unexpected response:')} ${dim(JSON.stringify(startRes.body))}`);
296
+ return null;
297
+ }
298
+
299
+ const { code, loginUrl } = startRes.body;
300
+ console.log(` ${green('✓')}\n`);
301
+
302
+ // Step 2: Display code and open browser
303
+ console.log(` ┌───────────────────────────────────────────────┐`);
304
+ console.log(` │ │`);
305
+ console.log(` │ ${bold('Your device code:')} ${cyan(bold(code))} │`);
306
+ console.log(` │ │`);
307
+ console.log(` │ ${dim('Open this URL to sign in:')} │`);
308
+ console.log(` │ ${cyan(loginUrl.padEnd(41))}│`);
309
+ console.log(` │ │`);
310
+ console.log(` └───────────────────────────────────────────────┘\n`);
311
+
312
+ if (!hasCompletedOnboarding()) {
313
+ openBrowser(loginUrl);
314
+ markOnboardingCompleted();
315
+ console.log(` ${dim('Browser opened automatically (first-time onboarding).')}`);
316
+ } else {
317
+ console.log(` ${dim('Browser auto-open skipped (onboarding already completed).')}`);
318
+ }
319
+ console.log(` ${dim('Waiting for you to sign in...')}\n`);
320
+
321
+ // Step 3: Poll until confirmed or expired
322
+ const POLL_INTERVAL = 3000; // 3 seconds
323
+ const MAX_POLLS = 200; // 10 min max (200 × 3s)
324
+ let polls = 0;
325
+ const spinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
326
+
327
+ while (polls < MAX_POLLS) {
328
+ polls++;
329
+ const frame = spinner[polls % spinner.length];
330
+ process.stdout.write(`\r ${cyan(frame)} Polling... (${polls})`);
331
+
332
+ try {
333
+ const pollRes = await httpJson('GET', `${resolvedApiBaseUrl.baseUrl}/api/auth/device/poll?code=${code}`);
334
+
335
+ if (pollRes.body.status === 'confirmed' && pollRes.body.apiKey) {
336
+ process.stdout.write(`\r ${green('✓')} Device authenticated! \n`);
337
+ console.log(` ${dim('Email:')} ${pollRes.body.email || 'linked'}`);
338
+ return pollRes.body.apiKey;
339
+ }
340
+
341
+ if (pollRes.body.status === 'expired') {
342
+ process.stdout.write(`\r ${red('✗')} Device code expired. \n`);
343
+ console.log(` ${dim('Run the wizard again to get a new code.')}`);
344
+ return null;
345
+ }
346
+ } catch {
347
+ // Network hiccup — keep polling
348
+ }
349
+
350
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL));
351
+ }
352
+
353
+ process.stdout.write(`\r ${red('✗')} Timed out waiting for authentication.\n`);
354
+ return null;
355
+ }
356
+
57
357
  function printBanner() {
58
358
  console.log(`
59
359
  ${dim('─────────────────────────────────────────────────')}
@@ -182,21 +482,42 @@ async function main() {
182
482
  ensureDir(path.join(VESPER_DIR, 'datasets'));
183
483
  console.log(` ${green('✓')}`);
184
484
 
185
- // ─── Step 2: Generate local API key ────────────────────────
186
- process.stdout.write(` ${dim('[')}${cyan('2/6')}${dim(']')} Generating local API key...`);
485
+ // ─── Step 2: Authenticate (device flow or local key) ──────
486
+ console.log(`\n ${dim('[')}${cyan('2/6')}${dim(']')} Authentication`);
487
+
187
488
  const existing = readToml(CONFIG_TOML);
188
- const localKey = existing.api_key || generateLocalKey();
189
- const configData = { ...existing, api_key: localKey };
489
+ let localKey = existing.api_key || '';
490
+ let authMode = existing.auth_mode || '';
491
+
492
+ const authChoice = await chooseAuthMode(localKey, authMode);
493
+
494
+ if (authChoice === 'manual') {
495
+ localKey = await promptForManualApiKey();
496
+ authMode = 'cloud';
497
+ console.log(` ${green('✓')} Cloud API key saved from manual input`);
498
+ } else if (authChoice === 'browser') {
499
+ const cloudKey = await deviceAuthFlow();
500
+ if (cloudKey) {
501
+ localKey = cloudKey;
502
+ authMode = 'cloud';
503
+ } else {
504
+ console.log(`\n ${yellow('!')} Browser sign-in did not complete. Falling back to manual key entry.`);
505
+ localKey = await promptForManualApiKey();
506
+ authMode = 'cloud';
507
+ }
508
+ }
509
+
510
+ const configData = { ...existing, api_key: localKey, auth_mode: authMode };
190
511
  writeToml(CONFIG_TOML, configData);
191
- console.log(` ${green('')}`);
192
- console.log(` ${dim('Key:')} ${dim(localKey.slice(0, 20) + '...')} ${dim('→')} ${dim(CONFIG_TOML)}`);
512
+ console.log(` ${dim('Key:')} ${dim(localKey.slice(0, 24) + '...')} ${dim('→')} ${dim(CONFIG_TOML)}`);
193
513
 
194
514
  // ─── Step 3: Local vault initialization ────────────────────
195
515
  process.stdout.write(`\n ${dim('[')}${cyan('3/6')}${dim(']')} Initializing local credentials vault...`);
196
- configData.auth_mode = configData.auth_mode || 'local_unified';
197
- writeToml(CONFIG_TOML, configData);
516
+ const vaultData = readToml(CONFIG_TOML);
517
+ if (!vaultData.auth_mode) vaultData.auth_mode = 'local_unified';
518
+ writeToml(CONFIG_TOML, vaultData);
198
519
  console.log(` ${green('✓')}`);
199
- console.log(` ${dim('Mode:')} ${dim('single local Vesper key (no external keys required)')}`);
520
+ console.log(` ${dim('Mode:')} ${dim(vaultData.auth_mode === 'cloud' ? 'cloud (linked to Vesper account)' : 'single local Vesper key (no external keys required)')}`);
200
521
 
201
522
  // ─── Step 4: Install @vespermcp/mcp-server ─────────────────
202
523
  console.log(`\n ${dim('[')}${cyan('4/6')}${dim(']')} Installing Vesper MCP server...`);
@@ -251,19 +572,24 @@ async function main() {
251
572
  console.log(` ${configuredAgents.length > 0 ? green('✓') : yellow('⚠')} MCP agents ${dim(configuredAgents.length + ' configured')}`);
252
573
 
253
574
  // ─── Final Summary ─────────────────────────────────────────
575
+ const finalConfig = readToml(CONFIG_TOML);
576
+ const isCloud = finalConfig.auth_mode === 'cloud';
254
577
  console.log(`
255
578
  ${dim('═════════════════════════════════════════════════')}
256
579
 
257
580
  ${green(bold('✓ Vesper is ready!'))}
258
581
 
259
- ${bold('Your local API key:')}
260
- ${cyan(localKey)}
582
+ ${bold(isCloud ? 'Your cloud API key:' : 'Your local API key:')}
583
+ ${cyan(finalConfig.api_key || localKey)}
584
+
585
+ ${bold('Auth mode:')}
586
+ ${dim(isCloud ? '☁ Cloud (linked to Vesper account)' : '🔑 Local-only (key never leaves your machine)')}
261
587
 
262
588
  ${bold('Config file:')}
263
589
  ${dim(CONFIG_TOML)}
264
590
 
265
591
  ${bold('What just happened:')}
266
- ${dim('1.')} Generated a local API key (never leaves your machine)
592
+ ${dim('1.')} ${isCloud ? 'Linked to your Vesper cloud account' : 'Generated a local API key (never leaves your machine)'}
267
593
  ${dim('2.')} Initialized local credentials vault
268
594
  ${dim('3.')} Auto-configured MCP for ${configuredAgents.length > 0 ? configuredAgents.join(', ') : 'detected agents'}
269
595
  ${dim('4.')} Vesper server ready on stdio transport
@@ -26,6 +26,7 @@ def _print(payload: Dict[str, Any]) -> None:
26
26
  async def _run_download(args: argparse.Namespace) -> Dict[str, Any]:
27
27
  payload = json.loads(args.payload)
28
28
  output_root = payload.get("output_root") or str(Path.home() / ".vesper" / "data" / "assets")
29
+ output_dir = payload.get("output_dir")
29
30
  workers = int(payload.get("workers") or 8)
30
31
  recipes_dir = payload.get("recipes_dir")
31
32
 
@@ -43,6 +44,7 @@ async def _run_download(args: argparse.Namespace) -> Dict[str, Any]:
43
44
  kaggle_ref=payload.get("kaggle_ref"),
44
45
  urls=payload.get("urls"),
45
46
  output_format=payload.get("output_format", "webdataset"),
47
+ output_dir=str(output_dir) if output_dir else None,
46
48
  max_items=payload.get("max_items"),
47
49
  image_column=payload.get("image_column"),
48
50
  )
@@ -0,0 +1,92 @@
1
+ """
2
+ Convert a dataset file between formats (CSV, Parquet, JSON, JSONL).
3
+ Usage: convert_engine.py <input_path> <output_path>
4
+ Outputs JSON: {"ok": true, "output_path": "...", "rows": N, "columns": N} or {"ok": false, "error": "..."}
5
+ """
6
+ import sys
7
+ import json
8
+ import os
9
+
10
+ try:
11
+ import polars as pl
12
+ except Exception:
13
+ print(json.dumps({"ok": False, "error": "polars is required. Install with: pip install polars"}))
14
+ sys.exit(1)
15
+
16
+
17
+ def _load(src: str) -> pl.DataFrame:
18
+ ext = os.path.splitext(src)[1].lower()
19
+ if ext == ".csv":
20
+ return pl.read_csv(src, ignore_errors=True, infer_schema_length=10000)
21
+ if ext in (".tsv", ".tab"):
22
+ return pl.read_csv(src, separator="\t", ignore_errors=True, infer_schema_length=10000)
23
+ if ext in (".parquet", ".pq"):
24
+ return pl.read_parquet(src)
25
+ if ext in (".feather", ".ftr", ".arrow", ".ipc"):
26
+ return pl.read_ipc(src)
27
+ if ext in (".jsonl", ".ndjson"):
28
+ return pl.read_ndjson(src)
29
+ if ext == ".json":
30
+ raw = open(src, "r", encoding="utf-8").read().strip()
31
+ if raw.startswith("["):
32
+ return pl.read_json(src)
33
+ if "\n" in raw and raw.split("\n")[0].strip().startswith("{"):
34
+ return pl.read_ndjson(src)
35
+ obj = json.loads(raw)
36
+ if isinstance(obj, dict):
37
+ for key in ("data", "rows", "items", "records", "results", "entries", "samples"):
38
+ if key in obj and isinstance(obj[key], list):
39
+ return pl.DataFrame(obj[key])
40
+ for v in obj.values():
41
+ if isinstance(v, list) and len(v) > 0 and isinstance(v[0], dict):
42
+ return pl.DataFrame(v)
43
+ return pl.read_json(src)
44
+ # Fallback: try csv
45
+ return pl.read_csv(src, ignore_errors=True, infer_schema_length=10000)
46
+
47
+
48
+ def _write(df: pl.DataFrame, dst: str) -> None:
49
+ ext = os.path.splitext(dst)[1].lower()
50
+ os.makedirs(os.path.dirname(dst) or ".", exist_ok=True)
51
+ if ext in (".parquet", ".pq"):
52
+ df.write_parquet(dst)
53
+ elif ext == ".csv":
54
+ df.write_csv(dst)
55
+ elif ext == ".json":
56
+ df.write_json(dst, row_oriented=True)
57
+ elif ext in (".jsonl", ".ndjson"):
58
+ df.write_ndjson(dst)
59
+ else:
60
+ raise ValueError(f"Unsupported output format: {ext}")
61
+
62
+
63
+ def main():
64
+ if len(sys.argv) < 3:
65
+ print(json.dumps({"ok": False, "error": "Usage: convert_engine.py <input> <output>"}))
66
+ sys.exit(1)
67
+
68
+ input_path = sys.argv[1]
69
+ output_path = sys.argv[2]
70
+
71
+ if not os.path.exists(input_path):
72
+ print(json.dumps({"ok": False, "error": f"File not found: {input_path}"}))
73
+ sys.exit(1)
74
+
75
+ try:
76
+ df = _load(input_path)
77
+ _write(df, output_path)
78
+ size_mb = round(os.path.getsize(output_path) / (1024 * 1024), 2)
79
+ print(json.dumps({
80
+ "ok": True,
81
+ "output_path": output_path,
82
+ "rows": df.height,
83
+ "columns": df.width,
84
+ "size_mb": size_mb,
85
+ }))
86
+ except Exception as e:
87
+ print(json.dumps({"ok": False, "error": str(e)}))
88
+ sys.exit(1)
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
@@ -50,6 +50,51 @@ def _load(file_path: str, options: dict) -> pl.DataFrame:
50
50
  df = pl.read_ipc(file_path)
51
51
  elif ext == ".jsonl":
52
52
  df = pl.read_ndjson(file_path)
53
+ elif ext == ".json":
54
+ # Auto-detect: array-of-objects vs NDJSON vs nested structures
55
+ try:
56
+ import json as _json
57
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as fh:
58
+ raw_text = fh.read(512) # peek
59
+ stripped = raw_text.lstrip()
60
+ if stripped.startswith("["):
61
+ # Array of objects — standard JSON
62
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as fh:
63
+ data = _json.load(fh)
64
+ if isinstance(data, list) and len(data) > 0:
65
+ df = pl.DataFrame(data)
66
+ else:
67
+ raise ValueError("JSON file is empty or not an array of objects")
68
+ elif stripped.startswith("{"):
69
+ # Could be NDJSON or a single object wrapping rows
70
+ try:
71
+ df = pl.read_ndjson(file_path)
72
+ except Exception:
73
+ with open(file_path, "r", encoding="utf-8", errors="ignore") as fh:
74
+ data = _json.load(fh)
75
+ # Try common wrapper patterns: {"data": [...]}, {"rows": [...]}, etc.
76
+ rows = None
77
+ if isinstance(data, dict):
78
+ for key in ("data", "rows", "records", "items", "results", "entries"):
79
+ if key in data and isinstance(data[key], list):
80
+ rows = data[key]
81
+ break
82
+ if rows is None:
83
+ # Last resort: try to use the dict values
84
+ rows = [data]
85
+ if rows and len(rows) > 0:
86
+ df = pl.DataFrame(rows)
87
+ else:
88
+ raise ValueError("Could not parse JSON structure into tabular data")
89
+ else:
90
+ raise ValueError("JSON file does not start with [ or {")
91
+ except pl.exceptions.ComputeError as ce:
92
+ raise ValueError(f"Failed to parse JSON: {ce}")
93
+ elif ext == ".xlsx":
94
+ try:
95
+ df = pl.read_excel(file_path)
96
+ except Exception as e:
97
+ raise ValueError(f"Failed to read Excel file: {e}")
53
98
  else:
54
99
  raise ValueError(f"Unsupported input format: {ext}")
55
100