@massa-ai/tools-api 1.46.0 → 1.48.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.
Files changed (2) hide show
  1. package/dist/index.js +1501 -578
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -401,9 +401,64 @@ var init_xdg = () => {};
401
401
 
402
402
  // ../../packages/shared/dist/config/massa-ai-config.js
403
403
  import path2 from "path";
404
- var defaultMassaAiConfig;
404
+ var SCHEDULER_JOB_KINDS, MAX_MATCH_WORK = 1e5, MAX_IGNORE_PATTERNS = 1024, DEFAULT_CAPTURE_POLICY, DEFAULT_SCHEDULER_CONFIG, defaultMassaAiConfig;
405
405
  var init_massa_ai_config = __esm(() => {
406
406
  init_xdg();
407
+ SCHEDULER_JOB_KINDS = [
408
+ "memory-consolidation",
409
+ "decay-sweep",
410
+ "auto-improve",
411
+ "observation-bridge",
412
+ "checkpoint-purge"
413
+ ];
414
+ DEFAULT_CAPTURE_POLICY = {
415
+ rules: [
416
+ { pattern: "**/node_modules/**", disposition: "Drop" },
417
+ { pattern: "**/.git/**", disposition: "Drop" },
418
+ { pattern: "**/dist/**", disposition: "Drop" },
419
+ { pattern: "**/build/**", disposition: "Drop" },
420
+ { pattern: "**/coverage/**", disposition: "Drop" },
421
+ { pattern: ".env", disposition: "Drop" },
422
+ { pattern: ".env.*", disposition: "Drop" },
423
+ { pattern: "**/generated/**", disposition: "Drop" },
424
+ { pattern: "**/*.generated.*", disposition: "Drop" },
425
+ { pattern: "**/*.d.ts", disposition: "Drop" },
426
+ { pattern: "**/__tests__/**", disposition: "Drop" },
427
+ { pattern: "**/tests/**", disposition: "Drop" },
428
+ { pattern: "**/*.test.ts", disposition: "Drop" },
429
+ { pattern: "**/*.test.tsx", disposition: "Drop" },
430
+ { pattern: "**/*.test.js", disposition: "Drop" },
431
+ { pattern: "**/*.test.jsx", disposition: "Drop" },
432
+ { pattern: "**/*.spec.ts", disposition: "Drop" },
433
+ { pattern: "**/*.spec.tsx", disposition: "Drop" },
434
+ { pattern: "**/*.spec.js", disposition: "Drop" },
435
+ { pattern: "**/*.spec.jsx", disposition: "Drop" },
436
+ { pattern: "**/benchmarks/**", disposition: "Drop" },
437
+ { pattern: "**/fixtures/**", disposition: "Drop" },
438
+ { pattern: "**/*.wasm*", disposition: "Drop" },
439
+ { pattern: "**/*.min.*", disposition: "Drop" },
440
+ { pattern: "**/*.map", disposition: "Drop" },
441
+ { pattern: "**/lock.yaml", disposition: "Drop" },
442
+ { pattern: "**/pnpm-lock.yaml", disposition: "Drop" },
443
+ { pattern: "**/package-lock.json", disposition: "Drop" },
444
+ { pattern: "**/bun.lockb", disposition: "Drop" },
445
+ { pattern: "**/yarn.lock", disposition: "Drop" }
446
+ ],
447
+ maxMatchWork: MAX_MATCH_WORK,
448
+ maxIgnorePatterns: MAX_IGNORE_PATTERNS
449
+ };
450
+ DEFAULT_SCHEDULER_CONFIG = {
451
+ enabled: false,
452
+ tickMs: 60000,
453
+ maxConcurrent: 2,
454
+ jobs: {
455
+ "memory-consolidation": { enabled: false, intervalMs: 30 * 60 * 1000 },
456
+ "decay-sweep": { enabled: false, intervalMs: 60 * 60 * 1000 },
457
+ "auto-improve": { enabled: false, intervalMs: 30 * 60 * 1000 },
458
+ "observation-bridge": { enabled: false, intervalMs: 30 * 60 * 1000 },
459
+ "checkpoint-purge": { enabled: false, intervalMs: 60 * 60 * 1000 }
460
+ }
461
+ };
407
462
  defaultMassaAiConfig = {
408
463
  database: {
409
464
  url: ""
@@ -422,7 +477,7 @@ var init_massa_ai_config = __esm(() => {
422
477
  impact: {
423
478
  bfsCteEnabled: false
424
479
  },
425
- capturePolicy: undefined,
480
+ capturePolicy: DEFAULT_CAPTURE_POLICY,
426
481
  cache: {
427
482
  enabled: true,
428
483
  l1MaxSizeMB: 100,
@@ -545,7 +600,8 @@ var init_massa_ai_config = __esm(() => {
545
600
  },
546
601
  security: {
547
602
  corsOrigins: []
548
- }
603
+ },
604
+ scheduler: DEFAULT_SCHEDULER_CONFIG
549
605
  };
550
606
  });
551
607
 
@@ -555,6 +611,8 @@ __export(exports_config_loader, {
555
611
  writeFileAtomically: () => writeFileAtomically,
556
612
  saveConfig: () => saveConfig,
557
613
  migrateDataDirOnce: () => migrateDataDirOnce,
614
+ mergeSchedulerSection: () => mergeSchedulerSection,
615
+ loadRawUserConfig: () => loadRawUserConfig,
558
616
  loadConfigSafe: () => loadConfigSafe,
559
617
  loadConfig: () => loadConfig,
560
618
  initConfig: () => initConfig,
@@ -577,6 +635,22 @@ function getConfigPath() {
577
635
  function configExists() {
578
636
  return fs.existsSync(CONFIG_FILE);
579
637
  }
638
+ function mergeSchedulerJobs(base, incoming) {
639
+ const defaults = defaultMassaAiConfig.scheduler?.jobs ?? {};
640
+ const merged = {};
641
+ for (const kind of Object.keys(defaults)) {
642
+ merged[kind] = { ...defaults[kind], ...base?.[kind], ...incoming?.[kind] };
643
+ }
644
+ return merged;
645
+ }
646
+ function mergeSchedulerSection(base, incoming) {
647
+ return {
648
+ ...defaultMassaAiConfig.scheduler,
649
+ ...base,
650
+ ...incoming,
651
+ jobs: mergeSchedulerJobs(base?.jobs, incoming?.jobs)
652
+ };
653
+ }
580
654
  function loadConfig() {
581
655
  if (!fs.existsSync(CONFIG_FILE)) {
582
656
  return defaultMassaAiConfig;
@@ -597,13 +671,27 @@ function loadConfig() {
597
671
  memory: { ...defaultMassaAiConfig.memory, ...userConfig.memory },
598
672
  hooks: { ...defaultMassaAiConfig.hooks, ...userConfig.hooks },
599
673
  handoffs: { ...defaultMassaAiConfig.handoffs, ...userConfig.handoffs },
600
- security: { ...defaultMassaAiConfig.security, ...userConfig.security }
674
+ security: { ...defaultMassaAiConfig.security, ...userConfig.security },
675
+ scheduler: mergeSchedulerSection(undefined, userConfig.scheduler),
676
+ capturePolicy: userConfig.capturePolicy ?? defaultMassaAiConfig.capturePolicy
601
677
  };
602
678
  } catch (error) {
603
679
  console.error(`Error loading config from ${CONFIG_FILE}:`, error);
604
680
  return defaultMassaAiConfig;
605
681
  }
606
682
  }
683
+ function loadRawUserConfig() {
684
+ try {
685
+ if (!fs.existsSync(CONFIG_FILE))
686
+ return {};
687
+ const parsed = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
688
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
689
+ return {};
690
+ return parsed;
691
+ } catch {
692
+ return {};
693
+ }
694
+ }
607
695
  function loadConfigSafe() {
608
696
  try {
609
697
  return loadConfig();
@@ -759,6 +847,8 @@ function restartNeededSections(config) {
759
847
  return config.llm !== undefined;
760
848
  if (s === "security")
761
849
  return config.security !== undefined;
850
+ if (s === "scheduler")
851
+ return config.scheduler !== undefined;
762
852
  return false;
763
853
  });
764
854
  }
@@ -1007,6 +1097,29 @@ function validatePartial(partial) {
1007
1097
  details.push("security.allowedExtensions[] must be dot-prefixed extensions");
1008
1098
  }
1009
1099
  }
1100
+ if (partial.scheduler !== undefined) {
1101
+ const sch = partial.scheduler;
1102
+ if (sch.enabled !== undefined && !checkBoolean(sch.enabled))
1103
+ details.push("scheduler.enabled must be a boolean");
1104
+ if (sch.tickMs !== undefined && !checkNumber(sch.tickMs, 1000))
1105
+ details.push("scheduler.tickMs must be a number >= 1000");
1106
+ if (sch.maxConcurrent !== undefined && !checkNumber(sch.maxConcurrent, 1))
1107
+ details.push("scheduler.maxConcurrent must be a number >= 1");
1108
+ if (sch.jobs !== undefined) {
1109
+ for (const [kind, job] of Object.entries(sch.jobs)) {
1110
+ if (!SCHEDULER_JOB_KINDS.includes(kind)) {
1111
+ details.push(`scheduler.jobs.${kind} is not a registered job kind (expected one of: ${SCHEDULER_JOB_KINDS.join(", ")})`);
1112
+ continue;
1113
+ }
1114
+ if (job === undefined || job === null)
1115
+ continue;
1116
+ if (job.enabled !== undefined && !checkBoolean(job.enabled))
1117
+ details.push(`scheduler.jobs.${kind}.enabled must be a boolean`);
1118
+ if (job.intervalMs !== undefined && !checkNumber(job.intervalMs, 60000))
1119
+ details.push(`scheduler.jobs.${kind}.intervalMs must be a number >= 60000`);
1120
+ }
1121
+ }
1122
+ }
1010
1123
  return details;
1011
1124
  }
1012
1125
  function repairAndPruneBackups(configPath) {
@@ -1048,6 +1161,9 @@ function savePartialConfig(partial) {
1048
1161
  return { success: false, details };
1049
1162
  }
1050
1163
  const merged = { ...current, ...mergedPartial };
1164
+ if (mergedPartial.scheduler !== undefined) {
1165
+ merged.scheduler = mergeSchedulerSection(current.scheduler, mergedPartial.scheduler);
1166
+ }
1051
1167
  const configPath = getConfigPath();
1052
1168
  if (fs2.existsSync(configPath)) {
1053
1169
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
@@ -1067,7 +1183,8 @@ function savePartialConfig(partial) {
1067
1183
  var MASK_SENTINEL = "***", RESTART_SECTIONS, VALID_EMBEDDING_PROVIDERS, VALID_LOG_LEVELS, BACKUP_RETENTION_LIMIT = 10;
1068
1184
  var init_config_writer = __esm(() => {
1069
1185
  init_config_loader();
1070
- RESTART_SECTIONS = ["database", "embedding", "llm", "security"];
1186
+ init_massa_ai_config();
1187
+ RESTART_SECTIONS = ["database", "embedding", "llm", "security", "scheduler"];
1071
1188
  VALID_EMBEDDING_PROVIDERS = ["ollama", "mistral", "openai", "google", "cohere"];
1072
1189
  VALID_LOG_LEVELS = ["debug", "info", "warn", "error"];
1073
1190
  });
@@ -1210,6 +1327,31 @@ function parsePositiveIntEnv(raw2, defaultValue, opts) {
1210
1327
  return Number.isInteger(n) && n >= floor ? n : defaultValue;
1211
1328
  }
1212
1329
 
1330
+ // ../../packages/shared/dist/config/embedding-dimensions.js
1331
+ function knownEmbeddingDimensions(model) {
1332
+ if (!model)
1333
+ return;
1334
+ return KNOWN_EMBEDDING_DIMENSIONS[model.trim()];
1335
+ }
1336
+ function resolveEmbeddingDimensions(model, configured, envValue) {
1337
+ if (envValue !== undefined)
1338
+ return { dimensions: envValue };
1339
+ const known = knownEmbeddingDimensions(model);
1340
+ if (known !== undefined) {
1341
+ return configured !== undefined && configured !== known ? { dimensions: known, correctedFrom: configured } : { dimensions: known };
1342
+ }
1343
+ return { dimensions: configured ?? DEFAULT_EMBEDDING_DIMENSIONS };
1344
+ }
1345
+ var KNOWN_EMBEDDING_DIMENSIONS, DEFAULT_EMBEDDING_DIMENSIONS = 2560;
1346
+ var init_embedding_dimensions = __esm(() => {
1347
+ KNOWN_EMBEDDING_DIMENSIONS = {
1348
+ "qwen3-embedding:8b": 4096,
1349
+ "qwen3-embedding:4b": 2560,
1350
+ "qwen3-embedding:0.6b": 1024,
1351
+ "bge-m3": 1024
1352
+ };
1353
+ });
1354
+
1213
1355
  // ../../packages/shared/dist/config/index.js
1214
1356
  import path6 from "path";
1215
1357
  function envNum(key, fallback) {
@@ -1241,6 +1383,22 @@ function envList(key, fallback) {
1241
1383
  const parsed = s.split(",").map((v) => v.trim()).filter((v) => v.length > 0);
1242
1384
  return parsed.length > 0 ? parsed : fallback;
1243
1385
  }
1386
+ function readSchedulerConfig(rawFileConfig) {
1387
+ try {
1388
+ const cfg = rawFileConfig;
1389
+ return cfg?.scheduler ?? {};
1390
+ } catch {
1391
+ return {};
1392
+ }
1393
+ }
1394
+ function resolveSchedulerJob(kind, fileJobs) {
1395
+ const meta = SCHEDULER_JOB_ENV[kind];
1396
+ const fileJob = fileJobs?.[kind];
1397
+ return {
1398
+ enabled: envBool(meta.enabledVar, fileJob?.enabled ?? false),
1399
+ intervalMs: envNum(meta.intervalVar, fileJob?.intervalMs ?? meta.defaultIntervalMs)
1400
+ };
1401
+ }
1244
1402
  function validateCapturePolicyConfig(raw2) {
1245
1403
  if (!raw2 || typeof raw2 !== "object")
1246
1404
  throw new TypeError("capturePolicy must be an object");
@@ -1368,6 +1526,11 @@ class Config {
1368
1526
  rateLimit: { ...defaults.rateLimit, ...overrides.rateLimit },
1369
1527
  security: { ...defaults.security, ...overrides.security },
1370
1528
  logging: { ...defaults.logging, ...overrides.logging },
1529
+ scheduler: {
1530
+ ...defaults.scheduler,
1531
+ ...overrides.scheduler,
1532
+ jobs: { ...defaults.scheduler.jobs, ...overrides.scheduler?.jobs }
1533
+ },
1371
1534
  synapse: {
1372
1535
  ...defaults.synapse,
1373
1536
  ...overrides.synapse,
@@ -1436,15 +1599,45 @@ class Config {
1436
1599
  this.config[key] = value;
1437
1600
  }
1438
1601
  }
1439
- var DEFAULT_LLM_MODEL = "qwen2.5:7b-instruct", DEFAULT_LLM_CODE_MODEL = "qwen2.5-coder:7b", MAX_IGNORE_PATTERNS = 1024, DEFAULT_ALLOWED_EXTENSIONS, fileConfig, fileCacheL1Bytes, fileCacheL2Bytes, defaultConfig, config;
1602
+ var DEFAULT_LLM_MODEL = "qwen2.5:7b-instruct", DEFAULT_LLM_CODE_MODEL = "qwen2.5-coder:7b", SCHEDULER_JOB_ENV, DEFAULT_ALLOWED_EXTENSIONS, fileConfig, fileCacheL1Bytes, fileCacheL2Bytes, resolvedDataDir, defaultConfig, config;
1440
1603
  var init_config = __esm(() => {
1441
1604
  init_env();
1442
1605
  init_config_loader();
1443
1606
  init_massa_ai_config();
1607
+ init_massa_ai_config();
1608
+ init_massa_ai_config();
1444
1609
  init_config_loader();
1445
1610
  init_config_writer();
1446
1611
  init_xdg();
1447
1612
  init_api_key();
1613
+ init_embedding_dimensions();
1614
+ SCHEDULER_JOB_ENV = {
1615
+ "memory-consolidation": {
1616
+ enabledVar: "MASSA_AI_SCHEDULER_CONSOLIDATION_ENABLED",
1617
+ intervalVar: "MASSA_AI_SCHEDULER_CONSOLIDATION_INTERVAL_MS",
1618
+ defaultIntervalMs: 30 * 60 * 1000
1619
+ },
1620
+ "decay-sweep": {
1621
+ enabledVar: "MASSA_AI_SCHEDULER_DECAY_ENABLED",
1622
+ intervalVar: "MASSA_AI_SCHEDULER_DECAY_INTERVAL_MS",
1623
+ defaultIntervalMs: 60 * 60 * 1000
1624
+ },
1625
+ "auto-improve": {
1626
+ enabledVar: "MASSA_AI_SCHEDULER_AUTO_IMPROVE_ENABLED",
1627
+ intervalVar: "MASSA_AI_SCHEDULER_AUTO_IMPROVE_INTERVAL_MS",
1628
+ defaultIntervalMs: 30 * 60 * 1000
1629
+ },
1630
+ "observation-bridge": {
1631
+ enabledVar: "MASSA_AI_SCHEDULER_OBSERVATION_BRIDGE_ENABLED",
1632
+ intervalVar: "MASSA_AI_SCHEDULER_OBSERVATION_BRIDGE_INTERVAL_MS",
1633
+ defaultIntervalMs: 30 * 60 * 1000
1634
+ },
1635
+ "checkpoint-purge": {
1636
+ enabledVar: "MASSA_AI_SCHEDULER_CHECKPOINT_PURGE_ENABLED",
1637
+ intervalVar: "MASSA_AI_SCHEDULER_CHECKPOINT_PURGE_INTERVAL_MS",
1638
+ defaultIntervalMs: 60 * 60 * 1000
1639
+ }
1640
+ };
1448
1641
  DEFAULT_ALLOWED_EXTENSIONS = [
1449
1642
  ".ts",
1450
1643
  ".js",
@@ -1483,10 +1676,11 @@ var init_config = __esm(() => {
1483
1676
  fileConfig = loadConfigSafe();
1484
1677
  fileCacheL1Bytes = fileConfig.cache?.l1MaxSizeMB ? fileConfig.cache.l1MaxSizeMB * 1024 * 1024 : undefined;
1485
1678
  fileCacheL2Bytes = fileConfig.cache?.l2MaxSizeMB ? fileConfig.cache.l2MaxSizeMB * 1024 * 1024 : undefined;
1679
+ resolvedDataDir = getGlobalDataDir();
1486
1680
  defaultConfig = {
1487
1681
  name: "massa-ai-server",
1488
1682
  version: "1.0.0",
1489
- dataDir: getGlobalDataDir(),
1683
+ dataDir: resolvedDataDir,
1490
1684
  cache: {
1491
1685
  l1: {
1492
1686
  maxSize: envNum("L1_CACHE_MAX_SIZE", fileCacheL1Bytes ?? 100 * 1024 * 1024),
@@ -1610,8 +1804,24 @@ var init_config = __esm(() => {
1610
1804
  logging: {
1611
1805
  level: process.env.LOG_LEVEL || fileConfig.logging?.level || "info",
1612
1806
  enableMetrics: process.env.ENABLE_METRICS === "true" || process.env.ENABLE_METRICS === undefined && !!fileConfig.logging?.enableMetrics,
1613
- file: process.env.MASSA_AI_LOG_FILE || fileConfig.logging?.file || undefined
1614
- },
1807
+ file: process.env.MASSA_AI_LOG_FILE || fileConfig.logging?.file || path6.join(resolvedDataDir, "logs", "massa-ai.log"),
1808
+ enableFileSink: envBool("MASSA_AI_LOG_ENABLE_FILE_SINK", fileConfig.logging?.enableFileSink ?? true),
1809
+ bufferSize: envNum("MASSA_AI_LOG_BUFFER_SIZE", fileConfig.logging?.bufferSize ?? 2000),
1810
+ maxFileSizeMb: envNum("MASSA_AI_LOG_MAX_FILE_SIZE_MB", fileConfig.logging?.maxFileSizeMb ?? 32),
1811
+ maxFiles: envNum("MASSA_AI_LOG_MAX_FILES", fileConfig.logging?.maxFiles ?? 5)
1812
+ },
1813
+ scheduler: (() => {
1814
+ const fileScheduler = readSchedulerConfig(fileConfig);
1815
+ return {
1816
+ enabled: envBool("MASSA_AI_SCHEDULER_ENABLED", fileScheduler.enabled ?? false),
1817
+ tickMs: envNum("MASSA_AI_SCHEDULER_TICK_MS", fileScheduler.tickMs ?? 60000),
1818
+ maxConcurrent: envNum("MASSA_AI_SCHEDULER_MAX_CONCURRENT", fileScheduler.maxConcurrent ?? 2),
1819
+ jobs: Object.fromEntries(SCHEDULER_JOB_KINDS.map((kind) => [
1820
+ kind,
1821
+ resolveSchedulerJob(kind, fileScheduler.jobs)
1822
+ ]))
1823
+ };
1824
+ })(),
1615
1825
  synapse: {
1616
1826
  enabled: process.env.SYNAPSE_ENABLED !== "false",
1617
1827
  inhibition: {
@@ -6948,13 +7158,190 @@ var init_types = __esm(() => {
6948
7158
  // ../../packages/shared/dist/types/interfaces.js
6949
7159
  var init_interfaces = () => {};
6950
7160
 
6951
- // ../../packages/shared/dist/utils/logger.js
7161
+ // ../../packages/shared/dist/utils/log-sink.js
6952
7162
  import fs4 from "fs";
7163
+ import path7 from "path";
7164
+ function getState(filePath) {
7165
+ let state = pathState.get(filePath);
7166
+ if (!state) {
7167
+ state = { trackedSize: 0, deltaSinceStat: 0, primed: false };
7168
+ pathState.set(filePath, state);
7169
+ }
7170
+ return state;
7171
+ }
7172
+ function ensureDir(filePath) {
7173
+ const dir = path7.dirname(filePath);
7174
+ if (ensuredDirs.has(dir))
7175
+ return;
7176
+ fs4.mkdirSync(dir, { recursive: true });
7177
+ ensuredDirs.add(dir);
7178
+ }
7179
+ function restat(filePath, state) {
7180
+ try {
7181
+ state.trackedSize = fs4.statSync(filePath).size;
7182
+ } catch {
7183
+ state.trackedSize = 0;
7184
+ }
7185
+ state.deltaSinceStat = 0;
7186
+ state.primed = true;
7187
+ }
7188
+ function rotate(filePath, maxFiles) {
7189
+ if (maxFiles <= 0) {
7190
+ if (fs4.existsSync(filePath))
7191
+ fs4.unlinkSync(filePath);
7192
+ return;
7193
+ }
7194
+ const oldest = `${filePath}.${maxFiles}`;
7195
+ if (fs4.existsSync(oldest))
7196
+ fs4.unlinkSync(oldest);
7197
+ for (let n2 = maxFiles - 1;n2 >= 1; n2--) {
7198
+ const src = `${filePath}.${n2}`;
7199
+ const dest = `${filePath}.${n2 + 1}`;
7200
+ if (fs4.existsSync(src))
7201
+ fs4.renameSync(src, dest);
7202
+ }
7203
+ if (fs4.existsSync(filePath))
7204
+ fs4.renameSync(filePath, `${filePath}.1`);
7205
+ }
7206
+ function appendLine(opts, line) {
7207
+ const { filePath, maxFileSizeBytes, maxFiles } = opts;
7208
+ try {
7209
+ ensureDir(filePath);
7210
+ const state = getState(filePath);
7211
+ const lineBytes = Buffer.byteLength(line + `
7212
+ `, "utf8");
7213
+ if (!state.primed || state.deltaSinceStat >= STAT_DELTA_THRESHOLD_BYTES || state.trackedSize + state.deltaSinceStat >= maxFileSizeBytes) {
7214
+ restat(filePath, state);
7215
+ }
7216
+ if (maxFileSizeBytes > 0 && state.trackedSize >= maxFileSizeBytes) {
7217
+ rotate(filePath, maxFiles);
7218
+ state.trackedSize = 0;
7219
+ state.deltaSinceStat = 0;
7220
+ state.primed = true;
7221
+ }
7222
+ fs4.appendFileSync(filePath, line + `
7223
+ `);
7224
+ state.trackedSize += lineBytes;
7225
+ state.deltaSinceStat += lineBytes;
7226
+ } catch (err) {
7227
+ lastError = err;
7228
+ }
7229
+ }
7230
+ function sinkFiles(filePath, maxFiles) {
7231
+ const files = [];
7232
+ try {
7233
+ if (fs4.existsSync(filePath))
7234
+ files.push(filePath);
7235
+ for (let n2 = 1;n2 <= maxFiles; n2++) {
7236
+ const rotated = `${filePath}.${n2}`;
7237
+ if (fs4.existsSync(rotated))
7238
+ files.push(rotated);
7239
+ }
7240
+ } catch (err) {
7241
+ lastError = err;
7242
+ }
7243
+ return files;
7244
+ }
7245
+ var STAT_DELTA_THRESHOLD_BYTES, ensuredDirs, pathState, lastError;
7246
+ var init_log_sink = __esm(() => {
7247
+ STAT_DELTA_THRESHOLD_BYTES = 1024 * 1024;
7248
+ ensuredDirs = new Set;
7249
+ pathState = new Map;
7250
+ });
7251
+
7252
+ // ../../packages/shared/dist/utils/log-buffer.js
7253
+ class LogBufferImpl {
7254
+ capacity = DEFAULT_CAPACITY;
7255
+ entries = [];
7256
+ subscribers = new Set;
7257
+ nextSeq = 0;
7258
+ dispatching = false;
7259
+ pending = [];
7260
+ push(entry) {
7261
+ if (this.dispatching) {
7262
+ this.pending.push(entry);
7263
+ return;
7264
+ }
7265
+ this.dispatching = true;
7266
+ try {
7267
+ this.pushOne(entry);
7268
+ while (this.pending.length > 0) {
7269
+ const next = this.pending.shift();
7270
+ this.pushOne(next);
7271
+ }
7272
+ } finally {
7273
+ this.dispatching = false;
7274
+ }
7275
+ }
7276
+ pushOne(entry) {
7277
+ const full = { ...entry, seq: this.nextSeq++ };
7278
+ this.entries.push(full);
7279
+ while (this.entries.length > this.capacity) {
7280
+ this.entries.shift();
7281
+ }
7282
+ for (const fn of this.subscribers) {
7283
+ try {
7284
+ fn(full);
7285
+ } catch {}
7286
+ }
7287
+ }
7288
+ snapshot(opts) {
7289
+ const from = opts?.from;
7290
+ const to = opts?.to;
7291
+ const level = opts?.level;
7292
+ const q = opts?.q?.toLowerCase();
7293
+ const result = [];
7294
+ for (let i = this.entries.length - 1;i >= 0; i--) {
7295
+ const e = this.entries[i];
7296
+ if (from !== undefined && e.seq < from)
7297
+ continue;
7298
+ if (to !== undefined && e.seq > to)
7299
+ continue;
7300
+ if (level !== undefined && e.level !== level)
7301
+ continue;
7302
+ if (q !== undefined && !e.message.toLowerCase().includes(q))
7303
+ continue;
7304
+ result.push(e);
7305
+ }
7306
+ return result;
7307
+ }
7308
+ subscribe(fn) {
7309
+ this.subscribers.add(fn);
7310
+ return () => {
7311
+ this.subscribers.delete(fn);
7312
+ };
7313
+ }
7314
+ setCapacity(n2) {
7315
+ this.capacity = n2 > 0 ? n2 : 0;
7316
+ while (this.entries.length > this.capacity) {
7317
+ this.entries.shift();
7318
+ }
7319
+ }
7320
+ size() {
7321
+ return this.entries.length;
7322
+ }
7323
+ _resetForTesting() {
7324
+ this.entries = [];
7325
+ this.subscribers.clear();
7326
+ this.nextSeq = 0;
7327
+ this.dispatching = false;
7328
+ this.pending = [];
7329
+ this.capacity = DEFAULT_CAPACITY;
7330
+ }
7331
+ }
7332
+ var DEFAULT_CAPACITY = 2000, logBuffer;
7333
+ var init_log_buffer = __esm(() => {
7334
+ logBuffer = new LogBufferImpl;
7335
+ });
6953
7336
 
7337
+ // ../../packages/shared/dist/utils/logger.js
6954
7338
  class Logger {
6955
7339
  _level;
6956
7340
  _enableMetrics;
6957
7341
  _logFilePath;
7342
+ _enableFileSink;
7343
+ _maxFileSizeBytes;
7344
+ _maxFiles;
6958
7345
  _initialized = false;
6959
7346
  constructor() {}
6960
7347
  ensureInitialized() {
@@ -6964,10 +7351,18 @@ class Logger {
6964
7351
  this._level = this.parseLogLevel(loggingConfig.level);
6965
7352
  this._enableMetrics = loggingConfig.enableMetrics;
6966
7353
  this._logFilePath = loggingConfig.file;
7354
+ this._enableFileSink = loggingConfig.enableFileSink;
7355
+ this._maxFileSizeBytes = loggingConfig.maxFileSizeMb * 1024 * 1024;
7356
+ this._maxFiles = loggingConfig.maxFiles;
7357
+ logBuffer.setCapacity(loggingConfig.bufferSize);
6967
7358
  } catch {
6968
7359
  this._level = LogLevel.INFO;
6969
7360
  this._enableMetrics = false;
6970
7361
  this._logFilePath = undefined;
7362
+ this._enableFileSink = false;
7363
+ this._maxFileSizeBytes = 32 * 1024 * 1024;
7364
+ this._maxFiles = 5;
7365
+ logBuffer.setCapacity(2000);
6971
7366
  }
6972
7367
  this._initialized = true;
6973
7368
  }
@@ -6984,6 +7379,18 @@ class Logger {
6984
7379
  this.ensureInitialized();
6985
7380
  return this._logFilePath;
6986
7381
  }
7382
+ get enableFileSink() {
7383
+ this.ensureInitialized();
7384
+ return this._enableFileSink;
7385
+ }
7386
+ get maxFileSizeBytes() {
7387
+ this.ensureInitialized();
7388
+ return this._maxFileSizeBytes;
7389
+ }
7390
+ get maxFiles() {
7391
+ this.ensureInitialized();
7392
+ return this._maxFiles;
7393
+ }
6987
7394
  parseLogLevel(level) {
6988
7395
  const levels = {
6989
7396
  debug: LogLevel.DEBUG,
@@ -6996,34 +7403,40 @@ class Logger {
6996
7403
  shouldLog(level) {
6997
7404
  return level >= this.level;
6998
7405
  }
6999
- formatMessage(level, message, meta) {
7000
- const timestamp = new Date().toISOString();
7406
+ formatMessage(level, message, meta, timestamp = new Date().toISOString()) {
7001
7407
  const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
7002
7408
  return `[${timestamp}] [${level}] ${message}${metaStr}`;
7003
7409
  }
7004
- write(message, _level) {
7005
- console.error(message);
7006
- const filePath = this.logFilePath;
7007
- if (filePath) {
7008
- try {
7009
- fs4.appendFileSync(filePath, message + `
7010
- `);
7011
- } catch {}
7410
+ emit(level, message, meta) {
7411
+ const ts = new Date().toISOString();
7412
+ const line = this.formatMessage(LOG_LEVEL_LABELS[level], message, meta, ts);
7413
+ console.error(line);
7414
+ if (this.enableFileSink) {
7415
+ const filePath = this.logFilePath;
7416
+ if (filePath) {
7417
+ appendLine({ filePath, maxFileSizeBytes: this.maxFileSizeBytes, maxFiles: this.maxFiles }, line);
7418
+ }
7012
7419
  }
7420
+ logBuffer.push({
7421
+ ts,
7422
+ level: LOG_LEVEL_BUFFER_TAGS[level],
7423
+ message,
7424
+ ...meta ? { meta } : {}
7425
+ });
7013
7426
  }
7014
7427
  debug(message, meta) {
7015
7428
  if (this.shouldLog(LogLevel.DEBUG)) {
7016
- this.write(this.formatMessage("DEBUG", message, meta), LogLevel.DEBUG);
7429
+ this.emit(LogLevel.DEBUG, message, meta);
7017
7430
  }
7018
7431
  }
7019
7432
  info(message, meta) {
7020
7433
  if (this.shouldLog(LogLevel.INFO)) {
7021
- this.write(this.formatMessage("INFO", message, meta), LogLevel.INFO);
7434
+ this.emit(LogLevel.INFO, message, meta);
7022
7435
  }
7023
7436
  }
7024
7437
  warn(message, meta) {
7025
7438
  if (this.shouldLog(LogLevel.WARN)) {
7026
- this.write(this.formatMessage("WARN", message, meta), LogLevel.WARN);
7439
+ this.emit(LogLevel.WARN, message, meta);
7027
7440
  }
7028
7441
  }
7029
7442
  error(message, error, meta) {
@@ -7036,7 +7449,7 @@ class Logger {
7036
7449
  stack: error.stack
7037
7450
  }
7038
7451
  } : meta;
7039
- this.write(this.formatMessage("ERROR", message, errorMeta), LogLevel.ERROR);
7452
+ this.emit(LogLevel.ERROR, message, errorMeta);
7040
7453
  }
7041
7454
  }
7042
7455
  metric(name, value, unit) {
@@ -7065,15 +7478,29 @@ class Logger {
7065
7478
  return childLogger;
7066
7479
  }
7067
7480
  }
7068
- var LogLevel, logger;
7481
+ var LogLevel, LOG_LEVEL_LABELS, LOG_LEVEL_BUFFER_TAGS, logger;
7069
7482
  var init_logger = __esm(() => {
7070
7483
  init_config();
7484
+ init_log_sink();
7485
+ init_log_buffer();
7071
7486
  (function(LogLevel2) {
7072
7487
  LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
7073
7488
  LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
7074
7489
  LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
7075
7490
  LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
7076
7491
  })(LogLevel || (LogLevel = {}));
7492
+ LOG_LEVEL_LABELS = {
7493
+ [LogLevel.DEBUG]: "DEBUG",
7494
+ [LogLevel.INFO]: "INFO",
7495
+ [LogLevel.WARN]: "WARN",
7496
+ [LogLevel.ERROR]: "ERROR"
7497
+ };
7498
+ LOG_LEVEL_BUFFER_TAGS = {
7499
+ [LogLevel.DEBUG]: "debug",
7500
+ [LogLevel.INFO]: "info",
7501
+ [LogLevel.WARN]: "warn",
7502
+ [LogLevel.ERROR]: "error"
7503
+ };
7077
7504
  logger = new Logger;
7078
7505
  });
7079
7506
 
@@ -7356,6 +7783,8 @@ var init_rate_limiter = __esm(() => {
7356
7783
  // ../../packages/shared/dist/utils/index.js
7357
7784
  var init_utils = __esm(() => {
7358
7785
  init_logger();
7786
+ init_log_buffer();
7787
+ init_log_sink();
7359
7788
  init_sanitizer();
7360
7789
  init_metrics();
7361
7790
  init_rate_limiter();
@@ -7363,7 +7792,7 @@ var init_utils = __esm(() => {
7363
7792
 
7364
7793
  // ../../packages/shared/dist/profile-switch/hosts.js
7365
7794
  import os3 from "os";
7366
- import path7 from "path";
7795
+ import path8 from "path";
7367
7796
  function isHost(v) {
7368
7797
  return typeof v === "string" && HOSTS.includes(v);
7369
7798
  }
@@ -7374,7 +7803,7 @@ function fileLayout(host, activeDir, activeGlob, variantsRoot) {
7374
7803
  activeDir,
7375
7804
  activeGlob,
7376
7805
  variantsRoot,
7377
- variantDir: (profile) => path7.join(variantsRoot, profile)
7806
+ variantDir: (profile) => path8.join(variantsRoot, profile)
7378
7807
  };
7379
7808
  }
7380
7809
  function resolveHostLayout(host, opts = {}) {
@@ -7384,25 +7813,37 @@ function resolveHostLayout(host, opts = {}) {
7384
7813
  case "cursor":
7385
7814
  return { host, route: "skip", reason: CURSOR_SKIP_REASON };
7386
7815
  case "claude": {
7387
- const root = override ?? path7.join(targetHome, ".claude");
7388
- return fileLayout(host, path7.join(root, "agents"), "massa-ai-*.md", path7.join(root, "massa-ai", "agent-profiles"));
7816
+ const marketplaceRoot = opts.marketplaceRoot?.claude;
7817
+ if (override === undefined && marketplaceRoot !== undefined) {
7818
+ return fileLayout(host, path8.join(marketplaceRoot, "agents"), "massa-ai-*.md", path8.join(marketplaceRoot, "agent-profiles"));
7819
+ }
7820
+ const root = override ?? path8.join(targetHome, ".claude");
7821
+ return fileLayout(host, path8.join(root, "agents"), "massa-ai-*.md", path8.join(root, "massa-ai", "agent-profiles"));
7389
7822
  }
7390
7823
  case "codex": {
7391
- const root = override ?? path7.join(targetHome, ".codex");
7392
- return fileLayout(host, path7.join(root, "agents"), "massa-ai-*.toml", path7.join(root, "massa-ai", "agent-profiles"));
7824
+ const root = override ?? path8.join(targetHome, ".codex");
7825
+ return fileLayout(host, path8.join(root, "agents"), "massa-ai-*.toml", path8.join(root, "massa-ai", "agent-profiles"));
7393
7826
  }
7394
7827
  case "opencode": {
7395
- const root = override ?? path7.join(targetHome, ".config", "opencode");
7396
- const pluginsDir = path7.join(root, "plugins", "massa-ai");
7397
- return fileLayout(host, path7.join(root, "agents"), "massa-ai-*.md", path7.join(pluginsDir, "agent-profiles"));
7828
+ const root = override ?? path8.join(targetHome, ".config", "opencode");
7829
+ const pluginsDir = path8.join(root, "plugins", "massa-ai");
7830
+ return fileLayout(host, path8.join(root, "agents"), "massa-ai-*.md", path8.join(pluginsDir, "agent-profiles"));
7398
7831
  }
7399
7832
  }
7400
7833
  }
7401
- function detectRoute(platform) {
7834
+ function detectRoute(platform, host) {
7402
7835
  const route = platform?.installRoute;
7403
7836
  if (route === "file")
7404
7837
  return { kind: "proceed" };
7405
7838
  if (route === "marketplace") {
7839
+ if (host === "claude")
7840
+ return { kind: "proceed" };
7841
+ if (host === "codex") {
7842
+ return {
7843
+ kind: "refuse",
7844
+ reason: "codex marketplace-route installs are refused (in-place bundle rewrite would dirty a checkout " + "and break the drift gate) \u2014 use the dev path: MASSA_AI_MODEL_PROFILE + regenerate."
7845
+ };
7846
+ }
7406
7847
  return {
7407
7848
  kind: "refuse",
7408
7849
  reason: "claude/codex marketplace-route installs are refused (in-place bundle rewrite would dirty a checkout " + "and break the drift gate) \u2014 use the dev path: MASSA_AI_MODEL_PROFILE + regenerate."
@@ -7420,7 +7861,7 @@ var init_hosts = __esm(() => {
7420
7861
 
7421
7862
  // ../../packages/shared/dist/profile-switch/state.js
7422
7863
  import fs5 from "fs";
7423
- import path8 from "path";
7864
+ import path9 from "path";
7424
7865
  function namedError(name, message) {
7425
7866
  const err = new InstallStateError(message);
7426
7867
  err.name = name;
@@ -7466,7 +7907,7 @@ function writeInstallState(filePath, state) {
7466
7907
  const text = `${JSON.stringify(validated, null, 2)}
7467
7908
  `;
7468
7909
  try {
7469
- fs5.mkdirSync(path8.dirname(filePath), { recursive: true });
7910
+ fs5.mkdirSync(path9.dirname(filePath), { recursive: true });
7470
7911
  fs5.writeFileSync(filePath, text);
7471
7912
  } catch (err) {
7472
7913
  throw UnwritableInstallStateError(filePath, err.message);
@@ -7495,7 +7936,7 @@ var init_state = __esm(() => {
7495
7936
 
7496
7937
  // ../../packages/shared/dist/profile-switch/lock.js
7497
7938
  import fs6 from "fs";
7498
- import path9 from "path";
7939
+ import path10 from "path";
7499
7940
  import os4 from "os";
7500
7941
  import crypto4 from "crypto";
7501
7942
  import { execFileSync } from "child_process";
@@ -7527,7 +7968,7 @@ function releaseIfOwned(lockDir, ownerPath, token) {
7527
7968
  }
7528
7969
  function acquireLock(stateFilePath, options = {}) {
7529
7970
  const lockDir = `${stateFilePath}.switch.lock`;
7530
- const ownerPath = path9.join(lockDir, "owner.json");
7971
+ const ownerPath = path10.join(lockDir, "owner.json");
7531
7972
  const clock = options.clock ?? DEFAULT_CLOCK;
7532
7973
  const identity = options.identity ?? DEFAULT_IDENTITY;
7533
7974
  const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
@@ -7547,7 +7988,7 @@ function acquireLock(stateFilePath, options = {}) {
7547
7988
  token,
7548
7989
  timestamp: clock.now()
7549
7990
  };
7550
- fs6.mkdirSync(path9.dirname(ownerPath), { recursive: true });
7991
+ fs6.mkdirSync(path10.dirname(ownerPath), { recursive: true });
7551
7992
  fs6.writeFileSync(ownerPath, JSON.stringify(record));
7552
7993
  return { lockDir, release: () => releaseIfOwned(lockDir, ownerPath, token) };
7553
7994
  };
@@ -7600,10 +8041,59 @@ var init_lock = __esm(() => {
7600
8041
  };
7601
8042
  });
7602
8043
 
7603
- // ../../packages/shared/dist/profile-switch/engine.js
8044
+ // ../../packages/shared/dist/profile-switch/claude-marketplace.js
7604
8045
  import fs7 from "fs";
7605
- import path10 from "path";
7606
8046
  import os5 from "os";
8047
+ import path11 from "path";
8048
+ function selectRecord(records) {
8049
+ if (records.length === 0)
8050
+ return;
8051
+ const userScoped = records.filter((r2) => r2.scope === "user");
8052
+ const pool = userScoped.length > 0 ? userScoped : records;
8053
+ let best;
8054
+ let bestTime = -Infinity;
8055
+ for (const record of pool) {
8056
+ const parsed = record.lastUpdated ? Date.parse(record.lastUpdated) : NaN;
8057
+ if (Number.isFinite(parsed) && parsed >= bestTime) {
8058
+ best = record;
8059
+ bestTime = parsed;
8060
+ }
8061
+ }
8062
+ return best ?? pool[pool.length - 1];
8063
+ }
8064
+ function resolveClaudeMarketplaceRoot(opts = {}) {
8065
+ const targetHome = opts.targetHome ?? os5.homedir();
8066
+ const pluginKey = opts.pluginKey ?? DEFAULT_PLUGIN_KEY;
8067
+ const registryPath = path11.join(targetHome, ".claude", "plugins", "installed_plugins.json");
8068
+ let records;
8069
+ try {
8070
+ const raw2 = fs7.readFileSync(registryPath, "utf8");
8071
+ const parsed = JSON.parse(raw2);
8072
+ records = parsed?.plugins?.[pluginKey];
8073
+ } catch {
8074
+ return null;
8075
+ }
8076
+ if (!Array.isArray(records) || records.length === 0)
8077
+ return null;
8078
+ const selected = selectRecord(records);
8079
+ const installPath = selected?.installPath;
8080
+ if (!installPath)
8081
+ return null;
8082
+ try {
8083
+ if (!fs7.existsSync(installPath))
8084
+ return null;
8085
+ } catch {
8086
+ return null;
8087
+ }
8088
+ return installPath;
8089
+ }
8090
+ var DEFAULT_PLUGIN_KEY = "massa-ai@massa-ai";
8091
+ var init_claude_marketplace = () => {};
8092
+
8093
+ // ../../packages/shared/dist/profile-switch/engine.js
8094
+ import fs8 from "fs";
8095
+ import path12 from "path";
8096
+ import os6 from "os";
7607
8097
  import crypto5 from "crypto";
7608
8098
  function namedError3(name, message) {
7609
8099
  const err = new SwitchEngineError(message);
@@ -7611,19 +8101,39 @@ function namedError3(name, message) {
7611
8101
  return err;
7612
8102
  }
7613
8103
  function defaultStatePath(targetHome) {
7614
- return path10.join(targetHome, ".config", "massa-ai", "install-state.json");
8104
+ return path12.join(targetHome, ".config", "massa-ai", "install-state.json");
7615
8105
  }
7616
8106
  function resolveCommon(opts) {
7617
- const targetHome = opts.targetHome ?? os5.homedir();
8107
+ const targetHome = opts.targetHome ?? os6.homedir();
7618
8108
  const stateFilePath = opts.stateFilePath ?? defaultStatePath(targetHome);
7619
8109
  return { targetHome, stateFilePath };
7620
8110
  }
8111
+ function marketplaceRoots(targetHome, state) {
8112
+ return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
8113
+ }
8114
+ function claudeMarketplaceUnresolvedReason(targetHome) {
8115
+ const registryPath = path12.join(targetHome, ".claude", "plugins", "installed_plugins.json");
8116
+ return `claude installRoute is "marketplace" but no install root could be resolved from ${registryPath} ` + "\u2014 re-run the Claude plugin installer, or verify the plugin registry file";
8117
+ }
7621
8118
  function listProfiles(opts = {}) {
7622
8119
  const { targetHome, stateFilePath } = resolveCommon(opts);
7623
8120
  const state = readInstallState(stateFilePath);
8121
+ const roots = marketplaceRoots(targetHome, state);
7624
8122
  const universe = opts.hosts ?? HOSTS;
7625
8123
  const hosts = universe.map((host) => {
7626
- const layout = resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot });
8124
+ if (host === "claude" && state.platforms.claude?.installRoute === "marketplace" && roots.claude === undefined) {
8125
+ const platform2 = state.platforms.claude;
8126
+ return {
8127
+ host,
8128
+ installed: false,
8129
+ skipped: false,
8130
+ skipReason: null,
8131
+ activeProfile: platform2.modelProfile?.profile ?? opts.hostDefaults?.[host] ?? "balanced",
8132
+ bundleVersion: platform2.plugin?.version ?? null,
8133
+ availableProfiles: []
8134
+ };
8135
+ }
8136
+ const layout = resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot, marketplaceRoot: roots });
7627
8137
  if (layout.route === "skip") {
7628
8138
  return {
7629
8139
  host,
@@ -7635,7 +8145,7 @@ function listProfiles(opts = {}) {
7635
8145
  availableProfiles: []
7636
8146
  };
7637
8147
  }
7638
- const installed = fs7.existsSync(layout.activeDir);
8148
+ const installed = fs8.existsSync(layout.activeDir);
7639
8149
  const availableProfiles = listVariantProfiles(layout);
7640
8150
  const platform = state.platforms[host];
7641
8151
  return {
@@ -7651,9 +8161,9 @@ function listProfiles(opts = {}) {
7651
8161
  return { hosts };
7652
8162
  }
7653
8163
  function listVariantProfiles(layout) {
7654
- if (!fs7.existsSync(layout.variantsRoot))
8164
+ if (!fs8.existsSync(layout.variantsRoot))
7655
8165
  return [];
7656
- return fs7.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
8166
+ return fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
7657
8167
  }
7658
8168
  function matchesGlob(filename, glob) {
7659
8169
  const starIdx = glob.indexOf("*");
@@ -7664,50 +8174,50 @@ function matchesGlob(filename, glob) {
7664
8174
  return filename.length >= prefix.length + suffix.length && filename.startsWith(prefix) && filename.endsWith(suffix);
7665
8175
  }
7666
8176
  function assertStateWritable(stateFilePath) {
7667
- const dir = path10.dirname(stateFilePath);
8177
+ const dir = path12.dirname(stateFilePath);
7668
8178
  try {
7669
- fs7.mkdirSync(dir, { recursive: true });
8179
+ fs8.mkdirSync(dir, { recursive: true });
7670
8180
  } catch (err) {
7671
8181
  throw UnwritableInstallStateError(stateFilePath, err.message);
7672
8182
  }
7673
- const checkPath = fs7.existsSync(stateFilePath) ? stateFilePath : dir;
8183
+ const checkPath = fs8.existsSync(stateFilePath) ? stateFilePath : dir;
7674
8184
  try {
7675
- fs7.accessSync(checkPath, fs7.constants.W_OK);
8185
+ fs8.accessSync(checkPath, fs8.constants.W_OK);
7676
8186
  } catch (err) {
7677
8187
  throw UnwritableInstallStateError(stateFilePath, err.message);
7678
8188
  }
7679
8189
  }
7680
8190
  function copyFileRouteVariant(layout, variantDir) {
7681
- fs7.mkdirSync(layout.activeDir, { recursive: true });
8191
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
7682
8192
  let changed = 0;
7683
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
8193
+ for (const entry of fs8.readdirSync(variantDir, { withFileTypes: true })) {
7684
8194
  if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
7685
8195
  continue;
7686
- fs7.copyFileSync(path10.join(variantDir, entry.name), path10.join(layout.activeDir, entry.name));
8196
+ fs8.copyFileSync(path12.join(variantDir, entry.name), path12.join(layout.activeDir, entry.name));
7687
8197
  changed++;
7688
8198
  }
7689
8199
  return changed;
7690
8200
  }
7691
8201
  function repointOpencodeVariant(layout, variantDir) {
7692
- fs7.mkdirSync(layout.activeDir, { recursive: true });
8202
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
7693
8203
  let changed = 0;
7694
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
8204
+ for (const entry of fs8.readdirSync(variantDir, { withFileTypes: true })) {
7695
8205
  if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
7696
8206
  continue;
7697
- const dest = path10.join(layout.activeDir, entry.name);
7698
- const target = path10.resolve(path10.join(variantDir, entry.name));
8207
+ const dest = path12.join(layout.activeDir, entry.name);
8208
+ const target = path12.resolve(path12.join(variantDir, entry.name));
7699
8209
  let destExists = true;
7700
8210
  let destIsSymlink = false;
7701
8211
  try {
7702
- destIsSymlink = fs7.lstatSync(dest).isSymbolicLink();
8212
+ destIsSymlink = fs8.lstatSync(dest).isSymbolicLink();
7703
8213
  } catch {
7704
8214
  destExists = false;
7705
8215
  }
7706
8216
  if (destExists && !destIsSymlink)
7707
8217
  continue;
7708
8218
  const tmp = `${dest}.massa-ai-switch.${crypto5.randomUUID()}`;
7709
- fs7.symlinkSync(target, tmp);
7710
- fs7.renameSync(tmp, dest);
8219
+ fs8.symlinkSync(target, tmp);
8220
+ fs8.renameSync(tmp, dest);
7711
8221
  changed++;
7712
8222
  }
7713
8223
  return changed;
@@ -7723,19 +8233,37 @@ function switchProfile(opts) {
7723
8233
  const state = readInstallState(stateFilePath);
7724
8234
  if (!dryRun)
7725
8235
  assertStateWritable(stateFilePath);
7726
- const layouts = universe.map((host) => ({ host, layout: resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot }) }));
7727
- const skipRows = layouts.filter((l2) => l2.layout.route === "skip").map((l2) => ({ host: l2.host, status: "skipped", reason: l2.layout.reason }));
8236
+ const roots = marketplaceRoots(targetHome, state);
8237
+ const unresolvedRows = [];
8238
+ const resolvableUniverse = universe.filter((host) => {
8239
+ if (host !== "claude")
8240
+ return true;
8241
+ if (state.platforms.claude?.installRoute !== "marketplace")
8242
+ return true;
8243
+ if (roots.claude !== undefined)
8244
+ return true;
8245
+ unresolvedRows.push({ host, status: "failed", reason: claudeMarketplaceUnresolvedReason(targetHome) });
8246
+ return false;
8247
+ });
8248
+ const layouts = resolvableUniverse.map((host) => ({
8249
+ host,
8250
+ layout: resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot, marketplaceRoot: roots })
8251
+ }));
8252
+ const skipRows = [
8253
+ ...unresolvedRows,
8254
+ ...layouts.filter((l2) => l2.layout.route === "skip").map((l2) => ({ host: l2.host, status: "skipped", reason: l2.layout.reason }))
8255
+ ];
7728
8256
  const fileHosts = layouts.filter((l2) => l2.layout.route === "files");
7729
8257
  if (fileHosts.length === 0) {
7730
8258
  return { profile: opts.profile, dryRun, hosts: orderRows(universe, skipRows), restartRequired: false };
7731
8259
  }
7732
- const installedFileHosts = fileHosts.filter((h) => fs7.existsSync(h.layout.activeDir));
8260
+ const installedFileHosts = fileHosts.filter((h) => fs8.existsSync(h.layout.activeDir));
7733
8261
  if (installedFileHosts.length === 0)
7734
8262
  throw NoHostsDetectedError();
7735
8263
  const withAvailability = fileHosts.map((h) => {
7736
- const variantsRootExists = fs7.existsSync(h.layout.variantsRoot);
8264
+ const variantsRootExists = fs8.existsSync(h.layout.variantsRoot);
7737
8265
  const variantDir = h.layout.variantDir(opts.profile);
7738
- const available = variantsRootExists && fs7.existsSync(variantDir) && fs7.statSync(variantDir).isDirectory();
8266
+ const available = variantsRootExists && fs8.existsSync(variantDir) && fs8.statSync(variantDir).isDirectory();
7739
8267
  return { ...h, variantsRootExists, variantDir, available };
7740
8268
  });
7741
8269
  if (!withAvailability.some((h) => h.available)) {
@@ -7765,7 +8293,7 @@ function switchProfile(opts) {
7765
8293
  });
7766
8294
  continue;
7767
8295
  }
7768
- const route = detectRoute(state.platforms[h.host]);
8296
+ const route = detectRoute(state.platforms[h.host], h.host);
7769
8297
  if (route.kind === "refuse") {
7770
8298
  rows.push({ host: h.host, status: "failed", reason: route.reason });
7771
8299
  continue;
@@ -7800,6 +8328,7 @@ var init_engine = __esm(() => {
7800
8328
  init_hosts();
7801
8329
  init_state();
7802
8330
  init_lock();
8331
+ init_claude_marketplace();
7803
8332
  SwitchEngineError = class SwitchEngineError extends Error {
7804
8333
  constructor(message) {
7805
8334
  super(message);
@@ -7814,18 +8343,25 @@ function reportSucceeded(report) {
7814
8343
  }
7815
8344
 
7816
8345
  // ../../packages/shared/dist/profile-switch/variant-sync.js
7817
- import fs8 from "fs";
7818
- import path11 from "path";
8346
+ import fs9 from "fs";
8347
+ import path13 from "path";
8348
+ import os7 from "os";
7819
8349
  import crypto6 from "crypto";
8350
+ function defaultStatePath2(targetHome) {
8351
+ return path13.join(targetHome, ".config", "massa-ai", "install-state.json");
8352
+ }
8353
+ function marketplaceRoots2(targetHome, state) {
8354
+ return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
8355
+ }
7820
8356
  function writeFileIntoDirAtomically(destDir, destName, content) {
7821
8357
  const unique = `${process.pid}.${++tempFileCounter2}.${crypto6.randomBytes(6).toString("hex")}`;
7822
- const tempFile = path11.join(destDir, `.${destName}.${unique}.tmp`);
8358
+ const tempFile = path13.join(destDir, `.${destName}.${unique}.tmp`);
7823
8359
  try {
7824
- fs8.writeFileSync(tempFile, content);
7825
- fs8.renameSync(tempFile, path11.join(destDir, destName));
8360
+ fs9.writeFileSync(tempFile, content);
8361
+ fs9.renameSync(tempFile, path13.join(destDir, destName));
7826
8362
  } catch (error) {
7827
8363
  try {
7828
- fs8.unlinkSync(tempFile);
8364
+ fs9.unlinkSync(tempFile);
7829
8365
  } catch {}
7830
8366
  throw error;
7831
8367
  }
@@ -7833,20 +8369,20 @@ function writeFileIntoDirAtomically(destDir, destName, content) {
7833
8369
  function isSafeDirName(name) {
7834
8370
  if (name === "." || name === "..")
7835
8371
  return false;
7836
- if (name.includes("/") || name.includes("\\") || name.includes(path11.sep))
8372
+ if (name.includes("/") || name.includes("\\") || name.includes(path13.sep))
7837
8373
  return false;
7838
- return path11.basename(name) === name;
8374
+ return path13.basename(name) === name;
7839
8375
  }
7840
- function syncHost(host, sourceRoot, targetHome) {
7841
- const layout = resolveHostLayout(host, { targetHome });
8376
+ function syncHost(host, sourceRoot, targetHome, marketplaceRoot) {
8377
+ const layout = resolveHostLayout(host, { targetHome, marketplaceRoot });
7842
8378
  if (layout.route === "skip") {
7843
8379
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: layout.reason };
7844
8380
  }
7845
- const srcDir = path11.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
7846
- if (!fs8.existsSync(srcDir) || !fs8.statSync(srcDir).isDirectory()) {
8381
+ const srcDir = path13.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
8382
+ if (!fs9.existsSync(srcDir) || !fs9.statSync(srcDir).isDirectory()) {
7847
8383
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: "no generated variants for this host" };
7848
8384
  }
7849
- if (!fs8.existsSync(layout.variantsRoot)) {
8385
+ if (!fs9.existsSync(layout.variantsRoot)) {
7850
8386
  return {
7851
8387
  host,
7852
8388
  status: "skipped",
@@ -7858,24 +8394,24 @@ function syncHost(host, sourceRoot, targetHome) {
7858
8394
  }
7859
8395
  const profiles = [];
7860
8396
  let files = 0;
7861
- for (const entry of fs8.readdirSync(srcDir, { withFileTypes: true })) {
8397
+ for (const entry of fs9.readdirSync(srcDir, { withFileTypes: true })) {
7862
8398
  if (!entry.isDirectory())
7863
8399
  continue;
7864
8400
  if (!isSafeDirName(entry.name))
7865
8401
  continue;
7866
- const srcProfileDir = path11.join(srcDir, entry.name);
7867
- const destProfileDir = path11.join(layout.variantsRoot, entry.name);
7868
- fs8.mkdirSync(destProfileDir, { recursive: true });
7869
- for (const fileEntry of fs8.readdirSync(srcProfileDir, { withFileTypes: true })) {
8402
+ const srcProfileDir = path13.join(srcDir, entry.name);
8403
+ const destProfileDir = path13.join(layout.variantsRoot, entry.name);
8404
+ fs9.mkdirSync(destProfileDir, { recursive: true });
8405
+ for (const fileEntry of fs9.readdirSync(srcProfileDir, { withFileTypes: true })) {
7870
8406
  if (!fileEntry.isFile())
7871
8407
  continue;
7872
- const content = fs8.readFileSync(path11.join(srcProfileDir, fileEntry.name));
8408
+ const content = fs9.readFileSync(path13.join(srcProfileDir, fileEntry.name));
7873
8409
  writeFileIntoDirAtomically(destProfileDir, fileEntry.name, content);
7874
8410
  files++;
7875
8411
  }
7876
8412
  profiles.push(entry.name);
7877
8413
  }
7878
- const retained = fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
8414
+ const retained = fs9.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
7879
8415
  return { host, status: "synced", profiles: profiles.sort(), retained, files };
7880
8416
  }
7881
8417
  function syncGeneratedVariants(opts) {
@@ -7891,9 +8427,12 @@ function syncGeneratedVariants(opts) {
7891
8427
  }));
7892
8428
  }
7893
8429
  const sourceRoot = opts.sourceRoot;
8430
+ const targetHome = opts.targetHome ?? os7.homedir();
8431
+ const state = readInstallState(defaultStatePath2(targetHome));
8432
+ const roots = marketplaceRoots2(targetHome, state);
7894
8433
  return hosts.map((host) => {
7895
8434
  try {
7896
- return syncHost(host, sourceRoot, opts.targetHome);
8435
+ return syncHost(host, sourceRoot, opts.targetHome, roots);
7897
8436
  } catch (err) {
7898
8437
  return { host, status: "failed", profiles: [], retained: [], files: 0, error: err.message };
7899
8438
  }
@@ -7902,17 +8441,19 @@ function syncGeneratedVariants(opts) {
7902
8441
  var tempFileCounter2 = 0;
7903
8442
  var init_variant_sync = __esm(() => {
7904
8443
  init_hosts();
8444
+ init_state();
8445
+ init_claude_marketplace();
7905
8446
  });
7906
8447
 
7907
8448
  // ../../packages/shared/dist/profile-switch/repo-root.js
7908
- import fs9 from "fs";
7909
- import path12 from "path";
8449
+ import fs10 from "fs";
8450
+ import path14 from "path";
7910
8451
  function findRepoRootWithMarker(startDir, marker, maxLevels) {
7911
8452
  let dir = startDir;
7912
8453
  for (let i = 0;i <= maxLevels; i++) {
7913
- if (fs9.existsSync(path12.join(dir, marker)))
8454
+ if (fs10.existsSync(path14.join(dir, marker)))
7914
8455
  return dir;
7915
- const parent = path12.dirname(dir);
8456
+ const parent = path14.dirname(dir);
7916
8457
  if (parent === dir)
7917
8458
  break;
7918
8459
  dir = parent;
@@ -9452,7 +9993,7 @@ var import_brace_expansion, minimatch = (p, pattern, options = {}) => {
9452
9993
  }, qmarksTestNoExtDot = ([$0]) => {
9453
9994
  const len = $0.length;
9454
9995
  return (f) => f.length === len && f !== "." && f !== "..";
9455
- }, defaultPlatform, path13, sep, GLOBSTAR, qmark2 = "[^/]", star2, twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options), ext = (a12, b = {}) => Object.assign({}, a12, b), defaults = (def) => {
9996
+ }, defaultPlatform, path15, sep, GLOBSTAR, qmark2 = "[^/]", star2, twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options), ext = (a12, b = {}) => Object.assign({}, a12, b), defaults = (def) => {
9456
9997
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
9457
9998
  return minimatch;
9458
9999
  }
@@ -9510,11 +10051,11 @@ var init_esm = __esm(() => {
9510
10051
  starRE = /^\*+$/;
9511
10052
  qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
9512
10053
  defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
9513
- path13 = {
10054
+ path15 = {
9514
10055
  win32: { sep: "\\" },
9515
10056
  posix: { sep: "/" }
9516
10057
  };
9517
- sep = defaultPlatform === "win32" ? path13.win32.sep : path13.posix.sep;
10058
+ sep = defaultPlatform === "win32" ? path15.win32.sep : path15.posix.sep;
9518
10059
  minimatch.sep = sep;
9519
10060
  GLOBSTAR = Symbol("globstar **");
9520
10061
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -11480,12 +12021,12 @@ var init_esm4 = __esm(() => {
11480
12021
  childrenCache() {
11481
12022
  return this.#children;
11482
12023
  }
11483
- resolve(path14) {
11484
- if (!path14) {
12024
+ resolve(path16) {
12025
+ if (!path16) {
11485
12026
  return this;
11486
12027
  }
11487
- const rootPath = this.getRootString(path14);
11488
- const dir = path14.substring(rootPath.length);
12028
+ const rootPath = this.getRootString(path16);
12029
+ const dir = path16.substring(rootPath.length);
11489
12030
  const dirParts = dir.split(this.splitSep);
11490
12031
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
11491
12032
  return result;
@@ -12013,8 +12554,8 @@ var init_esm4 = __esm(() => {
12013
12554
  newChild(name, type = UNKNOWN, opts = {}) {
12014
12555
  return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
12015
12556
  }
12016
- getRootString(path14) {
12017
- return win32.parse(path14).root;
12557
+ getRootString(path16) {
12558
+ return win32.parse(path16).root;
12018
12559
  }
12019
12560
  getRoot(rootPath) {
12020
12561
  rootPath = uncToDrive(rootPath.toUpperCase());
@@ -12039,8 +12580,8 @@ var init_esm4 = __esm(() => {
12039
12580
  constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
12040
12581
  super(name, type, root, roots, nocase, children, opts);
12041
12582
  }
12042
- getRootString(path14) {
12043
- return path14.startsWith("/") ? "/" : "";
12583
+ getRootString(path16) {
12584
+ return path16.startsWith("/") ? "/" : "";
12044
12585
  }
12045
12586
  getRoot(_rootPath) {
12046
12587
  return this.root;
@@ -12059,8 +12600,8 @@ var init_esm4 = __esm(() => {
12059
12600
  #children;
12060
12601
  nocase;
12061
12602
  #fs;
12062
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs10 = defaultFS } = {}) {
12063
- this.#fs = fsFromOption(fs10);
12603
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs11 = defaultFS } = {}) {
12604
+ this.#fs = fsFromOption(fs11);
12064
12605
  if (cwd instanceof URL || cwd.startsWith("file://")) {
12065
12606
  cwd = fileURLToPath(cwd);
12066
12607
  }
@@ -12096,11 +12637,11 @@ var init_esm4 = __esm(() => {
12096
12637
  }
12097
12638
  this.cwd = prev;
12098
12639
  }
12099
- depth(path14 = this.cwd) {
12100
- if (typeof path14 === "string") {
12101
- path14 = this.cwd.resolve(path14);
12640
+ depth(path16 = this.cwd) {
12641
+ if (typeof path16 === "string") {
12642
+ path16 = this.cwd.resolve(path16);
12102
12643
  }
12103
- return path14.depth();
12644
+ return path16.depth();
12104
12645
  }
12105
12646
  childrenCache() {
12106
12647
  return this.#children;
@@ -12516,9 +13057,9 @@ var init_esm4 = __esm(() => {
12516
13057
  process2();
12517
13058
  return results;
12518
13059
  }
12519
- chdir(path14 = this.cwd) {
13060
+ chdir(path16 = this.cwd) {
12520
13061
  const oldCwd = this.cwd;
12521
- this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
13062
+ this.cwd = typeof path16 === "string" ? this.cwd.resolve(path16) : path16;
12522
13063
  this.cwd[setAsCwd](oldCwd);
12523
13064
  }
12524
13065
  };
@@ -12535,8 +13076,8 @@ var init_esm4 = __esm(() => {
12535
13076
  parseRootPath(dir) {
12536
13077
  return win32.parse(dir).root.toUpperCase();
12537
13078
  }
12538
- newRoot(fs10) {
12539
- return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs10 });
13079
+ newRoot(fs11) {
13080
+ return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs11 });
12540
13081
  }
12541
13082
  isAbsolute(p) {
12542
13083
  return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
@@ -12552,8 +13093,8 @@ var init_esm4 = __esm(() => {
12552
13093
  parseRootPath(_dir) {
12553
13094
  return "/";
12554
13095
  }
12555
- newRoot(fs10) {
12556
- return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs10 });
13096
+ newRoot(fs11) {
13097
+ return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs11 });
12557
13098
  }
12558
13099
  isAbsolute(p) {
12559
13100
  return p.startsWith("/");
@@ -12810,8 +13351,8 @@ class MatchRecord {
12810
13351
  this.store.set(target, current === undefined ? n2 : n2 & current);
12811
13352
  }
12812
13353
  entries() {
12813
- return [...this.store.entries()].map(([path14, n2]) => [
12814
- path14,
13354
+ return [...this.store.entries()].map(([path16, n2]) => [
13355
+ path16,
12815
13356
  !!(n2 & 2),
12816
13357
  !!(n2 & 1)
12817
13358
  ]);
@@ -13015,9 +13556,9 @@ class GlobUtil {
13015
13556
  signal;
13016
13557
  maxDepth;
13017
13558
  includeChildMatches;
13018
- constructor(patterns, path14, opts) {
13559
+ constructor(patterns, path16, opts) {
13019
13560
  this.patterns = patterns;
13020
- this.path = path14;
13561
+ this.path = path16;
13021
13562
  this.opts = opts;
13022
13563
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
13023
13564
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -13036,11 +13577,11 @@ class GlobUtil {
13036
13577
  });
13037
13578
  }
13038
13579
  }
13039
- #ignored(path14) {
13040
- return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
13580
+ #ignored(path16) {
13581
+ return this.seen.has(path16) || !!this.#ignore?.ignored?.(path16);
13041
13582
  }
13042
- #childrenIgnored(path14) {
13043
- return !!this.#ignore?.childrenIgnored?.(path14);
13583
+ #childrenIgnored(path16) {
13584
+ return !!this.#ignore?.childrenIgnored?.(path16);
13044
13585
  }
13045
13586
  pause() {
13046
13587
  this.paused = true;
@@ -13257,8 +13798,8 @@ var init_walker = __esm(() => {
13257
13798
  init_processor();
13258
13799
  GlobWalker = class GlobWalker extends GlobUtil {
13259
13800
  matches = new Set;
13260
- constructor(patterns, path14, opts) {
13261
- super(patterns, path14, opts);
13801
+ constructor(patterns, path16, opts) {
13802
+ super(patterns, path16, opts);
13262
13803
  }
13263
13804
  matchEmit(e) {
13264
13805
  this.matches.add(e);
@@ -13295,8 +13836,8 @@ var init_walker = __esm(() => {
13295
13836
  };
13296
13837
  GlobStream = class GlobStream extends GlobUtil {
13297
13838
  results;
13298
- constructor(patterns, path14, opts) {
13299
- super(patterns, path14, opts);
13839
+ constructor(patterns, path16, opts) {
13840
+ super(patterns, path16, opts);
13300
13841
  this.results = new Minipass({
13301
13842
  signal: this.signal,
13302
13843
  objectMode: true
@@ -13724,20 +14265,20 @@ var require_ignore = __commonJS((exports, module) => {
13724
14265
  var throwError = (message, Ctor) => {
13725
14266
  throw new Ctor(message);
13726
14267
  };
13727
- var checkPath = (path14, originalPath, doThrow) => {
13728
- if (!isString(path14)) {
14268
+ var checkPath = (path16, originalPath, doThrow) => {
14269
+ if (!isString(path16)) {
13729
14270
  return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
13730
14271
  }
13731
- if (!path14) {
14272
+ if (!path16) {
13732
14273
  return doThrow(`path must not be empty`, TypeError);
13733
14274
  }
13734
- if (checkPath.isNotRelative(path14)) {
14275
+ if (checkPath.isNotRelative(path16)) {
13735
14276
  const r2 = "`path.relative()`d";
13736
14277
  return doThrow(`path should be a ${r2} string, but got "${originalPath}"`, RangeError);
13737
14278
  }
13738
14279
  return true;
13739
14280
  };
13740
- var isNotRelative = (path14) => REGEX_TEST_INVALID_PATH.test(path14);
14281
+ var isNotRelative = (path16) => REGEX_TEST_INVALID_PATH.test(path16);
13741
14282
  checkPath.isNotRelative = isNotRelative;
13742
14283
  checkPath.convert = (p) => p;
13743
14284
 
@@ -13780,7 +14321,7 @@ var require_ignore = __commonJS((exports, module) => {
13780
14321
  addPattern(pattern) {
13781
14322
  return this.add(pattern);
13782
14323
  }
13783
- _testOne(path14, checkUnignored) {
14324
+ _testOne(path16, checkUnignored) {
13784
14325
  let ignored = false;
13785
14326
  let unignored = false;
13786
14327
  this._rules.forEach((rule) => {
@@ -13788,7 +14329,7 @@ var require_ignore = __commonJS((exports, module) => {
13788
14329
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
13789
14330
  return;
13790
14331
  }
13791
- const matched = rule.regex.test(path14);
14332
+ const matched = rule.regex.test(path16);
13792
14333
  if (matched) {
13793
14334
  ignored = !negative;
13794
14335
  unignored = negative;
@@ -13800,39 +14341,39 @@ var require_ignore = __commonJS((exports, module) => {
13800
14341
  };
13801
14342
  }
13802
14343
  _test(originalPath, cache, checkUnignored, slices) {
13803
- const path14 = originalPath && checkPath.convert(originalPath);
13804
- checkPath(path14, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
13805
- return this._t(path14, cache, checkUnignored, slices);
14344
+ const path16 = originalPath && checkPath.convert(originalPath);
14345
+ checkPath(path16, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
14346
+ return this._t(path16, cache, checkUnignored, slices);
13806
14347
  }
13807
- _t(path14, cache, checkUnignored, slices) {
13808
- if (path14 in cache) {
13809
- return cache[path14];
14348
+ _t(path16, cache, checkUnignored, slices) {
14349
+ if (path16 in cache) {
14350
+ return cache[path16];
13810
14351
  }
13811
14352
  if (!slices) {
13812
- slices = path14.split(SLASH);
14353
+ slices = path16.split(SLASH);
13813
14354
  }
13814
14355
  slices.pop();
13815
14356
  if (!slices.length) {
13816
- return cache[path14] = this._testOne(path14, checkUnignored);
14357
+ return cache[path16] = this._testOne(path16, checkUnignored);
13817
14358
  }
13818
14359
  const parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
13819
- return cache[path14] = parent.ignored ? parent : this._testOne(path14, checkUnignored);
14360
+ return cache[path16] = parent.ignored ? parent : this._testOne(path16, checkUnignored);
13820
14361
  }
13821
- ignores(path14) {
13822
- return this._test(path14, this._ignoreCache, false).ignored;
14362
+ ignores(path16) {
14363
+ return this._test(path16, this._ignoreCache, false).ignored;
13823
14364
  }
13824
14365
  createFilter() {
13825
- return (path14) => !this.ignores(path14);
14366
+ return (path16) => !this.ignores(path16);
13826
14367
  }
13827
14368
  filter(paths) {
13828
14369
  return makeArray(paths).filter(this.createFilter());
13829
14370
  }
13830
- test(path14) {
13831
- return this._test(path14, this._testCache, true);
14371
+ test(path16) {
14372
+ return this._test(path16, this._testCache, true);
13832
14373
  }
13833
14374
  }
13834
14375
  var factory = (options) => new Ignore2(options);
13835
- var isPathValid = (path14) => checkPath(path14 && checkPath.convert(path14), path14, RETURN_FALSE);
14376
+ var isPathValid = (path16) => checkPath(path16 && checkPath.convert(path16), path16, RETURN_FALSE);
13836
14377
  factory.isPathValid = isPathValid;
13837
14378
  factory.default = factory;
13838
14379
  module.exports = factory;
@@ -13840,7 +14381,7 @@ var require_ignore = __commonJS((exports, module) => {
13840
14381
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
13841
14382
  checkPath.convert = makePosix;
13842
14383
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
13843
- checkPath.isNotRelative = (path14) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path14) || isNotRelative(path14);
14384
+ checkPath.isNotRelative = (path16) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path16) || isNotRelative(path16);
13844
14385
  }
13845
14386
  });
13846
14387
 
@@ -13892,7 +14433,7 @@ function validatePolicy(policy, opts = {}) {
13892
14433
  if (!Array.isArray(p.rules))
13893
14434
  throw new TypeError("policy.rules must be an array");
13894
14435
  const dropCount = p.rules.filter((r2) => r2?.disposition === "Drop").length;
13895
- const maxIgnore = typeof p.maxIgnorePatterns === "number" ? p.maxIgnorePatterns : MAX_IGNORE_PATTERNS2;
14436
+ const maxIgnore = typeof p.maxIgnorePatterns === "number" ? p.maxIgnorePatterns : MAX_IGNORE_PATTERNS;
13896
14437
  if (dropCount > maxIgnore) {
13897
14438
  throw new TypeError(`policy: ${dropCount} Drop rules exceed maxIgnorePatterns=${maxIgnore}`);
13898
14439
  }
@@ -13902,15 +14443,15 @@ function validatePolicy(policy, opts = {}) {
13902
14443
  }
13903
14444
  }
13904
14445
  }
13905
- function matchesGlob2(path14, pattern) {
14446
+ function matchesGlob2(path16, pattern) {
13906
14447
  let re = regexCache.get(pattern);
13907
14448
  if (!re) {
13908
14449
  re = globToRegex(pattern);
13909
14450
  regexCache.set(pattern, re);
13910
14451
  }
13911
- return re.test(path14);
14452
+ return re.test(path16);
13912
14453
  }
13913
- var MAX_MATCH_WORK = 1e5, MAX_IGNORE_PATTERNS2 = 1024, DEFAULT_POLICY, applyPolicy = (filePath, policy) => {
14454
+ var DEFAULT_POLICY, applyPolicy = (filePath, policy) => {
13914
14455
  const normalized = filePath.trim();
13915
14456
  for (const rule of policy.rules) {
13916
14457
  if (matchesGlob2(normalized, rule.pattern))
@@ -13919,48 +14460,14 @@ var MAX_MATCH_WORK = 1e5, MAX_IGNORE_PATTERNS2 = 1024, DEFAULT_POLICY, applyPoli
13919
14460
  return "Keep";
13920
14461
  }, regexCache;
13921
14462
  var init_capture_policy = __esm(() => {
13922
- DEFAULT_POLICY = {
13923
- rules: [
13924
- { pattern: "**/node_modules/**", disposition: "Drop" },
13925
- { pattern: "**/.git/**", disposition: "Drop" },
13926
- { pattern: "**/dist/**", disposition: "Drop" },
13927
- { pattern: "**/build/**", disposition: "Drop" },
13928
- { pattern: "**/coverage/**", disposition: "Drop" },
13929
- { pattern: ".env", disposition: "Drop" },
13930
- { pattern: ".env.*", disposition: "Drop" },
13931
- { pattern: "**/generated/**", disposition: "Drop" },
13932
- { pattern: "**/*.generated.*", disposition: "Drop" },
13933
- { pattern: "**/*.d.ts", disposition: "Drop" },
13934
- { pattern: "**/__tests__/**", disposition: "Drop" },
13935
- { pattern: "**/tests/**", disposition: "Drop" },
13936
- { pattern: "**/*.test.ts", disposition: "Drop" },
13937
- { pattern: "**/*.test.tsx", disposition: "Drop" },
13938
- { pattern: "**/*.test.js", disposition: "Drop" },
13939
- { pattern: "**/*.test.jsx", disposition: "Drop" },
13940
- { pattern: "**/*.spec.ts", disposition: "Drop" },
13941
- { pattern: "**/*.spec.tsx", disposition: "Drop" },
13942
- { pattern: "**/*.spec.js", disposition: "Drop" },
13943
- { pattern: "**/*.spec.jsx", disposition: "Drop" },
13944
- { pattern: "**/benchmarks/**", disposition: "Drop" },
13945
- { pattern: "**/fixtures/**", disposition: "Drop" },
13946
- { pattern: "**/*.wasm*", disposition: "Drop" },
13947
- { pattern: "**/*.min.*", disposition: "Drop" },
13948
- { pattern: "**/*.map", disposition: "Drop" },
13949
- { pattern: "**/lock.yaml", disposition: "Drop" },
13950
- { pattern: "**/pnpm-lock.yaml", disposition: "Drop" },
13951
- { pattern: "**/package-lock.json", disposition: "Drop" },
13952
- { pattern: "**/bun.lockb", disposition: "Drop" },
13953
- { pattern: "**/yarn.lock", disposition: "Drop" }
13954
- ],
13955
- maxMatchWork: MAX_MATCH_WORK,
13956
- maxIgnorePatterns: MAX_IGNORE_PATTERNS2
13957
- };
14463
+ init_dist();
14464
+ DEFAULT_POLICY = DEFAULT_CAPTURE_POLICY;
13958
14465
  regexCache = new Map;
13959
14466
  });
13960
14467
 
13961
14468
  // ../../packages/core/dist/services/search/ignore-patterns.js
13962
- import fs10 from "fs/promises";
13963
- import path14 from "path";
14469
+ import fs11 from "fs/promises";
14470
+ import path16 from "path";
13964
14471
  function buildExtensionGlob(extensions2) {
13965
14472
  return extensions2.map((ext2) => `**/*${ext2}`);
13966
14473
  }
@@ -13983,8 +14490,8 @@ async function loadProjectIgnore(projectPath) {
13983
14490
  const ig = ignore();
13984
14491
  ig.add(DEFAULT_IGNORES);
13985
14492
  try {
13986
- const gitignorePath = path14.join(projectPath, ".gitignore");
13987
- const gitignoreContent = await fs10.readFile(gitignorePath, "utf8");
14493
+ const gitignorePath = path16.join(projectPath, ".gitignore");
14494
+ const gitignoreContent = await fs11.readFile(gitignorePath, "utf8");
13988
14495
  const rules = gitignoreContent.split(`
13989
14496
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
13990
14497
  ig.add(rules);
@@ -14235,8 +14742,8 @@ var init_alias_resolver = __esm(() => {
14235
14742
  });
14236
14743
 
14237
14744
  // ../../packages/core/dist/services/search/index-manager.js
14238
- import fs11 from "fs";
14239
- import path15 from "path";
14745
+ import fs12 from "fs";
14746
+ import path17 from "path";
14240
14747
 
14241
14748
  class IndexManager {
14242
14749
  metadataCache = new Map;
@@ -14329,9 +14836,9 @@ class IndexManager {
14329
14836
  const fileMetadata = {};
14330
14837
  let totalSize = 0;
14331
14838
  for (const filePath of indexedFiles) {
14332
- const fullPath = path15.join(projectPath, filePath);
14839
+ const fullPath = path17.join(projectPath, filePath);
14333
14840
  try {
14334
- const stat2 = await fs11.promises.stat(fullPath);
14841
+ const stat2 = await fs12.promises.stat(fullPath);
14335
14842
  fileMetadata[filePath] = {
14336
14843
  path: filePath,
14337
14844
  mtime: stat2.mtimeMs,
@@ -14382,9 +14889,9 @@ class IndexManager {
14382
14889
  if (ig.ignores(match2)) {
14383
14890
  continue;
14384
14891
  }
14385
- const fullPath = path15.join(projectPath, match2);
14892
+ const fullPath = path17.join(projectPath, match2);
14386
14893
  try {
14387
- const stat2 = await fs11.promises.stat(fullPath);
14894
+ const stat2 = await fs12.promises.stat(fullPath);
14388
14895
  files.set(match2, {
14389
14896
  path: match2,
14390
14897
  mtime: stat2.mtimeMs,
@@ -14835,10 +15342,10 @@ function mergeDefs(...defs) {
14835
15342
  function cloneDef(schema) {
14836
15343
  return mergeDefs(schema._zod.def);
14837
15344
  }
14838
- function getElementAtPath(obj, path16) {
14839
- if (!path16)
15345
+ function getElementAtPath(obj, path18) {
15346
+ if (!path18)
14840
15347
  return obj;
14841
- return path16.reduce((acc, key) => acc?.[key], obj);
15348
+ return path18.reduce((acc, key) => acc?.[key], obj);
14842
15349
  }
14843
15350
  function promiseAllObject(promisesObj) {
14844
15351
  const keys = Object.keys(promisesObj);
@@ -15166,11 +15673,11 @@ function explicitlyAborted(x, startIndex = 0) {
15166
15673
  }
15167
15674
  return false;
15168
15675
  }
15169
- function prefixIssues(path16, issues) {
15676
+ function prefixIssues(path18, issues) {
15170
15677
  return issues.map((iss) => {
15171
15678
  var _a4;
15172
15679
  (_a4 = iss).path ?? (_a4.path = []);
15173
- iss.path.unshift(path16);
15680
+ iss.path.unshift(path18);
15174
15681
  return iss;
15175
15682
  });
15176
15683
  }
@@ -15383,16 +15890,16 @@ function flattenError(error, mapper = (issue2) => issue2.message) {
15383
15890
  }
15384
15891
  function formatError(error, mapper = (issue2) => issue2.message) {
15385
15892
  const fieldErrors = { _errors: [] };
15386
- const processError = (error2, path16 = []) => {
15893
+ const processError = (error2, path18 = []) => {
15387
15894
  for (const issue2 of error2.issues) {
15388
15895
  if (issue2.code === "invalid_union" && issue2.errors.length) {
15389
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
15896
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
15390
15897
  } else if (issue2.code === "invalid_key") {
15391
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15898
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15392
15899
  } else if (issue2.code === "invalid_element") {
15393
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15900
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15394
15901
  } else {
15395
- const fullpath = [...path16, ...issue2.path];
15902
+ const fullpath = [...path18, ...issue2.path];
15396
15903
  if (fullpath.length === 0) {
15397
15904
  fieldErrors._errors.push(mapper(issue2));
15398
15905
  } else {
@@ -15419,17 +15926,17 @@ function formatError(error, mapper = (issue2) => issue2.message) {
15419
15926
  }
15420
15927
  function treeifyError(error, mapper = (issue2) => issue2.message) {
15421
15928
  const result = { errors: [] };
15422
- const processError = (error2, path16 = []) => {
15929
+ const processError = (error2, path18 = []) => {
15423
15930
  var _a4, _b;
15424
15931
  for (const issue2 of error2.issues) {
15425
15932
  if (issue2.code === "invalid_union" && issue2.errors.length) {
15426
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
15933
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
15427
15934
  } else if (issue2.code === "invalid_key") {
15428
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15935
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15429
15936
  } else if (issue2.code === "invalid_element") {
15430
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15937
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15431
15938
  } else {
15432
- const fullpath = [...path16, ...issue2.path];
15939
+ const fullpath = [...path18, ...issue2.path];
15433
15940
  if (fullpath.length === 0) {
15434
15941
  result.errors.push(mapper(issue2));
15435
15942
  continue;
@@ -15461,8 +15968,8 @@ function treeifyError(error, mapper = (issue2) => issue2.message) {
15461
15968
  }
15462
15969
  function toDotPath(_path) {
15463
15970
  const segs = [];
15464
- const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
15465
- for (const seg of path16) {
15971
+ const path18 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
15972
+ for (const seg of path18) {
15466
15973
  if (typeof seg === "number")
15467
15974
  segs.push(`[${seg}]`);
15468
15975
  else if (typeof seg === "symbol")
@@ -28465,13 +28972,13 @@ function resolveRef(ref, ctx) {
28465
28972
  if (!ref.startsWith("#")) {
28466
28973
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
28467
28974
  }
28468
- const path16 = ref.slice(1).split("/").filter(Boolean);
28469
- if (path16.length === 0) {
28975
+ const path18 = ref.slice(1).split("/").filter(Boolean);
28976
+ if (path18.length === 0) {
28470
28977
  return ctx.rootSchema;
28471
28978
  }
28472
28979
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
28473
- if (path16[0] === defsKey) {
28474
- const key = path16[1];
28980
+ if (path18[0] === defsKey) {
28981
+ const key = path18[1];
28475
28982
  if (!key || !ctx.defs[key]) {
28476
28983
  throw new Error(`Reference not found: ${ref}`);
28477
28984
  }
@@ -29960,8 +30467,8 @@ class ParseStatus2 {
29960
30467
  }
29961
30468
  }
29962
30469
  var makeIssue2 = (params) => {
29963
- const { data, path: path16, errorMaps, issueData } = params;
29964
- const fullPath = [...path16, ...issueData.path || []];
30470
+ const { data, path: path18, errorMaps, issueData } = params;
30471
+ const fullPath = [...path18, ...issueData.path || []];
29965
30472
  const fullIssue = {
29966
30473
  ...issueData,
29967
30474
  path: fullPath
@@ -30006,11 +30513,11 @@ var init_errorUtil = __esm(() => {
30006
30513
 
30007
30514
  // ../../node_modules/zod/v3/types.js
30008
30515
  class ParseInputLazyPath2 {
30009
- constructor(parent, value, path16, key) {
30516
+ constructor(parent, value, path18, key) {
30010
30517
  this._cachedPath = [];
30011
30518
  this.parent = parent;
30012
30519
  this.data = value;
30013
- this._path = path16;
30520
+ this._path = path18;
30014
30521
  this._key = key;
30015
30522
  }
30016
30523
  get path() {
@@ -36007,19 +36514,19 @@ var require_token_io = __commonJS((exports, module) => {
36007
36514
  getUserDataDir: () => getUserDataDir
36008
36515
  });
36009
36516
  module.exports = __toCommonJS2(token_io_exports);
36010
- var import_path10 = __toESM2(__require("path"));
36011
- var import_fs7 = __toESM2(__require("fs"));
36517
+ var import_path11 = __toESM2(__require("path"));
36518
+ var import_fs8 = __toESM2(__require("fs"));
36012
36519
  var import_os3 = __toESM2(__require("os"));
36013
36520
  var import_token_error = require_token_error();
36014
36521
  function findRootDir() {
36015
36522
  try {
36016
36523
  let dir = process.cwd();
36017
- while (dir !== import_path10.default.dirname(dir)) {
36018
- const pkgPath = import_path10.default.join(dir, ".vercel");
36019
- if (import_fs7.default.existsSync(pkgPath)) {
36524
+ while (dir !== import_path11.default.dirname(dir)) {
36525
+ const pkgPath = import_path11.default.join(dir, ".vercel");
36526
+ if (import_fs8.default.existsSync(pkgPath)) {
36020
36527
  return dir;
36021
36528
  }
36022
- dir = import_path10.default.dirname(dir);
36529
+ dir = import_path11.default.dirname(dir);
36023
36530
  }
36024
36531
  } catch (e) {
36025
36532
  throw new import_token_error.VercelOidcTokenError("Token refresh only supported in node server environments");
@@ -36032,9 +36539,9 @@ var require_token_io = __commonJS((exports, module) => {
36032
36539
  }
36033
36540
  switch (import_os3.default.platform()) {
36034
36541
  case "darwin":
36035
- return import_path10.default.join(import_os3.default.homedir(), "Library/Application Support");
36542
+ return import_path11.default.join(import_os3.default.homedir(), "Library/Application Support");
36036
36543
  case "linux":
36037
- return import_path10.default.join(import_os3.default.homedir(), ".local/share");
36544
+ return import_path11.default.join(import_os3.default.homedir(), ".local/share");
36038
36545
  case "win32":
36039
36546
  if (process.env.LOCALAPPDATA) {
36040
36547
  return process.env.LOCALAPPDATA;
@@ -36075,23 +36582,23 @@ var require_auth_config = __commonJS((exports, module) => {
36075
36582
  writeAuthConfig: () => writeAuthConfig
36076
36583
  });
36077
36584
  module.exports = __toCommonJS2(auth_config_exports);
36078
- var fs12 = __toESM2(__require("fs"));
36079
- var path16 = __toESM2(__require("path"));
36585
+ var fs13 = __toESM2(__require("fs"));
36586
+ var path18 = __toESM2(__require("path"));
36080
36587
  var import_token_util = require_token_util();
36081
36588
  function getAuthConfigPath() {
36082
36589
  const dataDir = (0, import_token_util.getVercelDataDir)();
36083
36590
  if (!dataDir) {
36084
36591
  throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);
36085
36592
  }
36086
- return path16.join(dataDir, "auth.json");
36593
+ return path18.join(dataDir, "auth.json");
36087
36594
  }
36088
36595
  function readAuthConfig() {
36089
36596
  try {
36090
36597
  const authPath = getAuthConfigPath();
36091
- if (!fs12.existsSync(authPath)) {
36598
+ if (!fs13.existsSync(authPath)) {
36092
36599
  return null;
36093
36600
  }
36094
- const content = fs12.readFileSync(authPath, "utf8");
36601
+ const content = fs13.readFileSync(authPath, "utf8");
36095
36602
  if (!content) {
36096
36603
  return null;
36097
36604
  }
@@ -36102,11 +36609,11 @@ var require_auth_config = __commonJS((exports, module) => {
36102
36609
  }
36103
36610
  function writeAuthConfig(config3) {
36104
36611
  const authPath = getAuthConfigPath();
36105
- const authDir = path16.dirname(authPath);
36106
- if (!fs12.existsSync(authDir)) {
36107
- fs12.mkdirSync(authDir, { mode: 504, recursive: true });
36612
+ const authDir = path18.dirname(authPath);
36613
+ if (!fs13.existsSync(authDir)) {
36614
+ fs13.mkdirSync(authDir, { mode: 504, recursive: true });
36108
36615
  }
36109
- fs12.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
36616
+ fs13.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
36110
36617
  }
36111
36618
  function isValidAccessToken(authConfig, expirationBufferMs = 0) {
36112
36619
  if (!authConfig.token)
@@ -36281,8 +36788,8 @@ var require_token_util = __commonJS((exports, module) => {
36281
36788
  saveToken: () => saveToken
36282
36789
  });
36283
36790
  module.exports = __toCommonJS2(token_util_exports);
36284
- var path16 = __toESM2(__require("path"));
36285
- var fs12 = __toESM2(__require("fs"));
36791
+ var path18 = __toESM2(__require("path"));
36792
+ var fs13 = __toESM2(__require("fs"));
36286
36793
  var import_token_error = require_token_error();
36287
36794
  var import_token_io = require_token_io();
36288
36795
  var import_auth_config = require_auth_config();
@@ -36294,7 +36801,7 @@ var require_token_util = __commonJS((exports, module) => {
36294
36801
  if (!dataDir) {
36295
36802
  return null;
36296
36803
  }
36297
- return path16.join(dataDir, vercelFolder);
36804
+ return path18.join(dataDir, vercelFolder);
36298
36805
  }
36299
36806
  async function getVercelToken2(options) {
36300
36807
  const authConfig = (0, import_auth_config.readAuthConfig)();
@@ -36362,11 +36869,11 @@ var require_token_util = __commonJS((exports, module) => {
36362
36869
  if (!dir) {
36363
36870
  throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");
36364
36871
  }
36365
- const prjPath = path16.join(dir, ".vercel", "project.json");
36366
- if (!fs12.existsSync(prjPath)) {
36872
+ const prjPath = path18.join(dir, ".vercel", "project.json");
36873
+ if (!fs13.existsSync(prjPath)) {
36367
36874
  throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");
36368
36875
  }
36369
- const prj = JSON.parse(fs12.readFileSync(prjPath, "utf8"));
36876
+ const prj = JSON.parse(fs13.readFileSync(prjPath, "utf8"));
36370
36877
  if (typeof prj.projectId !== "string" && typeof prj.orgId !== "string") {
36371
36878
  throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");
36372
36879
  }
@@ -36377,11 +36884,11 @@ var require_token_util = __commonJS((exports, module) => {
36377
36884
  if (!dir) {
36378
36885
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
36379
36886
  }
36380
- const tokenPath = path16.join(dir, "com.vercel.token", `${projectId}.json`);
36887
+ const tokenPath = path18.join(dir, "com.vercel.token", `${projectId}.json`);
36381
36888
  const tokenJson = JSON.stringify(token);
36382
- fs12.mkdirSync(path16.dirname(tokenPath), { mode: 504, recursive: true });
36383
- fs12.writeFileSync(tokenPath, tokenJson);
36384
- fs12.chmodSync(tokenPath, 432);
36889
+ fs13.mkdirSync(path18.dirname(tokenPath), { mode: 504, recursive: true });
36890
+ fs13.writeFileSync(tokenPath, tokenJson);
36891
+ fs13.chmodSync(tokenPath, 432);
36385
36892
  return;
36386
36893
  }
36387
36894
  function loadToken(projectId) {
@@ -36389,11 +36896,11 @@ var require_token_util = __commonJS((exports, module) => {
36389
36896
  if (!dir) {
36390
36897
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
36391
36898
  }
36392
- const tokenPath = path16.join(dir, "com.vercel.token", `${projectId}.json`);
36393
- if (!fs12.existsSync(tokenPath)) {
36899
+ const tokenPath = path18.join(dir, "com.vercel.token", `${projectId}.json`);
36900
+ if (!fs13.existsSync(tokenPath)) {
36394
36901
  return null;
36395
36902
  }
36396
- const token = JSON.parse(fs12.readFileSync(tokenPath, "utf8"));
36903
+ const token = JSON.parse(fs13.readFileSync(tokenPath, "utf8"));
36397
36904
  assertVercelOidcTokenResponse(token);
36398
36905
  return token;
36399
36906
  }
@@ -47235,37 +47742,37 @@ function createOpenAI(options = {}) {
47235
47742
  }, `ai-sdk/openai/${VERSION4}`);
47236
47743
  const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
47237
47744
  provider: `${providerName}.chat`,
47238
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47745
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47239
47746
  headers: getHeaders,
47240
47747
  fetch: options.fetch
47241
47748
  });
47242
47749
  const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
47243
47750
  provider: `${providerName}.completion`,
47244
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47751
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47245
47752
  headers: getHeaders,
47246
47753
  fetch: options.fetch
47247
47754
  });
47248
47755
  const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
47249
47756
  provider: `${providerName}.embedding`,
47250
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47757
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47251
47758
  headers: getHeaders,
47252
47759
  fetch: options.fetch
47253
47760
  });
47254
47761
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
47255
47762
  provider: `${providerName}.image`,
47256
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47763
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47257
47764
  headers: getHeaders,
47258
47765
  fetch: options.fetch
47259
47766
  });
47260
47767
  const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
47261
47768
  provider: `${providerName}.transcription`,
47262
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47769
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47263
47770
  headers: getHeaders,
47264
47771
  fetch: options.fetch
47265
47772
  });
47266
47773
  const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
47267
47774
  provider: `${providerName}.speech`,
47268
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47775
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47269
47776
  headers: getHeaders,
47270
47777
  fetch: options.fetch
47271
47778
  });
@@ -47278,7 +47785,7 @@ function createOpenAI(options = {}) {
47278
47785
  const createResponsesModel = (modelId) => {
47279
47786
  return new OpenAIResponsesLanguageModel(modelId, {
47280
47787
  provider: `${providerName}.responses`,
47281
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47788
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47282
47789
  headers: getHeaders,
47283
47790
  fetch: options.fetch,
47284
47791
  fileIdPrefixes: ["file-"]
@@ -63823,26 +64330,26 @@ var require_process = __commonJS((exports, module) => {
63823
64330
 
63824
64331
  // ../../node_modules/detect-libc/lib/filesystem.js
63825
64332
  var require_filesystem = __commonJS((exports, module) => {
63826
- var fs12 = __require("fs");
64333
+ var fs13 = __require("fs");
63827
64334
  var LDD_PATH = "/usr/bin/ldd";
63828
64335
  var SELF_PATH = "/proc/self/exe";
63829
64336
  var MAX_LENGTH = 2048;
63830
- var readFileSync2 = (path16) => {
63831
- const fd = fs12.openSync(path16, "r");
64337
+ var readFileSync2 = (path18) => {
64338
+ const fd = fs13.openSync(path18, "r");
63832
64339
  const buffer = Buffer.alloc(MAX_LENGTH);
63833
- const bytesRead = fs12.readSync(fd, buffer, 0, MAX_LENGTH, 0);
63834
- fs12.close(fd, () => {});
64340
+ const bytesRead = fs13.readSync(fd, buffer, 0, MAX_LENGTH, 0);
64341
+ fs13.close(fd, () => {});
63835
64342
  return buffer.subarray(0, bytesRead);
63836
64343
  };
63837
- var readFile = (path16) => new Promise((resolve4, reject) => {
63838
- fs12.open(path16, "r", (err, fd) => {
64344
+ var readFile = (path18) => new Promise((resolve4, reject) => {
64345
+ fs13.open(path18, "r", (err, fd) => {
63839
64346
  if (err) {
63840
64347
  reject(err);
63841
64348
  } else {
63842
64349
  const buffer = Buffer.alloc(MAX_LENGTH);
63843
- fs12.read(fd, buffer, 0, MAX_LENGTH, 0, (_2, bytesRead) => {
64350
+ fs13.read(fd, buffer, 0, MAX_LENGTH, 0, (_2, bytesRead) => {
63844
64351
  resolve4(buffer.subarray(0, bytesRead));
63845
- fs12.close(fd, () => {});
64352
+ fs13.close(fd, () => {});
63846
64353
  });
63847
64354
  }
63848
64355
  });
@@ -63947,11 +64454,11 @@ var require_detect_libc = __commonJS((exports, module) => {
63947
64454
  }
63948
64455
  return null;
63949
64456
  };
63950
- var familyFromInterpreterPath = (path16) => {
63951
- if (path16) {
63952
- if (path16.includes("/ld-musl-")) {
64457
+ var familyFromInterpreterPath = (path18) => {
64458
+ if (path18) {
64459
+ if (path18.includes("/ld-musl-")) {
63953
64460
  return MUSL;
63954
- } else if (path16.includes("/ld-linux-")) {
64461
+ } else if (path18.includes("/ld-linux-")) {
63955
64462
  return GLIBC;
63956
64463
  }
63957
64464
  }
@@ -63996,8 +64503,8 @@ var require_detect_libc = __commonJS((exports, module) => {
63996
64503
  cachedFamilyInterpreter = null;
63997
64504
  try {
63998
64505
  const selfContent = await readFile(SELF_PATH);
63999
- const path16 = interpreterPath(selfContent);
64000
- cachedFamilyInterpreter = familyFromInterpreterPath(path16);
64506
+ const path18 = interpreterPath(selfContent);
64507
+ cachedFamilyInterpreter = familyFromInterpreterPath(path18);
64001
64508
  } catch (e) {}
64002
64509
  return cachedFamilyInterpreter;
64003
64510
  };
@@ -64008,8 +64515,8 @@ var require_detect_libc = __commonJS((exports, module) => {
64008
64515
  cachedFamilyInterpreter = null;
64009
64516
  try {
64010
64517
  const selfContent = readFileSync2(SELF_PATH);
64011
- const path16 = interpreterPath(selfContent);
64012
- cachedFamilyInterpreter = familyFromInterpreterPath(path16);
64518
+ const path18 = interpreterPath(selfContent);
64519
+ cachedFamilyInterpreter = familyFromInterpreterPath(path18);
64013
64520
  } catch (e) {}
64014
64521
  return cachedFamilyInterpreter;
64015
64522
  };
@@ -65671,18 +66178,18 @@ var require_sharp = __commonJS((exports, module) => {
65671
66178
  `@img/sharp-${runtimePlatform}/sharp.node`,
65672
66179
  "@img/sharp-wasm32/sharp.node"
65673
66180
  ];
65674
- var path16;
66181
+ var path18;
65675
66182
  var sharp;
65676
66183
  var errors5 = [];
65677
- for (path16 of paths) {
66184
+ for (path18 of paths) {
65678
66185
  try {
65679
- sharp = __require(path16);
66186
+ sharp = __require(path18);
65680
66187
  break;
65681
66188
  } catch (err) {
65682
66189
  errors5.push(err);
65683
66190
  }
65684
66191
  }
65685
- if (sharp && path16.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
66192
+ if (sharp && path18.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
65686
66193
  const err = new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");
65687
66194
  err.code = "Unsupported CPU";
65688
66195
  errors5.push(err);
@@ -65691,7 +66198,7 @@ var require_sharp = __commonJS((exports, module) => {
65691
66198
  if (sharp) {
65692
66199
  module.exports = sharp;
65693
66200
  } else {
65694
- const [isLinux, isMacOs, isWindows] = ["linux", "darwin", "win32"].map((os6) => runtimePlatform.startsWith(os6));
66201
+ const [isLinux, isMacOs, isWindows] = ["linux", "darwin", "win32"].map((os8) => runtimePlatform.startsWith(os8));
65695
66202
  const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`];
65696
66203
  errors5.forEach((err) => {
65697
66204
  if (err.code !== "MODULE_NOT_FOUND") {
@@ -65704,9 +66211,9 @@ var require_sharp = __commonJS((exports, module) => {
65704
66211
  const { found, expected } = isUnsupportedNodeRuntime();
65705
66212
  help.push("- Please upgrade Node.js:", ` Found ${found}`, ` Requires ${expected}`);
65706
66213
  } else if (prebuiltPlatforms.includes(runtimePlatform)) {
65707
- const [os6, cpu] = runtimePlatform.split("-");
65708
- const libc = os6.endsWith("musl") ? " --libc=musl" : "";
65709
- help.push("- Ensure optional dependencies can be installed:", " npm install --include=optional sharp", "- Ensure your package manager supports multi-platform installation:", " See https://sharp.pixelplumbing.com/install#cross-platform", "- Add platform-specific dependencies:", ` npm install --os=${os6.replace("musl", "")}${libc} --cpu=${cpu} sharp`);
66214
+ const [os8, cpu] = runtimePlatform.split("-");
66215
+ const libc = os8.endsWith("musl") ? " --libc=musl" : "";
66216
+ help.push("- Ensure optional dependencies can be installed:", " npm install --include=optional sharp", "- Ensure your package manager supports multi-platform installation:", " See https://sharp.pixelplumbing.com/install#cross-platform", "- Add platform-specific dependencies:", ` npm install --os=${os8.replace("musl", "")}${libc} --cpu=${cpu} sharp`);
65710
66217
  } else {
65711
66218
  help.push(`- Manually install libvips >= ${minimumLibvipsVersion}`, "- Add experimental WebAssembly-based dependencies:", " npm install --cpu=wasm32 sharp", " npm install @img/sharp-wasm32");
65712
66219
  }
@@ -66966,7 +67473,7 @@ var require_operation = __commonJS((exports, module) => {
66966
67473
  float: "float",
66967
67474
  approximate: "approximate"
66968
67475
  };
66969
- function rotate(angle, options) {
67476
+ function rotate2(angle, options) {
66970
67477
  if (!is.defined(angle)) {
66971
67478
  return this.autoOrient();
66972
67479
  }
@@ -67393,7 +67900,7 @@ var require_operation = __commonJS((exports, module) => {
67393
67900
  module.exports = (Sharp) => {
67394
67901
  Object.assign(Sharp.prototype, {
67395
67902
  autoOrient,
67396
- rotate,
67903
+ rotate: rotate2,
67397
67904
  flip,
67398
67905
  flop,
67399
67906
  affine,
@@ -68544,15 +69051,15 @@ var require_color = __commonJS((exports, module) => {
68544
69051
  };
68545
69052
  }
68546
69053
  function wrapConversion(toModel, graph) {
68547
- const path16 = [graph[toModel].parent, toModel];
69054
+ const path18 = [graph[toModel].parent, toModel];
68548
69055
  let fn = conversions_default[graph[toModel].parent][toModel];
68549
69056
  let cur = graph[toModel].parent;
68550
69057
  while (graph[cur].parent) {
68551
- path16.unshift(graph[cur].parent);
69058
+ path18.unshift(graph[cur].parent);
68552
69059
  fn = link(conversions_default[graph[cur].parent][cur], fn);
68553
69060
  cur = graph[cur].parent;
68554
69061
  }
68555
- fn.conversion = path16;
69062
+ fn.conversion = path18;
68556
69063
  return fn;
68557
69064
  }
68558
69065
  function route(fromModel) {
@@ -69157,7 +69664,7 @@ var require_output = __commonJS((exports, module) => {
69157
69664
  Copyright 2013 Lovell Fuller and others.
69158
69665
  SPDX-License-Identifier: Apache-2.0
69159
69666
  */
69160
- var path16 = __require("path");
69667
+ var path18 = __require("path");
69161
69668
  var is = require_is();
69162
69669
  var sharp = require_sharp();
69163
69670
  var formats = new Map([
@@ -69188,9 +69695,9 @@ var require_output = __commonJS((exports, module) => {
69188
69695
  let err;
69189
69696
  if (!is.string(fileOut)) {
69190
69697
  err = new Error("Missing output file path");
69191
- } else if (is.string(this.options.input.file) && path16.resolve(this.options.input.file) === path16.resolve(fileOut)) {
69698
+ } else if (is.string(this.options.input.file) && path18.resolve(this.options.input.file) === path18.resolve(fileOut)) {
69192
69699
  err = new Error("Cannot use same file for input and output");
69193
- } else if (jp2Regex.test(path16.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
69700
+ } else if (jp2Regex.test(path18.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
69194
69701
  err = errJp2Save();
69195
69702
  }
69196
69703
  if (err) {
@@ -76437,11 +76944,11 @@ var init_transformers_node = __esm(() => {
76437
76944
  throw new Error(`The number of external data chunks (${num_chunks}) exceeds the maximum allowed value (${_utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.MAX_EXTERNAL_DATA_CHUNKS}).`);
76438
76945
  }
76439
76946
  for (let i = 0;i < num_chunks; ++i) {
76440
- const path16 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
76441
- const fullPath = `${options.subfolder ?? ""}/${path16}`;
76947
+ const path18 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
76948
+ const fullPath = `${options.subfolder ?? ""}/${path18}`;
76442
76949
  externalDataPromises.push(new Promise(async (resolve4, reject) => {
76443
76950
  const data = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, fullPath, true, options, return_path);
76444
- resolve4(data instanceof Uint8Array ? { path: path16, data } : path16);
76951
+ resolve4(data instanceof Uint8Array ? { path: path18, data } : path18);
76445
76952
  }));
76446
76953
  }
76447
76954
  } else if (session_options.externalData !== undefined) {
@@ -89505,7 +90012,7 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
89505
90012
  const blob = new Blob([wav], { type: "audio/wav" });
89506
90013
  return blob;
89507
90014
  }
89508
- async save(path16) {
90015
+ async save(path18) {
89509
90016
  let fn;
89510
90017
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_BROWSER_ENV) {
89511
90018
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_WEBWORKER_ENV) {
@@ -89513,14 +90020,14 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
89513
90020
  }
89514
90021
  fn = _core_js__WEBPACK_IMPORTED_MODULE_2__.saveBlob;
89515
90022
  } else if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_FS_AVAILABLE) {
89516
- fn = async (path17, blob) => {
90023
+ fn = async (path19, blob) => {
89517
90024
  let buffer = await blob.arrayBuffer();
89518
- node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path17, Buffer.from(buffer));
90025
+ node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path19, Buffer.from(buffer));
89519
90026
  };
89520
90027
  } else {
89521
90028
  throw new Error("Unable to save because filesystem is disabled in this environment.");
89522
90029
  }
89523
- await fn(path16, this.toBlob());
90030
+ await fn(path18, this.toBlob());
89524
90031
  }
89525
90032
  }
89526
90033
  },
@@ -89616,11 +90123,11 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
89616
90123
  function calculateReflectOffset(i, w) {
89617
90124
  return Math.abs((i + w) % (2 * w) - w);
89618
90125
  }
89619
- function saveBlob(path16, blob) {
90126
+ function saveBlob(path18, blob) {
89620
90127
  const dataURL = URL.createObjectURL(blob);
89621
90128
  const downloadLink = document.createElement("a");
89622
90129
  downloadLink.href = dataURL;
89623
- downloadLink.download = path16;
90130
+ downloadLink.download = path18;
89624
90131
  downloadLink.click();
89625
90132
  downloadLink.remove();
89626
90133
  URL.revokeObjectURL(dataURL);
@@ -90221,8 +90728,8 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
90221
90728
  }
90222
90729
 
90223
90730
  class FileCache {
90224
- constructor(path16) {
90225
- this.path = path16;
90731
+ constructor(path18) {
90732
+ this.path = path18;
90226
90733
  }
90227
90734
  async match(request) {
90228
90735
  let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].join(this.path, request);
@@ -90978,20 +91485,20 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
90978
91485
  }
90979
91486
  return this;
90980
91487
  }
90981
- async save(path16) {
91488
+ async save(path18) {
90982
91489
  if (IS_BROWSER_OR_WEBWORKER) {
90983
91490
  if (_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV) {
90984
91491
  throw new Error("Unable to save an image from a Web Worker.");
90985
91492
  }
90986
- const extension = path16.split(".").pop().toLowerCase();
91493
+ const extension = path18.split(".").pop().toLowerCase();
90987
91494
  const mime2 = CONTENT_TYPE_MAP.get(extension) ?? "image/png";
90988
91495
  const blob = await this.toBlob(mime2);
90989
- (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path16, blob);
91496
+ (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path18, blob);
90990
91497
  } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) {
90991
91498
  throw new Error("Unable to save the image because filesystem is disabled in this environment.");
90992
91499
  } else {
90993
91500
  const img = this.toSharp();
90994
- return await img.toFile(path16);
91501
+ return await img.toFile(path18);
90995
91502
  }
90996
91503
  }
90997
91504
  toSharp() {
@@ -94518,20 +95025,20 @@ function getRetryDelay(attempt, config3) {
94518
95025
  return Math.min(delay2, config3.maxDelay);
94519
95026
  }
94520
95027
  async function withRetry(fn, config3, context2) {
94521
- let lastError;
95028
+ let lastError2;
94522
95029
  for (let attempt = 0;attempt <= config3.maxRetries; attempt++) {
94523
95030
  try {
94524
95031
  return await fn();
94525
95032
  } catch (error51) {
94526
- lastError = error51;
95033
+ lastError2 = error51;
94527
95034
  if (attempt < config3.maxRetries) {
94528
95035
  const delay2 = getRetryDelay(attempt, config3);
94529
- logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError.message });
95036
+ logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError2.message });
94530
95037
  await sleep(delay2);
94531
95038
  }
94532
95039
  }
94533
95040
  }
94534
- throw new Error(`${context2} failed after ${config3.maxRetries + 1} attempts: ${lastError?.message}`);
95041
+ throw new Error(`${context2} failed after ${config3.maxRetries + 1} attempts: ${lastError2?.message}`);
94535
95042
  }
94536
95043
  async function withTimeout(fn, timeoutMs, context2) {
94537
95044
  let timeoutId;
@@ -100217,7 +100724,7 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a12;
100217
100724
  function ns(e = Yo, t2 = Yo) {
100218
100725
  return (r2) => e(t2(r2));
100219
100726
  }
100220
- function os6({ dataPath: e, modelName: t2, args: r2, runtimeDataModel: n2 }) {
100727
+ function os8({ dataPath: e, modelName: t2, args: r2, runtimeDataModel: n2 }) {
100221
100728
  let i = { modelName: t2, args: r2 ?? {} }, o = dp(e);
100222
100729
  if (!o || o.length === 0)
100223
100730
  return i;
@@ -100522,10 +101029,10 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a12;
100522
101029
  super(t2, "P2023", r2);
100523
101030
  }
100524
101031
  };
100525
- var fs12 = new WeakMap;
101032
+ var fs13 = new WeakMap;
100526
101033
  function Ep(e) {
100527
- let t2 = fs12.get(e);
100528
- return t2 || (t2 = Object.entries(e), fs12.set(e, t2)), t2;
101034
+ let t2 = fs13.get(e);
101035
+ return t2 || (t2 = Object.entries(e), fs13.set(e, t2)), t2;
100529
101036
  }
100530
101037
  function hs(e, t2, r2) {
100531
101038
  switch (t2.type) {
@@ -104090,7 +104597,7 @@ new PrismaClient({
104090
104597
  let m2 = await es(this, d);
104091
104598
  if (!d.model)
104092
104599
  return m2;
104093
- let g = os6({ dataPath: d.dataPath, modelName: d.model, args: d.args, runtimeDataModel: this._runtimeDataModel });
104600
+ let g = os8({ dataPath: d.dataPath, modelName: d.model, args: d.args, runtimeDataModel: this._runtimeDataModel });
104094
104601
  return Wo({ result: m2, modelName: g.modelName, args: g.args, extensions: this._extensions, runtimeDataModel: this._runtimeDataModel, globalOmit: this._globalOmit });
104095
104602
  };
104096
104603
  return this._tracingHelper.runInChildSpan(s.operation, () => new zl.AsyncResource("prisma-client-request").runInAsyncScope(() => a12(o)));
@@ -104493,7 +105000,7 @@ var require_prisma = __commonJS((exports) => {
104493
105000
  Prisma.JsonNull = JsonNull2;
104494
105001
  Prisma.AnyNull = AnyNull2;
104495
105002
  Prisma.NullTypes = NullTypes2;
104496
- var path16 = __require("path");
105003
+ var path18 = __require("path");
104497
105004
  exports.Prisma.TransactionIsolationLevel = makeStrictEnum2({
104498
105005
  ReadUncommitted: "ReadUncommitted",
104499
105006
  ReadCommitted: "ReadCommitted",
@@ -106102,11 +106609,17 @@ var init_config2 = __esm(() => {
106102
106609
  ollama: (() => {
106103
106610
  const file3 = fileFor("ollama");
106104
106611
  const model = process.env.OLLAMA_EMBEDDING_MODEL || file3?.model || "qwen3-embedding:4b";
106612
+ const rawEnvDimensions = Number(process.env.OLLAMA_EMBEDDING_DIMENSIONS);
106613
+ const envDimensions = Number.isInteger(rawEnvDimensions) && rawEnvDimensions > 0 ? rawEnvDimensions : undefined;
106614
+ const resolvedDimensions = resolveEmbeddingDimensions(model, file3?.dimensions, envDimensions);
106615
+ if (resolvedDimensions.correctedFrom !== undefined) {
106616
+ logger.warn(`[ollama] config.json records embedding.dimensions ${resolvedDimensions.correctedFrom} for model ` + `"${model}", which emits ${resolvedDimensions.dimensions}. Using ${resolvedDimensions.dimensions}. ` + "Update embedding.dimensions in config.json (or set OLLAMA_EMBEDDING_DIMENSIONS) to silence this.");
106617
+ }
106105
106618
  return {
106106
106619
  provider: "ollama",
106107
106620
  model,
106108
106621
  baseURL: process.env.OLLAMA_BASE_URL || file3?.baseURL || "http://localhost:11434",
106109
- dimensions: process.env.OLLAMA_EMBEDDING_DIMENSIONS ? Number(process.env.OLLAMA_EMBEDDING_DIMENSIONS) : file3?.dimensions ?? 2560,
106622
+ dimensions: resolvedDimensions.dimensions,
106110
106623
  priority: selectedProvider === "ollama" ? 1 : 50,
106111
106624
  timeout: 300000,
106112
106625
  maxRetries: 2,
@@ -110641,7 +111154,7 @@ async function upsertWorkspace(ws) {
110641
111154
  }, { timeout: 60000, maxWait: 1e4 });
110642
111155
  }
110643
111156
  async function updateWorkspaceStatus(projectId, status2, opts) {
110644
- const lastError = typeof opts === "string" ? opts : opts?.lastError ?? null;
111157
+ const lastError2 = typeof opts === "string" ? opts : opts?.lastError ?? null;
110645
111158
  const filesCount = typeof opts === "object" ? opts?.filesCount : undefined;
110646
111159
  const chunksCount = typeof opts === "object" ? opts?.chunksCount : undefined;
110647
111160
  const symbolsCount = typeof opts === "object" ? opts?.symbolsCount : undefined;
@@ -110651,7 +111164,7 @@ async function updateWorkspaceStatus(projectId, status2, opts) {
110651
111164
  await tx.$executeRaw`
110652
111165
  UPDATE workspaces SET
110653
111166
  status = ${status2},
110654
- last_error = ${lastError},
111167
+ last_error = ${lastError2},
110655
111168
  last_indexed_at = ${lastIndexedAt ?? null},
110656
111169
  files_count = COALESCE(${filesCount ?? null}, files_count),
110657
111170
  chunks_count = COALESCE(${chunksCount ?? null}, chunks_count),
@@ -115995,10 +116508,10 @@ var init_chunker_code = __esm(() => {
115995
116508
  });
115996
116509
 
115997
116510
  // ../../packages/core/dist/services/search/smart-chunker.js
115998
- import path16 from "path";
116511
+ import path18 from "path";
115999
116512
  function smartChunk(content, filePath, config3 = {}) {
116000
116513
  const cfg = { ...DEFAULT_CONFIG, ...config3 };
116001
- const ext2 = path16.extname(filePath).toLowerCase();
116514
+ const ext2 = path18.extname(filePath).toLowerCase();
116002
116515
  const relativePath = filePath;
116003
116516
  const fileImports = isCodeFile(ext2) ? extractFileImports(content, ext2) : undefined;
116004
116517
  let chunks;
@@ -116305,8 +116818,8 @@ var init_managed_run_repository_pg = __esm(() => {
116305
116818
  });
116306
116819
 
116307
116820
  // ../../packages/core/dist/services/search/project-indexer.js
116308
- import fs12 from "fs/promises";
116309
- import path17 from "path";
116821
+ import fs13 from "fs/promises";
116822
+ import path19 from "path";
116310
116823
  import { randomUUID as randomUUID3 } from "crypto";
116311
116824
  async function runWithIndexLock(lockMap, projectId, work) {
116312
116825
  const prevLock = lockMap.get(projectId);
@@ -116349,7 +116862,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
116349
116862
  dot: false
116350
116863
  });
116351
116864
  const filteredFiles = files.filter((file3) => {
116352
- const relativePath = path17.relative(projectPath, file3);
116865
+ const relativePath = path19.relative(projectPath, file3);
116353
116866
  const shouldIgnore = ig.ignores(relativePath);
116354
116867
  if (shouldIgnore) {
116355
116868
  logger.debug("Ignoring file per .gitignore during indexing", {
@@ -116389,7 +116902,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
116389
116902
  });
116390
116903
  }
116391
116904
  }
116392
- const indexedFilesList = filteredFiles.map((f) => path17.relative(projectPath, f));
116905
+ const indexedFilesList = filteredFiles.map((f) => path19.relative(projectPath, f));
116393
116906
  await deps.indexManager.updateIndexMetadata(projectId, projectPath, indexedFilesList);
116394
116907
  logger.info("Project indexing completed", {
116395
116908
  projectId,
@@ -116514,7 +117027,7 @@ async function ensureFreshIndex(deps, projectId, projectPath, options = {}) {
116514
117027
  let errors5 = 0;
116515
117028
  for (const relativeFilePath of filesToReindex) {
116516
117029
  try {
116517
- const fullPath = path17.join(projectPath, relativeFilePath);
117030
+ const fullPath = path19.join(projectPath, relativeFilePath);
116518
117031
  const result = await deps.indexFile(fullPath, projectId, projectPath, centralityMap);
116519
117032
  filesIndexed++;
116520
117033
  chunksIndexed += result.chunks;
@@ -116565,8 +117078,8 @@ async function checkSearchAdmission(deps, projectId, projectPath) {
116565
117078
  }
116566
117079
  async function indexFile(deps, filePath, projectId, projectRoot, centralityMap) {
116567
117080
  projectId = await getProjectIdentityAliasResolver().resolve(projectId);
116568
- const content = await fs12.readFile(filePath, "utf-8");
116569
- const relativePath = path17.relative(projectRoot, filePath);
117081
+ const content = await fs13.readFile(filePath, "utf-8");
117082
+ const relativePath = path19.relative(projectRoot, filePath);
116570
117083
  const maxFileSize = config.get("security").maxFileSize || 1024 * 1024;
116571
117084
  if (content.length > maxFileSize) {
116572
117085
  logger.warn("File too large, skipping", {
@@ -116586,7 +117099,7 @@ async function indexFile(deps, filePath, projectId, projectRoot, centralityMap)
116586
117099
  chunkIndex: i,
116587
117100
  totalChunks: chunks.length,
116588
117101
  type: chunk.type,
116589
- language: path17.extname(filePath).slice(1),
117102
+ language: path19.extname(filePath).slice(1),
116590
117103
  lineStart: chunk.lineStart,
116591
117104
  lineEnd: chunk.lineEnd,
116592
117105
  label: chunk.label,
@@ -117431,8 +117944,8 @@ function stripNul(content) {
117431
117944
  }
117432
117945
 
117433
117946
  // ../../packages/core/dist/services/etl/stages/discover.js
117434
- import fs13 from "fs/promises";
117435
- import path18 from "path";
117947
+ import fs14 from "fs/promises";
117948
+ import path20 from "path";
117436
117949
  import { createHash as createHash5 } from "crypto";
117437
117950
 
117438
117951
  class DiscoverStage {
@@ -117458,7 +117971,7 @@ class DiscoverStage {
117458
117971
  dot: false,
117459
117972
  absolute: false
117460
117973
  });
117461
- relPaths = found.map((p) => path18.isAbsolute(p) ? path18.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
117974
+ relPaths = found.map((p) => path20.isAbsolute(p) ? path20.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
117462
117975
  }
117463
117976
  if (ctx.resumeCursor?.path) {
117464
117977
  const cursorPath = ctx.resumeCursor.path;
@@ -117517,10 +118030,10 @@ class DiscoverStage {
117517
118030
  return discovered;
117518
118031
  }
117519
118032
  async processFile(ctx, relativePath, forceReindex) {
117520
- const absolutePath = path18.join(ctx.projectPath, relativePath);
118033
+ const absolutePath = path20.join(ctx.projectPath, relativePath);
117521
118034
  try {
117522
- const stat2 = await fs13.stat(absolutePath);
117523
- const content = stripNul(await fs13.readFile(absolutePath, "utf-8"));
118035
+ const stat2 = await fs14.stat(absolutePath);
118036
+ const content = stripNul(await fs14.readFile(absolutePath, "utf-8"));
117524
118037
  const contentHash = createHash5("sha256").update(content).digest("hex");
117525
118038
  let needsReparse = forceReindex;
117526
118039
  if (!forceReindex) {
@@ -117563,8 +118076,8 @@ class DiscoverStage {
117563
118076
  ig.add(pattern);
117564
118077
  }
117565
118078
  try {
117566
- const gitignorePath = path18.join(projectPath, ".gitignore");
117567
- const gitignoreContent = await fs13.readFile(gitignorePath, "utf8");
118079
+ const gitignorePath = path20.join(projectPath, ".gitignore");
118080
+ const gitignoreContent = await fs14.readFile(gitignorePath, "utf8");
117568
118081
  const rules = gitignoreContent.split(`
117569
118082
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
117570
118083
  ig.add(rules);
@@ -118919,8 +119432,8 @@ function rustUseLeaves(node2, source, prefix = []) {
118919
119432
  }
118920
119433
  if (node2.type === "use_wildcard")
118921
119434
  return [{ path: [...prefix, "*"], glob: true }];
118922
- const path19 = rustPathSegments(node2, source);
118923
- return path19.length ? [{ path: [...prefix, ...path19] }] : [];
119435
+ const path21 = rustPathSegments(node2, source);
119436
+ return path21.length ? [{ path: [...prefix, ...path21] }] : [];
118924
119437
  }
118925
119438
  function functionalCaptures(captures, source, family) {
118926
119439
  if (family !== "clojure")
@@ -119892,8 +120405,8 @@ var init_structural_runtime = __esm(() => {
119892
120405
  });
119893
120406
 
119894
120407
  // ../../packages/core/dist/services/etl/stages/parse.js
119895
- import path19 from "path";
119896
- import fs14 from "fs/promises";
120408
+ import path21 from "path";
120409
+ import fs15 from "fs/promises";
119897
120410
  function resolveChunkerMaxChars() {
119898
120411
  const global2 = Number(process.env.EMBEDDING_MAX_CHARS);
119899
120412
  if (Number.isFinite(global2) && global2 > 0)
@@ -119921,8 +120434,8 @@ class ParseStage {
119921
120434
  const results = new Map;
119922
120435
  let processed = 0;
119923
120436
  const phases = [
119924
- files.filter((file3) => path19.extname(file3.relativePath).toLowerCase() !== ".h"),
119925
- files.filter((file3) => path19.extname(file3.relativePath).toLowerCase() === ".h")
120437
+ files.filter((file3) => path21.extname(file3.relativePath).toLowerCase() !== ".h"),
120438
+ files.filter((file3) => path21.extname(file3.relativePath).toLowerCase() === ".h")
119926
120439
  ];
119927
120440
  const batches = phases.flatMap((phase) => Array.from({ length: Math.ceil(phase.length / BATCH_SIZE) }, (_2, index) => phase.slice(index * BATCH_SIZE, (index + 1) * BATCH_SIZE)));
119928
120441
  for (const batch of batches) {
@@ -119960,19 +120473,19 @@ class ParseStage {
119960
120473
  return files.map((file3) => results.get(file3.relativePath));
119961
120474
  }
119962
120475
  recordHeaderImporterEvidence(ctx, files, parsedFiles) {
119963
- const knownHeaders = new Set(files.filter((file3) => path19.extname(file3.relativePath).toLowerCase() === ".h").map((file3) => path19.posix.normalize(file3.relativePath)));
120476
+ const knownHeaders = new Set(files.filter((file3) => path21.extname(file3.relativePath).toLowerCase() === ".h").map((file3) => path21.posix.normalize(file3.relativePath)));
119964
120477
  const mutable = {
119965
120478
  ...ctx.structuralHeaderEvidenceByFile
119966
120479
  };
119967
120480
  for (const parsed of parsedFiles) {
119968
- const extension = path19.extname(parsed.file.relativePath).toLowerCase();
120481
+ const extension = path21.extname(parsed.file.relativePath).toLowerCase();
119969
120482
  const key = extension === ".c" ? "cImporters" : [".cpp", ".hpp"].includes(extension) ? "cppImporters" : undefined;
119970
120483
  if (!key)
119971
120484
  continue;
119972
120485
  for (const imported of parsed.rawImports) {
119973
120486
  if (!["c_include", "cpp_include"].includes(imported.form) || imported.specifier.startsWith("<"))
119974
120487
  continue;
119975
- const header = path19.posix.normalize(path19.posix.join(path19.posix.dirname(parsed.file.relativePath), imported.specifier));
120488
+ const header = path21.posix.normalize(path21.posix.join(path21.posix.dirname(parsed.file.relativePath), imported.specifier));
119976
120489
  if (!knownHeaders.has(header))
119977
120490
  continue;
119978
120491
  const existing = mutable[header] ?? {};
@@ -119983,9 +120496,9 @@ class ParseStage {
119983
120496
  }
119984
120497
  async parseFile(ctx, file3) {
119985
120498
  if (!file3.needsReparse) {
119986
- const extension = path19.extname(file3.relativePath).toLowerCase();
120499
+ const extension = path21.extname(file3.relativePath).toLowerCase();
119987
120500
  if ([".c", ".cpp", ".hpp"].includes(extension)) {
119988
- const content = file3.snapshotContent ?? await fs14.readFile(file3.absolutePath, "utf8");
120501
+ const content = file3.snapshotContent ?? await fs15.readFile(file3.absolutePath, "utf8");
119989
120502
  const outcome = await this.runtime.parse({ extension, source: Buffer.from(content) });
119990
120503
  if (outcome.status === "failed")
119991
120504
  throw new StructuralEtlParseError(file3.relativePath, outcome.failureKind, `Structural evidence parse failed (${outcome.failureKind})`, outcome.diagnosticCount, outcome.diagnostics.slice(0, 10));
@@ -119997,8 +120510,8 @@ class ParseStage {
119997
120510
  return { file: file3, chunks: [], symbols: [], rawImports: [], rawEdges: [] };
119998
120511
  }
119999
120512
  try {
120000
- const content = file3.snapshotContent ?? await fs14.readFile(file3.absolutePath, "utf-8");
120001
- const ext2 = path19.extname(file3.relativePath).toLowerCase();
120513
+ const content = file3.snapshotContent ?? await fs15.readFile(file3.absolutePath, "utf-8");
120514
+ const ext2 = path21.extname(file3.relativePath).toLowerCase();
120002
120515
  const chunkerMaxChars = resolveChunkerMaxChars();
120003
120516
  const chunks = smartChunk(content, file3.relativePath, chunkerMaxChars ? { maxChunkChars: chunkerMaxChars } : {});
120004
120517
  let symbols;
@@ -120552,7 +121065,7 @@ var init_resolver = __esm(() => {
120552
121065
  });
120553
121066
 
120554
121067
  // ../../packages/core/dist/services/structural/resolvers/typescript.js
120555
- import path20 from "path";
121068
+ import path22 from "path";
120556
121069
  function candidates(identities) {
120557
121070
  return Object.freeze(identities.map((identity) => Object.freeze({
120558
121071
  fqn: identity.fqn,
@@ -120647,7 +121160,7 @@ function probe(base, known, dialect = "typescript") {
120647
121160
  const bases = /\.[cm]?jsx?$/u.test(base) ? [base.replace(/\.[cm]?jsx?$/u, ".ts"), base.replace(/\.[cm]?jsx?$/u, ".tsx"), base] : [base];
120648
121161
  for (const candidateBase of bases)
120649
121162
  for (const suffix of DIALECT_PROBES[dialect] ?? [""]) {
120650
- const value = path20.posix.normalize(`${candidateBase}${suffix}`);
121163
+ const value = path22.posix.normalize(`${candidateBase}${suffix}`);
120651
121164
  if (!value.startsWith("../") && value !== ".." && known.has(value))
120652
121165
  return value;
120653
121166
  }
@@ -120656,7 +121169,7 @@ function probe(base, known, dialect = "typescript") {
120656
121169
  function resolveStructuralSpecifier(specifier, fromFile, build, dialect = "typescript") {
120657
121170
  const known = new Set(build.knownFiles.map(normalizeStructuralFile));
120658
121171
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
120659
- return probe(path20.posix.join(path20.posix.dirname(fromFile), specifier), known, dialect);
121172
+ return probe(path22.posix.join(path22.posix.dirname(fromFile), specifier), known, dialect);
120660
121173
  }
120661
121174
  const aliases = build.pathAliasesByFile?.[normalizeStructuralFile(fromFile)] ?? build.pathAliases ?? [];
120662
121175
  for (const alias of aliases) {
@@ -120920,7 +121433,7 @@ var init_scripting2 = __esm(() => {
120920
121433
  });
120921
121434
 
120922
121435
  // ../../packages/core/dist/services/structural/resolvers/systems.js
120923
- import path21 from "path";
121436
+ import path23 from "path";
120924
121437
  var DIALECTS, SYSTEMS_LANGUAGE_RESOLVER;
120925
121438
  var init_systems2 = __esm(() => {
120926
121439
  init_typescript2();
@@ -120939,7 +121452,7 @@ var init_systems2 = __esm(() => {
120939
121452
  const bindings = item.bindings.map((binding) => binding.imported === "*" && binding.local === "*" && unresolvedTarget && !unresolvedTarget.qualifier ? { ...binding, imported: unresolvedTarget.name, local: unresolvedTarget.name } : binding);
120940
121453
  if (item.specifier === "crate" || item.specifier.startsWith("crate/")) {
120941
121454
  const crateRoot = file3.file.startsWith("src/") ? "src" : "";
120942
- return { ...item, bindings, specifier: `./${path21.posix.relative(path21.posix.dirname(file3.file), path21.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
121455
+ return { ...item, bindings, specifier: `./${path23.posix.relative(path23.posix.dirname(file3.file), path23.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
120943
121456
  }
120944
121457
  if (item.specifier === "self" || item.specifier.startsWith("self/"))
120945
121458
  return { ...item, bindings, specifier: `./${item.specifier.replace(/^self\/?/u, "")}` };
@@ -121037,8 +121550,8 @@ var init_data_document2 = __esm(() => {
121037
121550
  });
121038
121551
 
121039
121552
  // ../../packages/core/dist/services/etl/stages/resolve.js
121040
- import path22 from "path";
121041
- import fs15 from "fs";
121553
+ import path24 from "path";
121554
+ import fs16 from "fs";
121042
121555
 
121043
121556
  class ResolveStage {
121044
121557
  symbolRepository;
@@ -121062,7 +121575,7 @@ class ResolveStage {
121062
121575
  const structuralDocuments = files.flatMap((file3) => {
121063
121576
  if (!file3.structure)
121064
121577
  return [];
121065
- const language = resolveStructuralLanguage(path22.extname(file3.file.relativePath));
121578
+ const language = resolveStructuralLanguage(path24.extname(file3.file.relativePath));
121066
121579
  if (language.status !== "supported")
121067
121580
  throw new Error(`structural_manifest_missing:${file3.file.relativePath}`);
121068
121581
  return [{
@@ -121074,13 +121587,13 @@ class ResolveStage {
121074
121587
  }];
121075
121588
  });
121076
121589
  const currentStructuralFiles = new Set(structuralDocuments.map((document2) => document2.file));
121077
- const skippedStructuralFiles = new Set(files.filter((item) => !item.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path22.extname(item.file.relativePath).toLowerCase())).map((item) => item.file.relativePath));
121590
+ const skippedStructuralFiles = new Set(files.filter((item) => !item.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path24.extname(item.file.relativePath).toLowerCase())).map((item) => item.file.relativePath));
121078
121591
  const pathAliasesByFile = Object.fromEntries([...knownRelPaths].map((file3) => [
121079
121592
  file3,
121080
121593
  this.structuralAliasesFor(file3, rootAliases, monorepoPackages)
121081
121594
  ]));
121082
121595
  const buildMetadata = { knownFiles: [...knownRelPaths], pathAliasesByFile };
121083
- const seedRows = repositoryDefinitions.filter((definition) => STRUCTURAL_SEED_EXTENSIONS.has(path22.extname(definition.file_path).toLowerCase())).filter((definition) => knownRelPaths.has(definition.file_path) && skippedStructuralFiles.has(definition.file_path)).filter((definition) => !currentStructuralFiles.has(definition.file_path));
121596
+ const seedRows = repositoryDefinitions.filter((definition) => STRUCTURAL_SEED_EXTENSIONS.has(path24.extname(definition.file_path).toLowerCase())).filter((definition) => knownRelPaths.has(definition.file_path) && skippedStructuralFiles.has(definition.file_path)).filter((definition) => !currentStructuralFiles.has(definition.file_path));
121084
121597
  const seedIds = new Set;
121085
121598
  for (const definition of seedRows) {
121086
121599
  if (seedIds.has(definition.id))
@@ -121173,7 +121686,7 @@ class ResolveStage {
121173
121686
  if (parsed.file !== definition.file_path) {
121174
121687
  throw new Error(`structural_repository_seed_file_mismatch:${definition.id}`);
121175
121688
  }
121176
- const language = resolveStructuralLanguage(path22.extname(definition.file_path));
121689
+ const language = resolveStructuralLanguage(path24.extname(definition.file_path));
121177
121690
  if (language.status !== "supported")
121178
121691
  throw new Error(`structural_repository_seed_language:${definition.id}`);
121179
121692
  let identity;
@@ -121225,7 +121738,7 @@ class ResolveStage {
121225
121738
  });
121226
121739
  }
121227
121740
  resolveFile(parsed, projectPath, knownRelPaths, rootAliases, monorepoPackages, symbolIndex, knownFqns) {
121228
- const fromDir = path22.dirname(path22.join(projectPath, parsed.file.relativePath));
121741
+ const fromDir = path24.dirname(path24.join(projectPath, parsed.file.relativePath));
121229
121742
  const packageAliases = this.getPackageAliases(parsed.file.relativePath, monorepoPackages);
121230
121743
  const allAliases = [...packageAliases, ...rootAliases];
121231
121744
  const resolvedImports = parsed.rawImports.map((raw2) => {
@@ -121296,7 +121809,7 @@ class ResolveStage {
121296
121809
  index.set(def.name, `${def.file_path}#${def.name}`);
121297
121810
  }
121298
121811
  } catch (err) {
121299
- const skippedStructural = files.some((file3) => !file3.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path22.extname(file3.file.relativePath).toLowerCase()));
121812
+ const skippedStructural = files.some((file3) => !file3.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path24.extname(file3.file.relativePath).toLowerCase()));
121300
121813
  if (skippedStructural)
121301
121814
  throw new Error("structural_repository_seed_failed", { cause: err });
121302
121815
  logger.warn("buildSymbolIndex: repo seed failed, in-batch only", {
@@ -121320,7 +121833,7 @@ class ResolveStage {
121320
121833
  }
121321
121834
  resolveSpecifier(specifier, fromDir, projectPath, knownRelPaths, aliases) {
121322
121835
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
121323
- const resolved = this.probeExtensions(path22.resolve(fromDir, specifier), projectPath, knownRelPaths);
121836
+ const resolved = this.probeExtensions(path24.resolve(fromDir, specifier), projectPath, knownRelPaths);
121324
121837
  return { resolvedPath: resolved, external: false };
121325
121838
  }
121326
121839
  for (const alias of aliases) {
@@ -121328,8 +121841,8 @@ class ResolveStage {
121328
121841
  const suffix = specifier.slice(alias.prefix.length);
121329
121842
  for (const target of alias.targets) {
121330
121843
  const cleanTarget = target.replace(/\/\*$/, "");
121331
- const basePath = alias.packagePath ? path22.join(projectPath, alias.packagePath) : projectPath;
121332
- const absPath = path22.join(basePath, cleanTarget + suffix);
121844
+ const basePath = alias.packagePath ? path24.join(projectPath, alias.packagePath) : projectPath;
121845
+ const absPath = path24.join(basePath, cleanTarget + suffix);
121333
121846
  const resolved = this.probeExtensions(absPath, projectPath, knownRelPaths);
121334
121847
  if (resolved)
121335
121848
  return { resolvedPath: resolved, external: false };
@@ -121345,7 +121858,7 @@ class ResolveStage {
121345
121858
  ...TS_EXTENSIONS.map((ext2) => absPath.replace(/\.[^.]+$/, ext2))
121346
121859
  ];
121347
121860
  for (const candidate2 of candidates2) {
121348
- const rel = path22.relative(projectPath, candidate2).replace(/\\/g, "/");
121861
+ const rel = path24.relative(projectPath, candidate2).replace(/\\/g, "/");
121349
121862
  if (knownRelPaths.has(rel))
121350
121863
  return rel;
121351
121864
  }
@@ -121353,9 +121866,9 @@ class ResolveStage {
121353
121866
  }
121354
121867
  loadTsConfigPaths(projectPath, packageBase) {
121355
121868
  const aliases = [];
121356
- const tsconfigPath = path22.join(projectPath, "tsconfig.json");
121869
+ const tsconfigPath = path24.join(projectPath, "tsconfig.json");
121357
121870
  try {
121358
- const raw2 = fs15.readFileSync(tsconfigPath, "utf-8");
121871
+ const raw2 = fs16.readFileSync(tsconfigPath, "utf-8");
121359
121872
  const stripped = raw2.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
121360
121873
  const tsconfig = JSON.parse(stripped);
121361
121874
  const paths = tsconfig?.compilerOptions?.paths ?? {};
@@ -121384,7 +121897,7 @@ class ResolveStage {
121384
121897
  }
121385
121898
  }
121386
121899
  for (const packageRelPath of packagePaths) {
121387
- const absPackagePath = path22.join(projectPath, packageRelPath);
121900
+ const absPackagePath = path24.join(projectPath, packageRelPath);
121388
121901
  const aliases = this.loadTsConfigPaths(absPackagePath, packageRelPath);
121389
121902
  if (aliases.length > 0) {
121390
121903
  packages.push({
@@ -121414,7 +121927,7 @@ class ResolveStage {
121414
121927
  structuralAliasesFor(filePath, rootAliases, packages) {
121415
121928
  return [...this.getPackageAliases(filePath, packages), ...rootAliases].map((alias) => ({
121416
121929
  pattern: alias.prefix + (alias.targets.some((target) => target.includes("*")) ? "/*" : ""),
121417
- targets: alias.targets.map((target) => alias.packagePath ? path22.posix.join(alias.packagePath, target) : target)
121930
+ targets: alias.targets.map((target) => alias.packagePath ? path24.posix.join(alias.packagePath, target) : target)
121418
121931
  }));
121419
121932
  }
121420
121933
  }
@@ -121478,7 +121991,7 @@ var init_with_deadlock_retry = __esm(() => {
121478
121991
  });
121479
121992
 
121480
121993
  // ../../packages/core/dist/services/etl/stages/load.js
121481
- import path23 from "path";
121994
+ import path25 from "path";
121482
121995
  function formatDuration(ms) {
121483
121996
  const totalSec = Math.max(0, Math.round(ms / 1000));
121484
121997
  if (totalSec < 60)
@@ -121755,7 +122268,7 @@ class LoadStage {
121755
122268
  const filePath = file3.file.relativePath;
121756
122269
  const batch = buildSymbolPersistenceBatch(ctx.projectId, file3);
121757
122270
  if (ctx.graphGenerationLease) {
121758
- const manifest = getLanguageManifestEntry(path23.extname(filePath));
122271
+ const manifest = getLanguageManifestEntry(path25.extname(filePath));
121759
122272
  const diagnostics2 = (file3.structuralDiagnostics ?? []).slice(0, 10).map((diagnostic2) => ({
121760
122273
  code: diagnostic2.code,
121761
122274
  severity: diagnostic2.severity,
@@ -122212,9 +122725,9 @@ var init_graph_generation_coordinator = __esm(() => {
122212
122725
  // ../../packages/core/dist/services/etl/pipeline.js
122213
122726
  import { createHash as createHash7 } from "crypto";
122214
122727
  import { setTimeout as delay2 } from "timers/promises";
122215
- import path24 from "path";
122728
+ import path26 from "path";
122216
122729
  function buildHeaderLanguageEvidence(files) {
122217
- const headers = new Set(files.filter((file3) => path24.posix.extname(file3.relativePath).toLowerCase() === ".h").map((file3) => path24.posix.normalize(file3.relativePath)));
122730
+ const headers = new Set(files.filter((file3) => path26.posix.extname(file3.relativePath).toLowerCase() === ".h").map((file3) => path26.posix.normalize(file3.relativePath)));
122218
122731
  const mutable = new Map;
122219
122732
  const entry2 = (header) => {
122220
122733
  let value = mutable.get(header);
@@ -122225,7 +122738,7 @@ function buildHeaderLanguageEvidence(files) {
122225
122738
  return value;
122226
122739
  };
122227
122740
  for (const file3 of files) {
122228
- if (path24.posix.basename(file3.relativePath) !== "compile_commands.json" || file3.snapshotContent === undefined)
122741
+ if (path26.posix.basename(file3.relativePath) !== "compile_commands.json" || file3.snapshotContent === undefined)
122229
122742
  continue;
122230
122743
  let commands;
122231
122744
  try {
@@ -122241,11 +122754,11 @@ function buildHeaderLanguageEvidence(files) {
122241
122754
  const record2 = command;
122242
122755
  if (typeof record2.file !== "string")
122243
122756
  continue;
122244
- const projectRoot = path24.resolve(file3.absolutePath, ...file3.relativePath.split("/").map(() => ".."));
122245
- const commandDirectory = typeof record2.directory === "string" ? path24.resolve(projectRoot, record2.directory) : projectRoot;
122246
- const absoluteInput = path24.resolve(commandDirectory, record2.file);
122247
- const relative2 = path24.relative(projectRoot, absoluteInput);
122248
- const header = path24.posix.normalize(relative2.replaceAll(path24.sep, "/"));
122757
+ const projectRoot = path26.resolve(file3.absolutePath, ...file3.relativePath.split("/").map(() => ".."));
122758
+ const commandDirectory = typeof record2.directory === "string" ? path26.resolve(projectRoot, record2.directory) : projectRoot;
122759
+ const absoluteInput = path26.resolve(commandDirectory, record2.file);
122760
+ const relative2 = path26.relative(projectRoot, absoluteInput);
122761
+ const header = path26.posix.normalize(relative2.replaceAll(path26.sep, "/"));
122249
122762
  if (!headers.has(header))
122250
122763
  continue;
122251
122764
  const invocation = typeof record2.command === "string" ? record2.command : Array.isArray(record2.arguments) ? record2.arguments.join(" ") : "";
@@ -123404,16 +123917,16 @@ function detectRoutes(httpEdges, defs, opts = {}) {
123404
123917
  const seen = new Set;
123405
123918
  const out = [];
123406
123919
  for (const e of httpEdges) {
123407
- const path26 = e.route;
123408
- if (!path26)
123920
+ const path28 = e.route;
123921
+ if (!path28)
123409
123922
  continue;
123410
123923
  const method = (e.method ?? "ANY").toUpperCase();
123411
- const key = method + " " + path26;
123924
+ const key = method + " " + path28;
123412
123925
  if (seen.has(key))
123413
123926
  continue;
123414
123927
  seen.add(key);
123415
123928
  out.push({
123416
- path: path26,
123929
+ path: path28,
123417
123930
  method: e.method,
123418
123931
  file: e.fromFile,
123419
123932
  handler: e.targetFqn ?? e.symbolName
@@ -123424,12 +123937,12 @@ function detectRoutes(httpEdges, defs, opts = {}) {
123424
123937
  continue;
123425
123938
  const parsed = parseRouteName(d.name);
123426
123939
  const method = parsed?.method ?? "ANY";
123427
- const path26 = parsed?.path ?? d.name;
123428
- const key = method + " " + path26;
123940
+ const path28 = parsed?.path ?? d.name;
123941
+ const key = method + " " + path28;
123429
123942
  if (seen.has(key))
123430
123943
  continue;
123431
123944
  seen.add(key);
123432
- out.push({ path: path26, method: parsed?.method, file: d.filePath, handler: d.name });
123945
+ out.push({ path: path28, method: parsed?.method, file: d.filePath, handler: d.name });
123433
123946
  }
123434
123947
  for (const d of defs) {
123435
123948
  const parsed = parseRouteName(d.name);
@@ -123650,8 +124163,8 @@ __export(exports_symbol_graph_service, {
123650
124163
  symbolGraphService: () => symbolGraphService,
123651
124164
  SymbolGraphService: () => SymbolGraphService
123652
124165
  });
123653
- import path26 from "path";
123654
- import fs16 from "fs/promises";
124166
+ import path28 from "path";
124167
+ import fs17 from "fs/promises";
123655
124168
 
123656
124169
  class SymbolGraphService {
123657
124170
  identityLookup;
@@ -123979,7 +124492,7 @@ class SymbolGraphService {
123979
124492
  async readSnippet(relativePath, lineStart, lineEnd, projectId) {
123980
124493
  try {
123981
124494
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
123982
- const content = await fs16.readFile(absolutePath, "utf-8");
124495
+ const content = await fs17.readFile(absolutePath, "utf-8");
123983
124496
  const lines = content.split(`
123984
124497
  `);
123985
124498
  return lines.slice(Math.max(0, lineStart - 1), Math.min(lines.length, lineEnd)).join(`
@@ -123991,7 +124504,7 @@ class SymbolGraphService {
123991
124504
  async readContext(relativePath, lineNumber, contextLines, projectId) {
123992
124505
  try {
123993
124506
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
123994
- const content = await fs16.readFile(absolutePath, "utf-8");
124507
+ const content = await fs17.readFile(absolutePath, "utf-8");
123995
124508
  const lines = content.split(`
123996
124509
  `);
123997
124510
  const start = Math.max(0, lineNumber - contextLines - 1);
@@ -124004,7 +124517,7 @@ class SymbolGraphService {
124004
124517
  }
124005
124518
  async resolveToAbsolute(relativePath, projectId) {
124006
124519
  const root = await this.getProjectRoot(projectId);
124007
- return root ? path26.resolve(root, relativePath) : relativePath;
124520
+ return root ? path28.resolve(root, relativePath) : relativePath;
124008
124521
  }
124009
124522
  async getProjectRoot(projectId) {
124010
124523
  const cached2 = this.projectRootCache.get(projectId);
@@ -127998,31 +128511,31 @@ class TracePathService {
127998
128511
  const chains = [];
127999
128512
  const seen = new Set;
128000
128513
  let walks = 0;
128001
- const walk = (fqn, path29) => {
128514
+ const walk = (fqn, path31) => {
128002
128515
  if (chains.length >= CHAIN_CAP)
128003
128516
  return;
128004
128517
  if (walks >= MAX_WALKS)
128005
128518
  return;
128006
128519
  walks++;
128007
- const key = path29.join("\u2192");
128520
+ const key = path31.join("\u2192");
128008
128521
  if (seen.has(key))
128009
128522
  return;
128010
128523
  seen.add(key);
128011
128524
  const next = adj.get(fqn);
128012
128525
  if (!next || next.length === 0 || !whoHasChild.has(fqn)) {
128013
- if (path29.length > 1)
128014
- chains.push(path29.map((n2) => this.fqnToName(n2)).join(" \u2192 "));
128526
+ if (path31.length > 1)
128527
+ chains.push(path31.map((n2) => this.fqnToName(n2)).join(" \u2192 "));
128015
128528
  return;
128016
128529
  }
128017
128530
  for (const child of next) {
128018
128531
  if (chains.length >= CHAIN_CAP || walks >= MAX_WALKS)
128019
128532
  return;
128020
- if (path29.includes(child)) {
128021
- const cycled = [...path29, `${this.fqnToName(child)}\u21BA`];
128533
+ if (path31.includes(child)) {
128534
+ const cycled = [...path31, `${this.fqnToName(child)}\u21BA`];
128022
128535
  chains.push(cycled.map((n2) => n2).join(" \u2192 "));
128023
128536
  continue;
128024
128537
  }
128025
- walk(child, [...path29, child]);
128538
+ walk(child, [...path31, child]);
128026
128539
  }
128027
128540
  };
128028
128541
  for (const seed of seeds) {
@@ -131164,9 +131677,9 @@ var init_l1_memory_cache = __esm(() => {
131164
131677
  });
131165
131678
 
131166
131679
  // ../../packages/core/dist/services/health/local-health-checker.js
131167
- import fs19 from "fs/promises";
131680
+ import fs20 from "fs/promises";
131168
131681
  import { existsSync as existsSync3 } from "fs";
131169
- import path31 from "path";
131682
+ import path33 from "path";
131170
131683
 
131171
131684
  class LocalHealthChecker {
131172
131685
  ollamaBaseUrl = process.env.OLLAMA_BASE_URL || "http://localhost:11434";
@@ -131200,10 +131713,10 @@ class LocalHealthChecker {
131200
131713
  const start = Date.now();
131201
131714
  try {
131202
131715
  if (!existsSync3(this.dataDir))
131203
- await fs19.mkdir(this.dataDir, { recursive: true });
131204
- const probe2 = path31.join(this.dataDir, ".health-check-test");
131205
- await fs19.writeFile(probe2, "ok");
131206
- await fs19.unlink(probe2);
131716
+ await fs20.mkdir(this.dataDir, { recursive: true });
131717
+ const probe2 = path33.join(this.dataDir, ".health-check-test");
131718
+ await fs20.writeFile(probe2, "ok");
131719
+ await fs20.unlink(probe2);
131207
131720
  return { available: true, latency: Date.now() - start, details: { path: this.dataDir, writable: true } };
131208
131721
  } catch (error51) {
131209
131722
  return { available: false, latency: Date.now() - start, error: `Data directory error: ${error51.message}` };
@@ -131599,10 +132112,18 @@ var init_scheduler_store_factory = __esm(() => {
131599
132112
  });
131600
132113
 
131601
132114
  // ../../packages/core/dist/services/scheduler/scheduler.js
131602
- function readEnabled() {
132115
+ function readEnabledEnv() {
131603
132116
  const raw2 = process.env.MASSA_AI_SCHEDULER_ENABLED;
132117
+ if (raw2 === undefined)
132118
+ return;
131604
132119
  return raw2 === "true" || raw2 === "1";
131605
132120
  }
132121
+ function envPositiveInt(raw2) {
132122
+ if (raw2 === undefined || raw2 === "")
132123
+ return;
132124
+ const parsed = parsePositiveIntEnv(raw2, NaN);
132125
+ return Number.isNaN(parsed) ? undefined : parsed;
132126
+ }
131606
132127
 
131607
132128
  class Scheduler {
131608
132129
  store;
@@ -131616,9 +132137,10 @@ class Scheduler {
131616
132137
  started = false;
131617
132138
  constructor(opts = {}) {
131618
132139
  this.store = opts.store ?? getScheduledJobStore();
131619
- this.tickIntervalMs = opts.tickIntervalMs ?? parsePositiveIntEnv(process.env.MASSA_AI_SCHEDULER_TICK_MS, DEFAULTS.tickMs);
131620
- this.maxConcurrent = opts.maxConcurrent ?? parsePositiveIntEnv(process.env.MASSA_AI_SCHEDULER_MAX_CONCURRENT, DEFAULTS.maxConcurrent);
131621
- this.enabled = opts.enabled ?? readEnabled();
132140
+ const schedulerConfig = config.get("scheduler");
132141
+ this.tickIntervalMs = opts.tickIntervalMs ?? envPositiveInt(process.env.MASSA_AI_SCHEDULER_TICK_MS) ?? schedulerConfig?.tickMs ?? DEFAULTS.tickMs;
132142
+ this.maxConcurrent = opts.maxConcurrent ?? envPositiveInt(process.env.MASSA_AI_SCHEDULER_MAX_CONCURRENT) ?? schedulerConfig?.maxConcurrent ?? DEFAULTS.maxConcurrent;
132143
+ this.enabled = opts.enabled ?? readEnabledEnv() ?? schedulerConfig?.enabled ?? false;
131622
132144
  }
131623
132145
  registerHandler(jobKind, handler) {
131624
132146
  this.handlers.set(jobKind, handler);
@@ -132982,21 +133504,31 @@ var init_observation_consolidation_job = __esm(() => {
132982
133504
  });
132983
133505
 
132984
133506
  // ../../packages/core/dist/services/scheduler/scheduler-defaults.js
132985
- function envBool2(key, fallback) {
133507
+ function envBool2(key, fileValue, fallback) {
132986
133508
  const raw2 = process.env[key];
132987
133509
  if (raw2 === undefined)
132988
- return fallback;
133510
+ return fileValue ?? fallback;
132989
133511
  return raw2 === "true" || raw2 === "1";
132990
133512
  }
132991
- function envNum2(key, fallback) {
133513
+ function envNum2(key, fileValue, fallback) {
132992
133514
  const raw2 = process.env[key];
132993
- if (raw2 === undefined || raw2 === "")
132994
- return fallback;
132995
- const n2 = Number(raw2);
132996
- return Number.isFinite(n2) && n2 > 0 ? n2 : fallback;
133515
+ if (raw2 !== undefined && raw2 !== "") {
133516
+ const n2 = Number(raw2);
133517
+ if (Number.isFinite(n2) && n2 > 0)
133518
+ return n2;
133519
+ }
133520
+ return fileValue ?? fallback;
133521
+ }
133522
+ function readFileSchedulerJobs() {
133523
+ try {
133524
+ const raw2 = loadRawUserConfig().scheduler?.jobs;
133525
+ return raw2;
133526
+ } catch {
133527
+ return;
133528
+ }
132997
133529
  }
132998
133530
  function applySafeDefaults(job) {
132999
- if (!envBool2("MASSA_AI_SCHEDULER_SAFE_DEFAULTS", false)) {
133531
+ if (!envBool2("MASSA_AI_SCHEDULER_SAFE_DEFAULTS", undefined, false)) {
133000
133532
  return job;
133001
133533
  }
133002
133534
  if (job.jobKind === "memory-consolidation") {
@@ -133043,10 +133575,12 @@ function registerDefaultJobs(scheduler) {
133043
133575
  const count = CheckpointManager2.getInstance().purgeExpired();
133044
133576
  logger.info("Scheduled checkpoint purge completed", { count });
133045
133577
  });
133578
+ const fileJobs = readFileSchedulerJobs();
133046
133579
  for (const rawDef of DEFAULT_SCHEDULED_JOBS) {
133047
133580
  const def = applySafeDefaults(rawDef);
133048
- const enabled2 = envBool2(def.enableEnvVar, def.defaultEnabled);
133049
- const intervalMs = envNum2(def.intervalEnvVar, def.schedule.intervalMs ?? THIRTY_MIN);
133581
+ const fileJob = fileJobs?.[def.jobKind];
133582
+ const enabled2 = envBool2(def.enableEnvVar, fileJob?.enabled, def.defaultEnabled);
133583
+ const intervalMs = envNum2(def.intervalEnvVar, fileJob?.intervalMs, def.schedule.intervalMs ?? THIRTY_MIN);
133050
133584
  const schedule = { type: "interval", intervalMs };
133051
133585
  scheduler.registerOrResumeJob({
133052
133586
  id: def.id,
@@ -133127,9 +133661,9 @@ var init_scheduler2 = __esm(() => {
133127
133661
  });
133128
133662
 
133129
133663
  // ../../packages/core/dist/services/pricing/models-dev-client.js
133130
- import fs20 from "fs/promises";
133664
+ import fs21 from "fs/promises";
133131
133665
  import { existsSync as existsSync4 } from "fs";
133132
- import path32 from "path";
133666
+ import path34 from "path";
133133
133667
  function getModelsDevClient() {
133134
133668
  if (!clientInstance) {
133135
133669
  clientInstance = new ModelsDevClient;
@@ -133149,7 +133683,7 @@ var init_models_dev_client = __esm(() => {
133149
133683
  memoryCacheTimestamp = 0;
133150
133684
  getLocalCachePath() {
133151
133685
  const dataDir = config.get("dataDir");
133152
- return path32.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
133686
+ return path34.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
133153
133687
  }
133154
133688
  async loadLocalCache() {
133155
133689
  const cachePath = this.getLocalCachePath();
@@ -133157,7 +133691,7 @@ var init_models_dev_client = __esm(() => {
133157
133691
  if (!existsSync4(cachePath)) {
133158
133692
  return null;
133159
133693
  }
133160
- const content = await fs20.readFile(cachePath, "utf-8");
133694
+ const content = await fs21.readFile(cachePath, "utf-8");
133161
133695
  const data = JSON.parse(content);
133162
133696
  const age = Date.now() - data.timestamp;
133163
133697
  if (age > ModelsDevClient.LOCAL_CACHE_TTL) {
@@ -133184,14 +133718,14 @@ var init_models_dev_client = __esm(() => {
133184
133718
  async saveLocalCache(models) {
133185
133719
  const cachePath = this.getLocalCachePath();
133186
133720
  try {
133187
- const dir = path32.dirname(cachePath);
133188
- await fs20.mkdir(dir, { recursive: true });
133721
+ const dir = path34.dirname(cachePath);
133722
+ await fs21.mkdir(dir, { recursive: true });
133189
133723
  const data = {
133190
133724
  timestamp: Date.now(),
133191
133725
  version: "1.0.0",
133192
133726
  models: Object.fromEntries(models)
133193
133727
  };
133194
- await fs20.writeFile(cachePath, JSON.stringify(data), "utf-8");
133728
+ await fs21.writeFile(cachePath, JSON.stringify(data), "utf-8");
133195
133729
  logger.debug("Saved pricing to local cache", {
133196
133730
  models: models.size,
133197
133731
  path: cachePath
@@ -133520,7 +134054,7 @@ var init_models_dev_client = __esm(() => {
133520
134054
  const cachePath = this.getLocalCachePath();
133521
134055
  try {
133522
134056
  if (existsSync4(cachePath)) {
133523
- await fs20.unlink(cachePath);
134057
+ await fs21.unlink(cachePath);
133524
134058
  logger.debug("Local pricing cache file deleted");
133525
134059
  }
133526
134060
  } catch (error51) {
@@ -139075,33 +139609,33 @@ var require_URL = __commonJS((exports, module) => {
139075
139609
  else
139076
139610
  return basepath.substring(0, lastslash + 1) + refpath;
139077
139611
  }
139078
- function remove_dot_segments(path33) {
139079
- if (!path33)
139080
- return path33;
139612
+ function remove_dot_segments(path35) {
139613
+ if (!path35)
139614
+ return path35;
139081
139615
  var output = "";
139082
- while (path33.length > 0) {
139083
- if (path33 === "." || path33 === "..") {
139084
- path33 = "";
139616
+ while (path35.length > 0) {
139617
+ if (path35 === "." || path35 === "..") {
139618
+ path35 = "";
139085
139619
  break;
139086
139620
  }
139087
- var twochars = path33.substring(0, 2);
139088
- var threechars = path33.substring(0, 3);
139089
- var fourchars = path33.substring(0, 4);
139621
+ var twochars = path35.substring(0, 2);
139622
+ var threechars = path35.substring(0, 3);
139623
+ var fourchars = path35.substring(0, 4);
139090
139624
  if (threechars === "../") {
139091
- path33 = path33.substring(3);
139625
+ path35 = path35.substring(3);
139092
139626
  } else if (twochars === "./") {
139093
- path33 = path33.substring(2);
139627
+ path35 = path35.substring(2);
139094
139628
  } else if (threechars === "/./") {
139095
- path33 = "/" + path33.substring(3);
139096
- } else if (twochars === "/." && path33.length === 2) {
139097
- path33 = "/";
139098
- } else if (fourchars === "/../" || threechars === "/.." && path33.length === 3) {
139099
- path33 = "/" + path33.substring(4);
139629
+ path35 = "/" + path35.substring(3);
139630
+ } else if (twochars === "/." && path35.length === 2) {
139631
+ path35 = "/";
139632
+ } else if (fourchars === "/../" || threechars === "/.." && path35.length === 3) {
139633
+ path35 = "/" + path35.substring(4);
139100
139634
  output = output.replace(/\/?[^\/]*$/, "");
139101
139635
  } else {
139102
- var segment = path33.match(/(\/?([^\/]*))/)[0];
139636
+ var segment = path35.match(/(\/?([^\/]*))/)[0];
139103
139637
  output += segment;
139104
- path33 = path33.substring(segment.length);
139638
+ path35 = path35.substring(segment.length);
139105
139639
  }
139106
139640
  }
139107
139641
  return output;
@@ -151171,21 +151705,21 @@ function jsonToKeyPathChunks(value, label = "$") {
151171
151705
  walk(value, label, out);
151172
151706
  return out;
151173
151707
  }
151174
- function walk(val, path33, out) {
151708
+ function walk(val, path35, out) {
151175
151709
  if (val === null || val === undefined)
151176
151710
  return;
151177
151711
  if (Array.isArray(val)) {
151178
151712
  if (val.length === 0) {
151179
- out.push({ path: path33, content: `**${path33}** = _[]_` });
151713
+ out.push({ path: path35, content: `**${path35}** = _[]_` });
151180
151714
  return;
151181
151715
  }
151182
151716
  if (val.every((v) => v !== null && typeof v === "object")) {
151183
- val.forEach((v, i) => walk(v, `${path33}[${i}]`, out));
151717
+ val.forEach((v, i) => walk(v, `${path35}[${i}]`, out));
151184
151718
  return;
151185
151719
  }
151186
151720
  const items = val.map((v) => `- \`${String(v)}\``).join(`
151187
151721
  `);
151188
- out.push({ path: path33, content: `**${path33}**
151722
+ out.push({ path: path35, content: `**${path35}**
151189
151723
 
151190
151724
  ${items}` });
151191
151725
  return;
@@ -151193,16 +151727,16 @@ ${items}` });
151193
151727
  if (typeof val === "object") {
151194
151728
  const entries = Object.entries(val);
151195
151729
  if (entries.length === 0) {
151196
- out.push({ path: path33, content: `**${path33}** = _{}_` });
151730
+ out.push({ path: path35, content: `**${path35}** = _{}_` });
151197
151731
  return;
151198
151732
  }
151199
151733
  for (const [k2, v] of entries) {
151200
151734
  const safeKey = /^[A-Za-z_$][\w$]*$/.test(k2) ? k2 : JSON.stringify(k2);
151201
- walk(v, `${path33}.${safeKey}`, out);
151735
+ walk(v, `${path35}.${safeKey}`, out);
151202
151736
  }
151203
151737
  return;
151204
151738
  }
151205
- out.push({ path: path33, content: `**${path33}** = \`${String(val)}\`` });
151739
+ out.push({ path: path35, content: `**${path35}** = \`${String(val)}\`` });
151206
151740
  }
151207
151741
  var gfm, STRIP_SELECTORS, tdCache = null;
151208
151742
  var init_html_to_md = __esm(() => {
@@ -174193,9 +174727,9 @@ async function acquireIndexingLease(request) {
174193
174727
 
174194
174728
  // ../../packages/core/dist/services/project-identity/project-root-identity.js
174195
174729
  import { realpath as realpath2 } from "fs/promises";
174196
- import path25 from "path";
174730
+ import path27 from "path";
174197
174731
  async function canonicalizeProjectRoot(projectPath, canonicalize = realpath2) {
174198
- return canonicalize(path25.resolve(projectPath));
174732
+ return canonicalize(path27.resolve(projectPath));
174199
174733
  }
174200
174734
  async function assertProjectRootReuse(options) {
174201
174735
  if (!options.storedProjectPath || options.forceReindex)
@@ -174203,9 +174737,9 @@ async function assertProjectRootReuse(options) {
174203
174737
  const canonicalize = options.canonicalize ?? realpath2;
174204
174738
  let storedCanonical;
174205
174739
  try {
174206
- storedCanonical = await canonicalize(path25.resolve(options.storedProjectPath));
174740
+ storedCanonical = await canonicalize(path27.resolve(options.storedProjectPath));
174207
174741
  } catch {
174208
- storedCanonical = path25.resolve(options.storedProjectPath);
174742
+ storedCanonical = path27.resolve(options.storedProjectPath);
174209
174743
  }
174210
174744
  if (storedCanonical !== options.canonicalProjectPath) {
174211
174745
  throw new Error(`Project ID "${options.projectId}" already indexes canonical root ` + `"${storedCanonical}", not "${options.canonicalProjectPath}"; ` + "use forceReindex only after verifying ownership of the existing project");
@@ -174215,7 +174749,7 @@ async function assertProjectRootReuse(options) {
174215
174749
  // ../../packages/core/dist/tools/index_project.js
174216
174750
  init_workspace_manager();
174217
174751
  init_parser_readiness();
174218
- import path27 from "path";
174752
+ import path29 from "path";
174219
174753
 
174220
174754
  class IndexProjectTool {
174221
174755
  name = "index_project";
@@ -174263,7 +174797,7 @@ class IndexProjectTool {
174263
174797
  try {
174264
174798
  await assertParserReadyForIndexing();
174265
174799
  const canonicalProjectPath = await canonicalizeProjectRoot(projectPath);
174266
- const finalProjectId = projectId || path27.basename(canonicalProjectPath) || "default";
174800
+ const finalProjectId = projectId || path29.basename(canonicalProjectPath) || "default";
174267
174801
  const existing = await workspaceManager.getWorkspace(finalProjectId);
174268
174802
  await assertProjectRootReuse({
174269
174803
  projectId: finalProjectId,
@@ -174817,17 +175351,17 @@ function applyReplacer(root, replacer) {
174817
175351
  return transformChildren(root, replacer, []);
174818
175352
  return transformChildren(normalizeValue(replacedRoot), replacer, []);
174819
175353
  }
174820
- function transformChildren(value, replacer, path28) {
175354
+ function transformChildren(value, replacer, path30) {
174821
175355
  if (isJsonObject(value))
174822
- return transformObject(value, replacer, path28);
175356
+ return transformObject(value, replacer, path30);
174823
175357
  if (isJsonArray(value))
174824
- return transformArray(value, replacer, path28);
175358
+ return transformArray(value, replacer, path30);
174825
175359
  return value;
174826
175360
  }
174827
- function transformObject(obj, replacer, path28) {
175361
+ function transformObject(obj, replacer, path30) {
174828
175362
  const result = {};
174829
175363
  for (const [key, value] of Object.entries(obj)) {
174830
- const childPath = [...path28, key];
175364
+ const childPath = [...path30, key];
174831
175365
  const replacedValue = replacer(key, value, childPath);
174832
175366
  if (replacedValue === undefined)
174833
175367
  continue;
@@ -174835,11 +175369,11 @@ function transformObject(obj, replacer, path28) {
174835
175369
  }
174836
175370
  return result;
174837
175371
  }
174838
- function transformArray(arr, replacer, path28) {
175372
+ function transformArray(arr, replacer, path30) {
174839
175373
  const result = [];
174840
175374
  for (let i = 0;i < arr.length; i++) {
174841
175375
  const value = arr[i];
174842
- const childPath = [...path28, i];
175376
+ const childPath = [...path30, i];
174843
175377
  const replacedValue = replacer(String(i), value, childPath);
174844
175378
  if (replacedValue === undefined)
174845
175379
  continue;
@@ -176220,9 +176754,9 @@ init_dist();
176220
176754
  init_db_connection();
176221
176755
  init_alias_resolver();
176222
176756
  init_safe_error_summary();
176223
- import fs17 from "fs";
176224
- import os6 from "os";
176225
- import path28 from "path";
176757
+ import fs18 from "fs";
176758
+ import os8 from "os";
176759
+ import path30 from "path";
176226
176760
 
176227
176761
  // ../../packages/core/dist/services/hooks/session-pin-store.js
176228
176762
  var DEFAULT_MAX_SIZE = 1000;
@@ -176321,8 +176855,8 @@ class AttributionResolver {
176321
176855
  this.aliasResolver = options.aliasResolver ?? getProjectIdentityAliasResolver();
176322
176856
  this.pins = options.pins ?? new SessionPinStore;
176323
176857
  this.canonicalize = options.canonicalize ?? defaultCanonicalize;
176324
- this.homedir = options.homedir ?? os6.homedir;
176325
- this.fsRoot = options.fsRoot ?? (() => path28.parse(path28.sep).root);
176858
+ this.homedir = options.homedir ?? os8.homedir;
176859
+ this.fsRoot = options.fsRoot ?? (() => path30.parse(path30.sep).root);
176326
176860
  }
176327
176861
  async resolve(input) {
176328
176862
  const caller = input.callerProjectId;
@@ -176373,7 +176907,7 @@ class AttributionResolver {
176373
176907
  }
176374
176908
  let bestPath = null;
176375
176909
  for (const candidate2 of byPath.keys()) {
176376
- if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path28.sep) ? candidate2 : candidate2 + path28.sep)) {
176910
+ if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path30.sep) ? candidate2 : candidate2 + path30.sep)) {
176377
176911
  if (bestPath === null || candidate2.length > bestPath.length) {
176378
176912
  bestPath = candidate2;
176379
176913
  }
@@ -176396,7 +176930,7 @@ class AttributionResolver {
176396
176930
  return projectPath2;
176397
176931
  const fsRoot = this.fsRoot();
176398
176932
  let normalized = projectPath2;
176399
- while (normalized.length > fsRoot.length && normalized.endsWith(path28.sep)) {
176933
+ while (normalized.length > fsRoot.length && normalized.endsWith(path30.sep)) {
176400
176934
  normalized = normalized.slice(0, -1);
176401
176935
  }
176402
176936
  return normalized;
@@ -176404,10 +176938,10 @@ class AttributionResolver {
176404
176938
  }
176405
176939
  function defaultCanonicalize(cwd) {
176406
176940
  try {
176407
- return fs17.realpathSync(cwd);
176941
+ return fs18.realpathSync(cwd);
176408
176942
  } catch {
176409
176943
  try {
176410
- return path28.resolve(cwd);
176944
+ return path30.resolve(cwd);
176411
176945
  } catch {
176412
176946
  return;
176413
176947
  }
@@ -176944,7 +177478,7 @@ init_code_compressor();
176944
177478
 
176945
177479
  // ../../packages/core/dist/services/file-read/file-content-cache.js
176946
177480
  init_dist();
176947
- import fs18 from "fs/promises";
177481
+ import fs19 from "fs/promises";
176948
177482
 
176949
177483
  class FileContentCache {
176950
177484
  extractMetadata;
@@ -176977,7 +177511,7 @@ class FileContentCache {
176977
177511
  metadata: cached2.metadata
176978
177512
  };
176979
177513
  }
176980
- const content = await fs18.readFile(filePath, "utf-8");
177514
+ const content = await fs19.readFile(filePath, "utf-8");
176981
177515
  const metadata = await this.extractMetadata(content, filePath, options);
176982
177516
  evictOldest(this.fileCache, this.FILE_CACHE_MAX_ENTRIES - 1);
176983
177517
  this.fileCache.set(cacheKey, {
@@ -176992,7 +177526,7 @@ class FileContentCache {
176992
177526
 
176993
177527
  // ../../packages/core/dist/services/file-read/file-metadata.js
176994
177528
  init_dist();
176995
- import path29 from "path";
177529
+ import path31 from "path";
176996
177530
 
176997
177531
  class FileMetadataExtractor {
176998
177532
  symbolGraph;
@@ -177028,7 +177562,7 @@ class FileMetadataExtractor {
177028
177562
  return metadata;
177029
177563
  }
177030
177564
  detectLanguage(filePath) {
177031
- const ext2 = path29.extname(filePath).toLowerCase();
177565
+ const ext2 = path31.extname(filePath).toLowerCase();
177032
177566
  const languageMap2 = {
177033
177567
  ".ts": "TypeScript",
177034
177568
  ".tsx": "TypeScript",
@@ -177145,7 +177679,7 @@ function selectLines(lines, range) {
177145
177679
 
177146
177680
  // ../../packages/core/dist/services/file-read/path-containment.js
177147
177681
  init_dist();
177148
- import path30 from "path";
177682
+ import path32 from "path";
177149
177683
 
177150
177684
  class PathContainment {
177151
177685
  projectRoots;
@@ -177153,14 +177687,14 @@ class PathContainment {
177153
177687
  this.projectRoots = projectRoots;
177154
177688
  }
177155
177689
  async resolveFilePath(filePath, projectId) {
177156
- if (path30.isAbsolute(filePath)) {
177157
- return path30.resolve(filePath);
177690
+ if (path32.isAbsolute(filePath)) {
177691
+ return path32.resolve(filePath);
177158
177692
  }
177159
177693
  if (projectId) {
177160
177694
  const root = await this.projectRoots.getProjectRoot(projectId);
177161
177695
  if (root) {
177162
177696
  const cleaned = sanitizeFilePath(filePath);
177163
- return path30.resolve(root, cleaned);
177697
+ return path32.resolve(root, cleaned);
177164
177698
  }
177165
177699
  return null;
177166
177700
  }
@@ -177171,17 +177705,17 @@ class PathContainment {
177171
177705
  if (projectId) {
177172
177706
  const root = await this.projectRoots.getProjectRoot(projectId);
177173
177707
  if (root)
177174
- roots.push(path30.resolve(root));
177708
+ roots.push(path32.resolve(root));
177175
177709
  }
177176
- roots.push(path30.resolve(process.cwd()));
177710
+ roots.push(path32.resolve(process.cwd()));
177177
177711
  const envRoots = (process.env.MASSA_AI_READ_FILE_ROOTS ?? "").split(":").map((s) => s.trim()).filter((s) => s.length > 0);
177178
177712
  for (const extra of envRoots) {
177179
- roots.push(path30.resolve(extra));
177713
+ roots.push(path32.resolve(extra));
177180
177714
  }
177181
- const target = path30.resolve(absoluteFilePath);
177715
+ const target = path32.resolve(absoluteFilePath);
177182
177716
  for (const root of roots) {
177183
- const rel = path30.relative(root, target);
177184
- if (rel !== "" && !rel.startsWith("..") && !path30.isAbsolute(rel)) {
177717
+ const rel = path32.relative(root, target);
177718
+ if (rel !== "" && !rel.startsWith("..") && !path32.isAbsolute(rel)) {
177185
177719
  return { allowed: true };
177186
177720
  }
177187
177721
  if (rel === "")
@@ -178018,8 +178552,8 @@ init_event_bus();
178018
178552
  init_llm_client();
178019
178553
  init_symbol_graph_service();
178020
178554
  import { randomUUID as randomUUID9 } from "crypto";
178021
- import fs21 from "fs";
178022
- import path33 from "path";
178555
+ import fs22 from "fs";
178556
+ import path35 from "path";
178023
178557
  import { spawn as spawn2 } from "child_process";
178024
178558
  var FALLBACK_BOOTSTRAP = {
178025
178559
  enabled: true,
@@ -178203,9 +178737,9 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
178203
178737
  }
178204
178738
  try {
178205
178739
  for (const name26 of README_CANDIDATES) {
178206
- const p = path33.join(projectRoot, name26);
178207
- if (fs21.existsSync(p) && fs21.statSync(p).isFile()) {
178208
- const buf = fs21.readFileSync(p);
178740
+ const p = path35.join(projectRoot, name26);
178741
+ if (fs22.existsSync(p) && fs22.statSync(p).isFile()) {
178742
+ const buf = fs22.readFileSync(p);
178209
178743
  signals.readme = buf.slice(0, MAX_README_BYTES).toString("utf8");
178210
178744
  break;
178211
178745
  }
@@ -178214,14 +178748,14 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
178214
178748
  logger.debug("bootstrap scan: README read failed", { error: e.message });
178215
178749
  }
178216
178750
  try {
178217
- const docsDir = path33.join(projectRoot, "docs");
178218
- if (fs21.existsSync(docsDir) && fs21.statSync(docsDir).isDirectory()) {
178751
+ const docsDir = path35.join(projectRoot, "docs");
178752
+ if (fs22.existsSync(docsDir) && fs22.statSync(docsDir).isDirectory()) {
178219
178753
  const entries = walkMarkdown(docsDir).slice(0, MAX_DOCS);
178220
178754
  for (const rel of entries) {
178221
178755
  try {
178222
- const buf = fs21.readFileSync(rel);
178756
+ const buf = fs22.readFileSync(rel);
178223
178757
  signals.docs.push({
178224
- path: path33.relative(projectRoot, rel),
178758
+ path: path35.relative(projectRoot, rel),
178225
178759
  snippet: buf.slice(0, MAX_DOC_BYTES).toString("utf8")
178226
178760
  });
178227
178761
  } catch {}
@@ -178232,10 +178766,10 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
178232
178766
  }
178233
178767
  try {
178234
178768
  for (const name26 of MANIFEST_FILES) {
178235
- const p = path33.join(projectRoot, name26);
178236
- if (!fs21.existsSync(p) || !fs21.statSync(p).isFile())
178769
+ const p = path35.join(projectRoot, name26);
178770
+ if (!fs22.existsSync(p) || !fs22.statSync(p).isFile())
178237
178771
  continue;
178238
- const raw2 = fs21.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
178772
+ const raw2 = fs22.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
178239
178773
  const kind = name26;
178240
178774
  if (name26 === "package.json") {
178241
178775
  try {
@@ -178275,12 +178809,12 @@ function walkMarkdown(dir) {
178275
178809
  const cur = stack.pop();
178276
178810
  let entries;
178277
178811
  try {
178278
- entries = fs21.readdirSync(cur, { withFileTypes: true });
178812
+ entries = fs22.readdirSync(cur, { withFileTypes: true });
178279
178813
  } catch {
178280
178814
  continue;
178281
178815
  }
178282
178816
  for (const e of entries) {
178283
- const full = path33.join(cur, e.name);
178817
+ const full = path35.join(cur, e.name);
178284
178818
  if (e.isDirectory()) {
178285
178819
  if (e.name === "node_modules" || e.name.startsWith("."))
178286
178820
  continue;
@@ -179349,8 +179883,8 @@ var checkpointRoutes = new Elysia({ prefix: "/api/v1/checkpoints" }).post("/list
179349
179883
 
179350
179884
  // src/routes/project.ts
179351
179885
  init_dist();
179352
- import fs22 from "fs/promises";
179353
- import path34 from "path";
179886
+ import fs23 from "fs/promises";
179887
+ import path36 from "path";
179354
179888
  function isDimensionMismatchError(error51) {
179355
179889
  const message = error51 instanceof Error ? error51.message : String(error51);
179356
179890
  return /dimension mismatch/i.test(message);
@@ -179570,22 +180104,22 @@ var projectRoutes = new Elysia({ prefix: "/api/v1/project" }).get("/list", async
179570
180104
  }).post("/upload-and-index", async ({ body }) => {
179571
180105
  const rawBase = body.projectId || body.projectPath.replace(/\\/g, "/").split("/").filter(Boolean).pop() || "default";
179572
180106
  const finalProjectId = rawBase.replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 128);
179573
- const uploadRoot = process.env.MASSA_AI_UPLOAD_DIR || path34.join(getGlobalDataDir(), "uploads");
179574
- const stagingDir = path34.resolve(uploadRoot, finalProjectId);
179575
- await fs22.rm(stagingDir, { recursive: true, force: true });
179576
- await fs22.mkdir(stagingDir, { recursive: true });
180107
+ const uploadRoot = process.env.MASSA_AI_UPLOAD_DIR || path36.join(getGlobalDataDir(), "uploads");
180108
+ const stagingDir = path36.resolve(uploadRoot, finalProjectId);
180109
+ await fs23.rm(stagingDir, { recursive: true, force: true });
180110
+ await fs23.mkdir(stagingDir, { recursive: true });
179577
180111
  const WRITE_BATCH = 20;
179578
180112
  for (let i = 0;i < body.files.length; i += WRITE_BATCH) {
179579
180113
  await Promise.all(body.files.slice(i, i + WRITE_BATCH).map(async (file3) => {
179580
- if (path34.isAbsolute(file3.relativePath) || file3.relativePath.includes("..")) {
180114
+ if (path36.isAbsolute(file3.relativePath) || file3.relativePath.includes("..")) {
179581
180115
  throw new Error(`Invalid file path: ${file3.relativePath}`);
179582
180116
  }
179583
- const dest = path34.resolve(stagingDir, file3.relativePath.replace(/\//g, path34.sep));
179584
- if (!dest.startsWith(stagingDir + path34.sep)) {
180117
+ const dest = path36.resolve(stagingDir, file3.relativePath.replace(/\//g, path36.sep));
180118
+ if (!dest.startsWith(stagingDir + path36.sep)) {
179585
180119
  throw new Error(`Path escapes staging directory: ${file3.relativePath}`);
179586
180120
  }
179587
- await fs22.mkdir(path34.dirname(dest), { recursive: true });
179588
- await fs22.writeFile(dest, file3.content, "utf-8");
180121
+ await fs23.mkdir(path36.dirname(dest), { recursive: true });
180122
+ await fs23.writeFile(dest, file3.content, "utf-8");
179589
180123
  }));
179590
180124
  }
179591
180125
  return await getIndexProjectTool().handle({
@@ -179739,9 +180273,9 @@ var analyticsRoutes = new Elysia({ prefix: "/api/v1/analytics" }).post("/", asyn
179739
180273
 
179740
180274
  // src/routes/system.ts
179741
180275
  init_dist();
179742
- import path35 from "path";
179743
- import fs23 from "fs";
179744
- import os7 from "os";
180276
+ import path37 from "path";
180277
+ import fs24 from "fs";
180278
+ import os9 from "os";
179745
180279
  function databaseUrlParts() {
179746
180280
  const url2 = new URL(process.env.DATABASE_URL);
179747
180281
  return {
@@ -179772,13 +180306,13 @@ var systemRoutes = new Elysia({ prefix: "/api/v1/system" }).get("/info", async (
179772
180306
  version: "1.0.0",
179773
180307
  service: "massa-ai-tools-api",
179774
180308
  node: process.version,
179775
- platform: os7.platform(),
179776
- arch: os7.arch(),
180309
+ platform: os9.platform(),
180310
+ arch: os9.arch(),
179777
180311
  uptime: process.uptime(),
179778
180312
  memory: {
179779
- total: os7.totalmem(),
179780
- free: os7.freemem(),
179781
- used: os7.totalmem() - os7.freemem(),
180313
+ total: os9.totalmem(),
180314
+ free: os9.freemem(),
180315
+ used: os9.totalmem() - os9.freemem(),
179782
180316
  process: process.memoryUsage()
179783
180317
  },
179784
180318
  dataDir: config.get("dataDir"),
@@ -179814,11 +180348,11 @@ var systemRoutes = new Elysia({ prefix: "/api/v1/system" }).get("/info", async (
179814
180348
  description: "Check PostgreSQL, pgvector, Ollama, and local artifact directory health"
179815
180349
  }
179816
180350
  }).get("/metrics", async () => {
179817
- const metricsPath = path35.join(process.cwd(), "data", "metrics.json");
180351
+ const metricsPath = path37.join(process.cwd(), "data", "metrics.json");
179818
180352
  let metrics2 = {};
179819
- if (fs23.existsSync(metricsPath)) {
180353
+ if (fs24.existsSync(metricsPath)) {
179820
180354
  try {
179821
- metrics2 = JSON.parse(fs23.readFileSync(metricsPath, "utf-8"));
180355
+ metrics2 = JSON.parse(fs24.readFileSync(metricsPath, "utf-8"));
179822
180356
  } catch {}
179823
180357
  }
179824
180358
  const database = await getDatabaseInfo();
@@ -179968,8 +180502,8 @@ var eventsRoutes = new Elysia({ prefix: "/api/v1" }).get("/events", async ({ que
179968
180502
  });
179969
180503
 
179970
180504
  // src/routes/workspace.ts
179971
- import fs24 from "fs/promises";
179972
- import path36 from "path";
180505
+ import fs25 from "fs/promises";
180506
+ import path38 from "path";
179973
180507
  import { realpathSync as realpathSync4 } from "fs";
179974
180508
  var indexProjectTool2 = null;
179975
180509
  function getIndexProjectTool2() {
@@ -180011,7 +180545,7 @@ function realpathSafe(p) {
180011
180545
  try {
180012
180546
  return realpathSync4(p);
180013
180547
  } catch {
180014
- return path36.resolve(p);
180548
+ return path38.resolve(p);
180015
180549
  }
180016
180550
  }
180017
180551
  var graphController = null;
@@ -180362,8 +180896,8 @@ var workspaceRoutes = new Elysia({ prefix: "/api/v1" }).get("/workspace/list", a
180362
180896
  }
180363
180897
  const registeredRoot = realpathSafe(workspace.project_path);
180364
180898
  const callerRoot = realpathSafe(projectPath2);
180365
- const rel = path36.relative(registeredRoot, callerRoot);
180366
- const escapes = rel.startsWith("..") || path36.isAbsolute(rel);
180899
+ const rel = path38.relative(registeredRoot, callerRoot);
180900
+ const escapes = rel.startsWith("..") || path38.isAbsolute(rel);
180367
180901
  if (registeredRoot !== callerRoot && escapes) {
180368
180902
  return {
180369
180903
  success: false,
@@ -180493,8 +181027,8 @@ var workspaceRoutes = new Elysia({ prefix: "/api/v1" }).get("/workspace/list", a
180493
181027
  } else {
180494
181028
  end = start + 20;
180495
181029
  }
180496
- const absolutePath = path36.join(workspace.project_path, file3);
180497
- const content = await fs24.readFile(absolutePath, "utf-8");
181030
+ const absolutePath = path38.join(workspace.project_path, file3);
181031
+ const content = await fs25.readFile(absolutePath, "utf-8");
180498
181032
  const lines = content.split(/\r?\n/);
180499
181033
  const slice = lines.slice(start - 1, Math.min(lines.length, end));
180500
181034
  const formatted = slice.map((text3, idx) => ({
@@ -181419,8 +181953,8 @@ var webRoutes = new Elysia({ prefix: "/api/v1/web" }).post("/fetch_and_index", a
181419
181953
  });
181420
181954
 
181421
181955
  // src/routes/web-ui.ts
181422
- import fs25 from "fs/promises";
181423
- import path37 from "path";
181956
+ import fs26 from "fs/promises";
181957
+ import path39 from "path";
181424
181958
  import { fileURLToPath as fileURLToPath3 } from "url";
181425
181959
 
181426
181960
  // src/web-ui-trust.ts
@@ -181464,9 +181998,9 @@ function buildStaticDirCandidates(moduleDir, cwd) {
181464
181998
  for (const root2 of [moduleDir, cwd]) {
181465
181999
  let dir = root2;
181466
182000
  for (let i = 0;i < 10; i++) {
181467
- candidates2.push(path37.resolve(dir, "apps/web-ui/src/static"));
181468
- candidates2.push(path37.resolve(dir, "web-ui/src/static"));
181469
- const parent = path37.dirname(dir);
182001
+ candidates2.push(path39.resolve(dir, "apps/web-ui/src/static"));
182002
+ candidates2.push(path39.resolve(dir, "web-ui/src/static"));
182003
+ const parent = path39.dirname(dir);
181470
182004
  if (parent === dir)
181471
182005
  break;
181472
182006
  dir = parent;
@@ -181474,11 +182008,11 @@ function buildStaticDirCandidates(moduleDir, cwd) {
181474
182008
  }
181475
182009
  return [...new Set(candidates2)];
181476
182010
  }
181477
- var STATIC_DIR_CANDIDATES = buildStaticDirCandidates(path37.dirname(fileURLToPath3(import.meta.url)), process.cwd());
182011
+ var STATIC_DIR_CANDIDATES = buildStaticDirCandidates(path39.dirname(fileURLToPath3(import.meta.url)), process.cwd());
181478
182012
  async function resolveStaticDir() {
181479
182013
  for (const dir of STATIC_DIR_CANDIDATES) {
181480
182014
  try {
181481
- const st = await fs25.stat(dir);
182015
+ const st = await fs26.stat(dir);
181482
182016
  if (st.isDirectory())
181483
182017
  return dir;
181484
182018
  } catch {}
@@ -181499,7 +182033,7 @@ var CONTENT_TYPES = {
181499
182033
  ".woff2": "font/woff2"
181500
182034
  };
181501
182035
  function contentTypeFor(filePath) {
181502
- const ext2 = path37.extname(filePath).toLowerCase();
182036
+ const ext2 = path39.extname(filePath).toLowerCase();
181503
182037
  return CONTENT_TYPES[ext2] ?? "application/octet-stream";
181504
182038
  }
181505
182039
  function webUiDisabled() {
@@ -181510,13 +182044,13 @@ function webUiDisabled() {
181510
182044
  }
181511
182045
  async function resolveSafePath(staticDir, sub) {
181512
182046
  const cleaned = sub.replace(/^\/+/, "");
181513
- const abs = path37.resolve(staticDir, cleaned);
181514
- const rel = path37.relative(staticDir, abs);
181515
- if (rel.startsWith("..") || path37.isAbsolute(rel)) {
182047
+ const abs = path39.resolve(staticDir, cleaned);
182048
+ const rel = path39.relative(staticDir, abs);
182049
+ if (rel.startsWith("..") || path39.isAbsolute(rel)) {
181516
182050
  return null;
181517
182051
  }
181518
182052
  try {
181519
- await fs25.stat(abs);
182053
+ await fs26.stat(abs);
181520
182054
  return { abs, exists: true };
181521
182055
  } catch {
181522
182056
  return { abs, exists: false };
@@ -181539,7 +182073,7 @@ function injectAccessMarkup(html, apiKey, trusted) {
181539
182073
  return out;
181540
182074
  }
181541
182075
  async function readShell(indexPath, remoteAddress) {
181542
- const raw2 = await fs25.readFile(indexPath, "utf-8");
182076
+ const raw2 = await fs26.readFile(indexPath, "utf-8");
181543
182077
  const trusted = isTrustedWebUiCaller(remoteAddress);
181544
182078
  return Buffer.from(injectAccessMarkup(raw2, getConfiguredApiKey(), trusted), "utf-8");
181545
182079
  }
@@ -181556,7 +182090,7 @@ var webUiRoutes = new Elysia().get("/ui", async ({ set: set3, request }) => {
181556
182090
  set3.status = 500;
181557
182091
  return { status: 500, error: "web ui static dir not found" };
181558
182092
  }
181559
- const indexPath = path37.join(dir, "index.html");
182093
+ const indexPath = path39.join(dir, "index.html");
181560
182094
  try {
181561
182095
  const body = await readShell(indexPath, remoteAddressOf(request));
181562
182096
  set3.headers["content-type"] = contentTypeFor(indexPath);
@@ -181589,7 +182123,7 @@ var webUiRoutes = new Elysia().get("/ui", async ({ set: set3, request }) => {
181589
182123
  }
181590
182124
  if (resolved.exists) {
181591
182125
  try {
181592
- const body = await fs25.readFile(resolved.abs);
182126
+ const body = await fs26.readFile(resolved.abs);
181593
182127
  set3.headers["content-type"] = contentTypeFor(resolved.abs);
181594
182128
  return body;
181595
182129
  } catch {
@@ -181598,7 +182132,7 @@ var webUiRoutes = new Elysia().get("/ui", async ({ set: set3, request }) => {
181598
182132
  }
181599
182133
  }
181600
182134
  try {
181601
- const body = await readShell(path37.join(dir, "index.html"), remoteAddressOf(request));
182135
+ const body = await readShell(path39.join(dir, "index.html"), remoteAddressOf(request));
181602
182136
  set3.headers["content-type"] = "text/html; charset=utf-8";
181603
182137
  return body;
181604
182138
  } catch {
@@ -181746,8 +182280,8 @@ init_dist();
181746
182280
 
181747
182281
  // src/routes/model-registry-deployment.ts
181748
182282
  init_dist();
181749
- import path38 from "path";
181750
- var MARKER = path38.join("scripts", "generate-subagent-artifacts.ts");
182283
+ import path40 from "path";
182284
+ var MARKER = path40.join("scripts", "generate-subagent-artifacts.ts");
181751
182285
  var MAX_LEVELS2 = 6;
181752
182286
  var cachedRoot;
181753
182287
  function findDeploymentRoot(startDir) {
@@ -181765,8 +182299,8 @@ function deploymentUnavailableMessage(what) {
181765
182299
 
181766
182300
  // src/routes/model-registry.ts
181767
182301
  init_config();
181768
- import fs26 from "fs";
181769
- import path39 from "path";
182302
+ import fs27 from "fs";
182303
+ import path41 from "path";
181770
182304
  import { spawnSync } from "child_process";
181771
182305
  var _profilesLib = null;
181772
182306
  function profilesLib() {
@@ -181775,7 +182309,7 @@ function profilesLib() {
181775
182309
  if (!root2) {
181776
182310
  throw new Error(deploymentUnavailableMessage("scripts/lib/model-profiles.ts"));
181777
182311
  }
181778
- const libPath = path39.join(root2, "scripts", "lib", "model-profiles.ts");
182312
+ const libPath = path41.join(root2, "scripts", "lib", "model-profiles.ts");
181779
182313
  _profilesLib = __require(libPath);
181780
182314
  }
181781
182315
  return _profilesLib;
@@ -181800,7 +182334,7 @@ function generatorLib() {
181800
182334
  if (!root2) {
181801
182335
  throw new Error(deploymentUnavailableMessage("scripts/generate-subagent-artifacts.ts"));
181802
182336
  }
181803
- const libPath = path39.join(root2, "scripts", "generate-subagent-artifacts.ts");
182337
+ const libPath = path41.join(root2, "scripts", "generate-subagent-artifacts.ts");
181804
182338
  _generatorLib = __require(libPath);
181805
182339
  }
181806
182340
  return _generatorLib;
@@ -181817,7 +182351,7 @@ async function loadAgentsInventory() {
181817
182351
  var REGISTRY_DETAIL = {
181818
182352
  tags: ["model-registry"]
181819
182353
  };
181820
- var OVERLAY_PATH = path39.join(configDir("massa-ai"), "model-profiles.json");
182354
+ var OVERLAY_PATH = path41.join(configDir("massa-ai"), "model-profiles.json");
181821
182355
  var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("/", async ({ set: set3 }) => {
181822
182356
  const root2 = getDeploymentRoot();
181823
182357
  if (!root2) {
@@ -181900,7 +182434,7 @@ var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("
181900
182434
  set3.status = 501;
181901
182435
  return { success: false, error: deploymentUnavailableMessage("scripts/generate-subagent-artifacts.ts") };
181902
182436
  }
181903
- const generateScript = path39.join(root2, "scripts", "generate-subagent-artifacts.ts");
182437
+ const generateScript = path41.join(root2, "scripts", "generate-subagent-artifacts.ts");
181904
182438
  try {
181905
182439
  const child = spawnSync("bun", [generateScript], {
181906
182440
  env: { ...process.env },
@@ -181939,8 +182473,8 @@ var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("
181939
182473
  }
181940
182474
  const lib = profilesLib();
181941
182475
  try {
181942
- if (fs26.existsSync(OVERLAY_PATH)) {
181943
- fs26.unlinkSync(OVERLAY_PATH);
182476
+ if (fs27.existsSync(OVERLAY_PATH)) {
182477
+ fs27.unlinkSync(OVERLAY_PATH);
181944
182478
  }
181945
182479
  const builtin = lib.loadRegistry(lib.DEFAULT_REGISTRY_PATH);
181946
182480
  set3.status = 200;
@@ -181966,17 +182500,17 @@ var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("
181966
182500
  }
181967
182501
  });
181968
182502
  function writeOverlayAtomically(overlayPath, data) {
181969
- const dir = path39.dirname(overlayPath);
181970
- if (!fs26.existsSync(dir)) {
181971
- fs26.mkdirSync(dir, { recursive: true });
182503
+ const dir = path41.dirname(overlayPath);
182504
+ if (!fs27.existsSync(dir)) {
182505
+ fs27.mkdirSync(dir, { recursive: true });
181972
182506
  }
181973
182507
  const tmp = `${overlayPath}.${process.pid}.${Date.now()}.tmp`;
181974
182508
  try {
181975
- fs26.writeFileSync(tmp, JSON.stringify(data, null, 2));
181976
- fs26.renameSync(tmp, overlayPath);
182509
+ fs27.writeFileSync(tmp, JSON.stringify(data, null, 2));
182510
+ fs27.renameSync(tmp, overlayPath);
181977
182511
  } catch (e) {
181978
182512
  try {
181979
- fs26.unlinkSync(tmp);
182513
+ fs27.unlinkSync(tmp);
181980
182514
  } catch {}
181981
182515
  throw e;
181982
182516
  }
@@ -182166,7 +182700,7 @@ var configRoutes = new Elysia({ prefix: "/api/v1/config" }).get("/", ({ set: set
182166
182700
  // src/routes/model-registry-stream.ts
182167
182701
  init_config();
182168
182702
  init_dist();
182169
- import path40 from "path";
182703
+ import path42 from "path";
182170
182704
  import { spawn as spawn3 } from "child_process";
182171
182705
  var encoder3 = new TextEncoder;
182172
182706
  function sseFrame(data) {
@@ -182248,7 +182782,7 @@ function createRegenerateStreamHandler() {
182248
182782
  closedRef.closed = true;
182249
182783
  return;
182250
182784
  }
182251
- const generateScript = path40.join(root2, "scripts", "generate-subagent-artifacts.ts");
182785
+ const generateScript = path42.join(root2, "scripts", "generate-subagent-artifacts.ts");
182252
182786
  try {
182253
182787
  child = spawn3("bun", [generateScript], {
182254
182788
  env: { ...process.env },
@@ -182440,13 +182974,390 @@ var restartRoutes = new Elysia({ prefix: "/api/v1/system" }).onAfterResponse(()
182440
182974
  }
182441
182975
  });
182442
182976
 
182977
+ // src/routes/logs.ts
182978
+ init_dist();
182979
+ import fs28 from "fs";
182980
+ var LOGS_DETAIL = { tags: ["logs"] };
182981
+ var MAX_SCAN_BYTES = 64 * 1024 * 1024;
182982
+ var MAX_LIMIT = 1000;
182983
+ var DEFAULT_LIMIT = 200;
182984
+ function isQueryValidationError(v) {
182985
+ return "param" in v;
182986
+ }
182987
+ function parseRangeQuery(query) {
182988
+ const fromRaw = query.from;
182989
+ const toRaw = query.to;
182990
+ const fromMs = fromRaw !== undefined ? Date.parse(fromRaw) : -Infinity;
182991
+ if (fromRaw !== undefined && Number.isNaN(fromMs)) {
182992
+ return { param: "from", message: `"from" is not a parseable ISO-8601 timestamp: "${fromRaw}"` };
182993
+ }
182994
+ const toMs = toRaw !== undefined ? Date.parse(toRaw) : Infinity;
182995
+ if (toRaw !== undefined && Number.isNaN(toMs)) {
182996
+ return { param: "to", message: `"to" is not a parseable ISO-8601 timestamp: "${toRaw}"` };
182997
+ }
182998
+ if (fromMs > toMs) {
182999
+ return { param: "from", message: `"from" (${fromRaw}) is after "to" (${toRaw})` };
183000
+ }
183001
+ let limit = DEFAULT_LIMIT;
183002
+ if (query.limit !== undefined) {
183003
+ const n2 = Number(query.limit);
183004
+ if (!Number.isFinite(n2) || n2 < 0) {
183005
+ return { param: "limit", message: `"limit" must be a non-negative number: "${query.limit}"` };
183006
+ }
183007
+ if (n2 > MAX_LIMIT) {
183008
+ return { param: "limit", message: `"limit" exceeds the maximum of ${MAX_LIMIT}: "${query.limit}"` };
183009
+ }
183010
+ limit = Math.floor(n2);
183011
+ }
183012
+ let offset = 0;
183013
+ if (query.offset !== undefined) {
183014
+ const n2 = Number(query.offset);
183015
+ if (!Number.isFinite(n2) || n2 < 0) {
183016
+ return { param: "offset", message: `"offset" must be a non-negative number: "${query.offset}"` };
183017
+ }
183018
+ offset = Math.floor(n2);
183019
+ }
183020
+ return { fromMs, toMs, fromRaw, toRaw, level: query.level, q: query.q, limit, offset };
183021
+ }
183022
+ var LINE_RE = /^\[(?<ts>[^\]]+)\] \[(?<level>[A-Z]+)\] (?<rest>[\s\S]*)$/;
183023
+ function normalizeLevel(raw2) {
183024
+ const lower2 = raw2.toLowerCase();
183025
+ return lower2 === "debug" || lower2 === "info" || lower2 === "warn" || lower2 === "error" ? lower2 : "raw";
183026
+ }
183027
+ function splitMessageAndMeta(rest) {
183028
+ if (!rest.endsWith("}"))
183029
+ return { message: rest };
183030
+ let searchFrom = rest.length;
183031
+ for (;; ) {
183032
+ const idx = rest.lastIndexOf(" {", searchFrom - 1);
183033
+ if (idx === -1)
183034
+ break;
183035
+ const candidate2 = rest.slice(idx + 1);
183036
+ try {
183037
+ const parsed = JSON.parse(candidate2);
183038
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
183039
+ return { message: rest.slice(0, idx), meta: parsed };
183040
+ }
183041
+ } catch {}
183042
+ searchFrom = idx;
183043
+ }
183044
+ return { message: rest };
183045
+ }
183046
+ function parseLine(line, prevTs) {
183047
+ const match2 = LINE_RE.exec(line);
183048
+ if (!match2 || !match2.groups) {
183049
+ return { entry: { seq: 0, ts: prevTs, level: "raw", message: line }, ts: prevTs };
183050
+ }
183051
+ const { ts, level, rest } = match2.groups;
183052
+ const { message, meta: meta3 } = splitMessageAndMeta(rest);
183053
+ const entry2 = { seq: 0, ts, level: normalizeLevel(level), message, ...meta3 ? { meta: meta3 } : {} };
183054
+ return { entry: entry2, ts };
183055
+ }
183056
+ function realReadTail(filePath, maxBytes) {
183057
+ let size;
183058
+ try {
183059
+ size = fs28.statSync(filePath).size;
183060
+ } catch {
183061
+ return { content: "", truncated: false };
183062
+ }
183063
+ if (size === 0)
183064
+ return { content: "", truncated: false };
183065
+ if (size <= maxBytes) {
183066
+ try {
183067
+ return { content: fs28.readFileSync(filePath, "utf8"), truncated: false };
183068
+ } catch {
183069
+ return { content: "", truncated: false };
183070
+ }
183071
+ }
183072
+ try {
183073
+ const fd = fs28.openSync(filePath, "r");
183074
+ try {
183075
+ const start = size - maxBytes;
183076
+ const buf = Buffer.alloc(maxBytes);
183077
+ fs28.readSync(fd, buf, 0, maxBytes, start);
183078
+ let text3 = buf.toString("utf8");
183079
+ const firstNewline = text3.indexOf(`
183080
+ `);
183081
+ text3 = firstNewline !== -1 ? text3.slice(firstNewline + 1) : "";
183082
+ return { content: text3, truncated: true };
183083
+ } finally {
183084
+ fs28.closeSync(fd);
183085
+ }
183086
+ } catch {
183087
+ return { content: "", truncated: true };
183088
+ }
183089
+ }
183090
+ var realReader = {
183091
+ listFiles(filePath, maxFiles) {
183092
+ return sinkFiles(filePath, maxFiles).filter((f) => {
183093
+ try {
183094
+ fs28.accessSync(f, fs28.constants.R_OK);
183095
+ return true;
183096
+ } catch {
183097
+ return false;
183098
+ }
183099
+ });
183100
+ },
183101
+ readTail: realReadTail
183102
+ };
183103
+ var activeReader = realReader;
183104
+ function scanEntries() {
183105
+ const loggingConfig = config.get("logging");
183106
+ const filePath = loggingConfig.file;
183107
+ const files = filePath ? activeReader.listFiles(filePath, loggingConfig.maxFiles) : [];
183108
+ if (files.length === 0) {
183109
+ return { entries: logBuffer.snapshot(), source: "buffer", truncated: false };
183110
+ }
183111
+ const readFiles = [];
183112
+ let budgetLeft = MAX_SCAN_BYTES;
183113
+ let truncated = false;
183114
+ for (const file3 of files) {
183115
+ if (budgetLeft <= 0) {
183116
+ truncated = true;
183117
+ break;
183118
+ }
183119
+ const { content, truncated: fileTruncated } = activeReader.readTail(file3, budgetLeft);
183120
+ if (fileTruncated)
183121
+ truncated = true;
183122
+ readFiles.push(content);
183123
+ budgetLeft -= Buffer.byteLength(content, "utf8");
183124
+ if (fileTruncated)
183125
+ break;
183126
+ }
183127
+ let prevTs = new Date().toISOString();
183128
+ const chronoEntries = [];
183129
+ for (let i = readFiles.length - 1;i >= 0; i--) {
183130
+ const lines = readFiles[i].split(`
183131
+ `).filter((l2) => l2.length > 0);
183132
+ for (const line of lines) {
183133
+ const { entry: entry2, ts } = parseLine(line, prevTs);
183134
+ prevTs = ts;
183135
+ chronoEntries.push(entry2);
183136
+ }
183137
+ }
183138
+ const entries = chronoEntries.reverse();
183139
+ for (let i = 0;i < entries.length; i++) {
183140
+ entries[i].seq = entries.length - 1 - i;
183141
+ }
183142
+ return { entries, source: "file", truncated };
183143
+ }
183144
+ function matchesFilter(entry2, parsed) {
183145
+ const tsMs = Date.parse(entry2.ts);
183146
+ if (Number.isNaN(tsMs) || tsMs < parsed.fromMs || tsMs > parsed.toMs)
183147
+ return false;
183148
+ if (parsed.level !== undefined && entry2.level !== parsed.level)
183149
+ return false;
183150
+ if (parsed.q !== undefined && !entry2.message.toLowerCase().includes(parsed.q.toLowerCase()))
183151
+ return false;
183152
+ return true;
183153
+ }
183154
+ function filteredEntries(parsed) {
183155
+ const scan = scanEntries();
183156
+ return { ...scan, entries: scan.entries.filter((e) => matchesFilter(e, parsed)) };
183157
+ }
183158
+ function sanitizeForFilename(s) {
183159
+ return s.replace(/[^A-Za-z0-9._-]/g, "-");
183160
+ }
183161
+ function exportFilename(parsed, ext2) {
183162
+ const fromPart = sanitizeForFilename(parsed.fromRaw ?? "all");
183163
+ const toPart = sanitizeForFilename(parsed.toRaw ?? "all");
183164
+ return `massa-ai-logs-${fromPart}_${toPart}.${ext2}`;
183165
+ }
183166
+ function renderTxtLine(entry2) {
183167
+ const metaStr = entry2.meta ? ` ${JSON.stringify(entry2.meta)}` : "";
183168
+ return `[${entry2.ts}] [${entry2.level.toUpperCase()}] ${entry2.message}${metaStr}`;
183169
+ }
183170
+ var SSE_HEARTBEAT_MS_DEFAULT = 15000;
183171
+ var SSE_MAX_DURATION_MS_DEFAULT = 10 * 60 * 1000;
183172
+ var SINK_POLL_MS_DEFAULT = 1000;
183173
+ var SINK_POLL_MAX_BYTES = 1024 * 1024;
183174
+ function startSinkTail(enqueue) {
183175
+ const loggingConfig = config.get("logging");
183176
+ const filePath = loggingConfig.file;
183177
+ if (!filePath)
183178
+ return;
183179
+ const initial = activeReader.listFiles(filePath, loggingConfig.maxFiles);
183180
+ if (initial.length === 0)
183181
+ return;
183182
+ let currentFile = initial[0];
183183
+ let offset;
183184
+ try {
183185
+ offset = fs28.statSync(currentFile).size;
183186
+ } catch {
183187
+ return;
183188
+ }
183189
+ let carry = "";
183190
+ let prevTs = new Date().toISOString();
183191
+ let seq = 0;
183192
+ const pollMs = Number(process.env.MASSA_AI_SSE_SINK_POLL_MS) || SINK_POLL_MS_DEFAULT;
183193
+ const timer = setInterval(() => {
183194
+ try {
183195
+ const newest = activeReader.listFiles(filePath, loggingConfig.maxFiles)[0];
183196
+ if (newest && newest !== currentFile) {
183197
+ currentFile = newest;
183198
+ offset = 0;
183199
+ carry = "";
183200
+ }
183201
+ const size = fs28.statSync(currentFile).size;
183202
+ if (size < offset) {
183203
+ offset = 0;
183204
+ carry = "";
183205
+ }
183206
+ if (size === offset)
183207
+ return;
183208
+ const length = Math.min(size - offset, SINK_POLL_MAX_BYTES);
183209
+ const buf = Buffer.alloc(length);
183210
+ const fd = fs28.openSync(currentFile, "r");
183211
+ try {
183212
+ fs28.readSync(fd, buf, 0, length, offset);
183213
+ } finally {
183214
+ fs28.closeSync(fd);
183215
+ }
183216
+ offset += length;
183217
+ const text3 = carry + buf.toString("utf8");
183218
+ const lines = text3.split(`
183219
+ `);
183220
+ carry = lines.pop() ?? "";
183221
+ for (const line of lines) {
183222
+ if (line.trim() === "")
183223
+ continue;
183224
+ const parsed = parseLine(line, prevTs);
183225
+ prevTs = parsed.ts;
183226
+ enqueue({ ...parsed.entry, seq: ++seq });
183227
+ }
183228
+ } catch {}
183229
+ }, pollMs);
183230
+ timer.unref?.();
183231
+ return () => clearInterval(timer);
183232
+ }
183233
+ var logsRoutes = new Elysia({ prefix: "/api/v1/logs" }).get("/", ({ query, set: set3 }) => {
183234
+ const parsed = parseRangeQuery(query);
183235
+ if (isQueryValidationError(parsed)) {
183236
+ set3.status = 400;
183237
+ return { success: false, error: `invalid "${parsed.param}": ${parsed.message}` };
183238
+ }
183239
+ const { entries, source, truncated } = filteredEntries(parsed);
183240
+ const total = entries.length;
183241
+ const page = entries.slice(parsed.offset, parsed.offset + parsed.limit);
183242
+ set3.status = 200;
183243
+ return { success: true, data: { entries: page, total, source, truncated } };
183244
+ }, {
183245
+ detail: {
183246
+ ...LOGS_DETAIL,
183247
+ summary: "Range/level/substring query over the log sink (or the ring buffer)",
183248
+ description: 'Query params: from, to (ISO-8601, closed interval), level, q (substring), limit (<=1000), offset. Reads the file sink newest-first within a 64 MB scan bound (truncated:true if the bound was hit); falls back to the in-process ring buffer (source:"buffer") when no sink file is present or readable. Validates from/to/limit before any read.'
183249
+ }
183250
+ }).get("/export", ({ query, set: set3 }) => {
183251
+ const parsed = parseRangeQuery(query);
183252
+ if (isQueryValidationError(parsed)) {
183253
+ set3.status = 400;
183254
+ return { success: false, error: `invalid "${parsed.param}": ${parsed.message}` };
183255
+ }
183256
+ const { entries } = filteredEntries(parsed);
183257
+ const format = query.format === "txt" ? "txt" : "jsonl";
183258
+ const ext2 = format === "txt" ? "txt" : "jsonl";
183259
+ const contentType = format === "txt" ? "text/plain" : "application/x-ndjson";
183260
+ const body = format === "txt" ? entries.map(renderTxtLine).join(`
183261
+ `) : entries.map((e) => JSON.stringify(e)).join(`
183262
+ `);
183263
+ const filename = exportFilename(parsed, ext2);
183264
+ return new Response(body, {
183265
+ status: 200,
183266
+ headers: {
183267
+ "Content-Type": contentType,
183268
+ "Content-Disposition": `attachment; filename="${filename}"`
183269
+ }
183270
+ });
183271
+ }, {
183272
+ detail: {
183273
+ ...LOGS_DETAIL,
183274
+ summary: "Download the queried log range as jsonl or txt",
183275
+ description: "Same query surface as GET /api/v1/logs (minus limit/offset \u2014 the full matching range is returned) plus format=jsonl|txt. Responds with Content-Disposition: attachment and a filename carrying the range. A range matching zero entries still returns an empty (200) download."
183276
+ }
183277
+ }).get("/stream", () => {
183278
+ const HEARTBEAT_MS = Number(process.env.MASSA_AI_SSE_HEARTBEAT_MS) || SSE_HEARTBEAT_MS_DEFAULT;
183279
+ const MAX_DURATION_MS = Number(process.env.MASSA_AI_SSE_MAX_DURATION_MS) || SSE_MAX_DURATION_MS_DEFAULT;
183280
+ const encoder4 = new TextEncoder;
183281
+ let closed = false;
183282
+ let unsubscribe;
183283
+ let heartbeatTimer;
183284
+ let closeTimer;
183285
+ const stream2 = new ReadableStream({
183286
+ start(controller2) {
183287
+ const enqueue = (data) => {
183288
+ if (closed)
183289
+ return;
183290
+ try {
183291
+ controller2.enqueue(encoder4.encode(`data: ${JSON.stringify(data)}
183292
+
183293
+ `));
183294
+ } catch {
183295
+ closed = true;
183296
+ }
183297
+ };
183298
+ const tail = startSinkTail(enqueue);
183299
+ if (tail) {
183300
+ unsubscribe = tail;
183301
+ } else {
183302
+ unsubscribe = logBuffer.subscribe((entry2) => {
183303
+ enqueue(entry2);
183304
+ });
183305
+ }
183306
+ heartbeatTimer = setInterval(() => {
183307
+ if (closed) {
183308
+ clearInterval(heartbeatTimer);
183309
+ return;
183310
+ }
183311
+ try {
183312
+ controller2.enqueue(encoder4.encode(`: heartbeat
183313
+
183314
+ `));
183315
+ } catch {
183316
+ closed = true;
183317
+ clearInterval(heartbeatTimer);
183318
+ }
183319
+ }, HEARTBEAT_MS);
183320
+ closeTimer = setTimeout(() => {
183321
+ closed = true;
183322
+ unsubscribe?.();
183323
+ clearInterval(heartbeatTimer);
183324
+ try {
183325
+ controller2.close();
183326
+ } catch {}
183327
+ }, MAX_DURATION_MS);
183328
+ },
183329
+ cancel() {
183330
+ closed = true;
183331
+ unsubscribe?.();
183332
+ if (heartbeatTimer)
183333
+ clearInterval(heartbeatTimer);
183334
+ if (closeTimer)
183335
+ clearTimeout(closeTimer);
183336
+ }
183337
+ });
183338
+ return new Response(stream2, {
183339
+ headers: {
183340
+ "Content-Type": "text/event-stream",
183341
+ "Cache-Control": "no-cache",
183342
+ Connection: "keep-alive",
183343
+ "X-Accel-Buffering": "no"
183344
+ }
183345
+ });
183346
+ }, {
183347
+ detail: {
183348
+ ...LOGS_DETAIL,
183349
+ summary: "SSE tail of newly buffered log entries",
183350
+ description: "Server-Sent Events stream emitting `data: <LogEntry JSON>` for every entry subsequently pushed into the in-process ring buffer, plus `: heartbeat` comments. Same heartbeat and max-duration auto-close behavior as GET /api/v1/events. Scoped to this server process \u2014 a separate range query over the file sink may contain entries this stream never showed (e.g. from the stdio MCP server)."
183351
+ }
183352
+ });
183353
+
182443
183354
  // src/middleware/error.ts
182444
183355
  init_dist();
182445
- var errorHandler = new Elysia({ name: "error-handler" }).onError(({ code, error: error51, set: set3, path: path41, request }) => {
183356
+ var errorHandler = new Elysia({ name: "error-handler" }).onError(({ code, error: error51, set: set3, path: path43, request }) => {
182446
183357
  logger.error("[massa-ai-api] Request failed", undefined, {
182447
183358
  ...safeErrorSummary(error51),
182448
183359
  code,
182449
- path: path41,
183360
+ path: path43,
182450
183361
  method: request.method
182451
183362
  });
182452
183363
  if (error51 instanceof SearchServiceError) {
@@ -182548,7 +183459,8 @@ var app = new Elysia({ adapter: node() }).use(cors(buildCorsOptions(config.get("
182548
183459
  { name: "executor", description: "Polyglot sandbox: execute code, run code over files, batch shell commands" },
182549
183460
  { name: "web", description: "SSRF-guarded web fetch + HTML\u2192md + index (fetch_and_index)" },
182550
183461
  { name: "webUi", description: "Read-only memory/search web browser (Phase 8)" },
182551
- { name: "profiles", description: "Model-profile switch: list shipped profiles, switch installed agents" }
183462
+ { name: "profiles", description: "Model-profile switch: list shipped profiles, switch installed agents" },
183463
+ { name: "logs", description: "Log read: range/level/substring query, export, live SSE tail" }
182552
183464
  ],
182553
183465
  components: {
182554
183466
  securitySchemes: {
@@ -182562,15 +183474,26 @@ var app = new Elysia({ adapter: node() }).use(cors(buildCorsOptions(config.get("
182562
183474
  },
182563
183475
  security: [{ ApiKeyAuth: [] }]
182564
183476
  }
182565
- })).use(errorHandler).use(authMiddleware).use(searchRoutes).use(memoryRoutes).use(checkpointRoutes).use(projectRoutes).use(contextRoutes).use(analyticsRoutes).use(systemRoutes).use(eventsRoutes).use(workspaceRoutes).use(fileRoutes).use(synapseRoutes).use(hookRoutes).use(bootstrapRoutes).use(handoffRoutes).use(proposalRoutes).use(executorRoutes).use(webRoutes).use(webUiRoutes).use(architectureRoutes).use(dashboardRoutes).use(profileRoutes).use(configRoutes).use(modelRegistryRoutes).use(modelRegistryStreamRoutes).use(restartRoutes).get("/health", () => buildHealthResponse(getParserReadiness()));
183477
+ })).use(errorHandler).use(authMiddleware).use(searchRoutes).use(memoryRoutes).use(checkpointRoutes).use(projectRoutes).use(contextRoutes).use(analyticsRoutes).use(systemRoutes).use(eventsRoutes).use(workspaceRoutes).use(fileRoutes).use(synapseRoutes).use(hookRoutes).use(bootstrapRoutes).use(handoffRoutes).use(proposalRoutes).use(executorRoutes).use(webRoutes).use(webUiRoutes).use(architectureRoutes).use(dashboardRoutes).use(profileRoutes).use(configRoutes).use(modelRegistryRoutes).use(modelRegistryStreamRoutes).use(restartRoutes).use(logsRoutes).get("/health", () => buildHealthResponse(getParserReadiness()));
182566
183478
  initAuthOrExit();
182567
183479
  warnIfTrustOverrideEnabled();
182568
183480
  await listenAfterParserValidation({
182569
183481
  validate: validateAllGrammars,
182570
183482
  listen: () => {
182571
- app.listen(PORT, (server) => {
182572
- setServerStopper(() => void server.stop());
182573
- });
183483
+ try {
183484
+ app.listen({ port: Number(PORT), reusePort: false }, (server) => {
183485
+ setServerStopper(() => void server.stop());
183486
+ });
183487
+ } catch (error51) {
183488
+ if (error51?.code === "EADDRINUSE") {
183489
+ console.error(`Port ${PORT} is already in use \u2014 another massa-ai Tools API is running.
183490
+ ` + `Stop it first, or start this one on another port:
183491
+ ` + ` lsof -nP -iTCP:${PORT} -sTCP:LISTEN
183492
+ ` + ` MASSA_AI_API_PORT=<other> bun run dev:api`);
183493
+ process.exit(1);
183494
+ }
183495
+ throw error51;
183496
+ }
182574
183497
  },
182575
183498
  onValidationFailure: (error51) => {
182576
183499
  console.error("Structural parser readiness failed; indexing is unavailable:", error51 instanceof Error ? error51.message : error51);