@massa-ai/tools-api 1.46.0 → 1.47.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 +1296 -533
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -401,9 +401,16 @@ 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, 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
+ ];
407
414
  defaultMassaAiConfig = {
408
415
  database: {
409
416
  url: ""
@@ -759,6 +766,8 @@ function restartNeededSections(config) {
759
766
  return config.llm !== undefined;
760
767
  if (s === "security")
761
768
  return config.security !== undefined;
769
+ if (s === "scheduler")
770
+ return config.scheduler !== undefined;
762
771
  return false;
763
772
  });
764
773
  }
@@ -1007,6 +1016,29 @@ function validatePartial(partial) {
1007
1016
  details.push("security.allowedExtensions[] must be dot-prefixed extensions");
1008
1017
  }
1009
1018
  }
1019
+ if (partial.scheduler !== undefined) {
1020
+ const sch = partial.scheduler;
1021
+ if (sch.enabled !== undefined && !checkBoolean(sch.enabled))
1022
+ details.push("scheduler.enabled must be a boolean");
1023
+ if (sch.tickMs !== undefined && !checkNumber(sch.tickMs, 1000))
1024
+ details.push("scheduler.tickMs must be a number >= 1000");
1025
+ if (sch.maxConcurrent !== undefined && !checkNumber(sch.maxConcurrent, 1))
1026
+ details.push("scheduler.maxConcurrent must be a number >= 1");
1027
+ if (sch.jobs !== undefined) {
1028
+ for (const [kind, job] of Object.entries(sch.jobs)) {
1029
+ if (!SCHEDULER_JOB_KINDS.includes(kind)) {
1030
+ details.push(`scheduler.jobs.${kind} is not a registered job kind (expected one of: ${SCHEDULER_JOB_KINDS.join(", ")})`);
1031
+ continue;
1032
+ }
1033
+ if (job === undefined || job === null)
1034
+ continue;
1035
+ if (job.enabled !== undefined && !checkBoolean(job.enabled))
1036
+ details.push(`scheduler.jobs.${kind}.enabled must be a boolean`);
1037
+ if (job.intervalMs !== undefined && !checkNumber(job.intervalMs, 60000))
1038
+ details.push(`scheduler.jobs.${kind}.intervalMs must be a number >= 60000`);
1039
+ }
1040
+ }
1041
+ }
1010
1042
  return details;
1011
1043
  }
1012
1044
  function repairAndPruneBackups(configPath) {
@@ -1067,7 +1099,8 @@ function savePartialConfig(partial) {
1067
1099
  var MASK_SENTINEL = "***", RESTART_SECTIONS, VALID_EMBEDDING_PROVIDERS, VALID_LOG_LEVELS, BACKUP_RETENTION_LIMIT = 10;
1068
1100
  var init_config_writer = __esm(() => {
1069
1101
  init_config_loader();
1070
- RESTART_SECTIONS = ["database", "embedding", "llm", "security"];
1102
+ init_massa_ai_config();
1103
+ RESTART_SECTIONS = ["database", "embedding", "llm", "security", "scheduler"];
1071
1104
  VALID_EMBEDDING_PROVIDERS = ["ollama", "mistral", "openai", "google", "cohere"];
1072
1105
  VALID_LOG_LEVELS = ["debug", "info", "warn", "error"];
1073
1106
  });
@@ -1241,6 +1274,22 @@ function envList(key, fallback) {
1241
1274
  const parsed = s.split(",").map((v) => v.trim()).filter((v) => v.length > 0);
1242
1275
  return parsed.length > 0 ? parsed : fallback;
1243
1276
  }
1277
+ function readSchedulerConfig(rawFileConfig) {
1278
+ try {
1279
+ const cfg = rawFileConfig;
1280
+ return cfg?.scheduler ?? {};
1281
+ } catch {
1282
+ return {};
1283
+ }
1284
+ }
1285
+ function resolveSchedulerJob(kind, fileJobs) {
1286
+ const meta = SCHEDULER_JOB_ENV[kind];
1287
+ const fileJob = fileJobs?.[kind];
1288
+ return {
1289
+ enabled: envBool(meta.enabledVar, fileJob?.enabled ?? false),
1290
+ intervalMs: envNum(meta.intervalVar, fileJob?.intervalMs ?? meta.defaultIntervalMs)
1291
+ };
1292
+ }
1244
1293
  function validateCapturePolicyConfig(raw2) {
1245
1294
  if (!raw2 || typeof raw2 !== "object")
1246
1295
  throw new TypeError("capturePolicy must be an object");
@@ -1368,6 +1417,11 @@ class Config {
1368
1417
  rateLimit: { ...defaults.rateLimit, ...overrides.rateLimit },
1369
1418
  security: { ...defaults.security, ...overrides.security },
1370
1419
  logging: { ...defaults.logging, ...overrides.logging },
1420
+ scheduler: {
1421
+ ...defaults.scheduler,
1422
+ ...overrides.scheduler,
1423
+ jobs: { ...defaults.scheduler.jobs, ...overrides.scheduler?.jobs }
1424
+ },
1371
1425
  synapse: {
1372
1426
  ...defaults.synapse,
1373
1427
  ...overrides.synapse,
@@ -1436,15 +1490,43 @@ class Config {
1436
1490
  this.config[key] = value;
1437
1491
  }
1438
1492
  }
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;
1493
+ var DEFAULT_LLM_MODEL = "qwen2.5:7b-instruct", DEFAULT_LLM_CODE_MODEL = "qwen2.5-coder:7b", SCHEDULER_JOB_ENV, MAX_IGNORE_PATTERNS = 1024, DEFAULT_ALLOWED_EXTENSIONS, fileConfig, fileCacheL1Bytes, fileCacheL2Bytes, resolvedDataDir, defaultConfig, config;
1440
1494
  var init_config = __esm(() => {
1441
1495
  init_env();
1442
1496
  init_config_loader();
1443
1497
  init_massa_ai_config();
1498
+ init_massa_ai_config();
1444
1499
  init_config_loader();
1445
1500
  init_config_writer();
1446
1501
  init_xdg();
1447
1502
  init_api_key();
1503
+ SCHEDULER_JOB_ENV = {
1504
+ "memory-consolidation": {
1505
+ enabledVar: "MASSA_AI_SCHEDULER_CONSOLIDATION_ENABLED",
1506
+ intervalVar: "MASSA_AI_SCHEDULER_CONSOLIDATION_INTERVAL_MS",
1507
+ defaultIntervalMs: 30 * 60 * 1000
1508
+ },
1509
+ "decay-sweep": {
1510
+ enabledVar: "MASSA_AI_SCHEDULER_DECAY_ENABLED",
1511
+ intervalVar: "MASSA_AI_SCHEDULER_DECAY_INTERVAL_MS",
1512
+ defaultIntervalMs: 60 * 60 * 1000
1513
+ },
1514
+ "auto-improve": {
1515
+ enabledVar: "MASSA_AI_SCHEDULER_AUTO_IMPROVE_ENABLED",
1516
+ intervalVar: "MASSA_AI_SCHEDULER_AUTO_IMPROVE_INTERVAL_MS",
1517
+ defaultIntervalMs: 30 * 60 * 1000
1518
+ },
1519
+ "observation-bridge": {
1520
+ enabledVar: "MASSA_AI_SCHEDULER_OBSERVATION_BRIDGE_ENABLED",
1521
+ intervalVar: "MASSA_AI_SCHEDULER_OBSERVATION_BRIDGE_INTERVAL_MS",
1522
+ defaultIntervalMs: 30 * 60 * 1000
1523
+ },
1524
+ "checkpoint-purge": {
1525
+ enabledVar: "MASSA_AI_SCHEDULER_CHECKPOINT_PURGE_ENABLED",
1526
+ intervalVar: "MASSA_AI_SCHEDULER_CHECKPOINT_PURGE_INTERVAL_MS",
1527
+ defaultIntervalMs: 60 * 60 * 1000
1528
+ }
1529
+ };
1448
1530
  DEFAULT_ALLOWED_EXTENSIONS = [
1449
1531
  ".ts",
1450
1532
  ".js",
@@ -1483,10 +1565,11 @@ var init_config = __esm(() => {
1483
1565
  fileConfig = loadConfigSafe();
1484
1566
  fileCacheL1Bytes = fileConfig.cache?.l1MaxSizeMB ? fileConfig.cache.l1MaxSizeMB * 1024 * 1024 : undefined;
1485
1567
  fileCacheL2Bytes = fileConfig.cache?.l2MaxSizeMB ? fileConfig.cache.l2MaxSizeMB * 1024 * 1024 : undefined;
1568
+ resolvedDataDir = getGlobalDataDir();
1486
1569
  defaultConfig = {
1487
1570
  name: "massa-ai-server",
1488
1571
  version: "1.0.0",
1489
- dataDir: getGlobalDataDir(),
1572
+ dataDir: resolvedDataDir,
1490
1573
  cache: {
1491
1574
  l1: {
1492
1575
  maxSize: envNum("L1_CACHE_MAX_SIZE", fileCacheL1Bytes ?? 100 * 1024 * 1024),
@@ -1610,8 +1693,24 @@ var init_config = __esm(() => {
1610
1693
  logging: {
1611
1694
  level: process.env.LOG_LEVEL || fileConfig.logging?.level || "info",
1612
1695
  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
- },
1696
+ file: process.env.MASSA_AI_LOG_FILE || fileConfig.logging?.file || path6.join(resolvedDataDir, "logs", "massa-ai.log"),
1697
+ enableFileSink: envBool("MASSA_AI_LOG_ENABLE_FILE_SINK", fileConfig.logging?.enableFileSink ?? true),
1698
+ bufferSize: envNum("MASSA_AI_LOG_BUFFER_SIZE", fileConfig.logging?.bufferSize ?? 2000),
1699
+ maxFileSizeMb: envNum("MASSA_AI_LOG_MAX_FILE_SIZE_MB", fileConfig.logging?.maxFileSizeMb ?? 32),
1700
+ maxFiles: envNum("MASSA_AI_LOG_MAX_FILES", fileConfig.logging?.maxFiles ?? 5)
1701
+ },
1702
+ scheduler: (() => {
1703
+ const fileScheduler = readSchedulerConfig(fileConfig);
1704
+ return {
1705
+ enabled: envBool("MASSA_AI_SCHEDULER_ENABLED", fileScheduler.enabled ?? false),
1706
+ tickMs: envNum("MASSA_AI_SCHEDULER_TICK_MS", fileScheduler.tickMs ?? 60000),
1707
+ maxConcurrent: envNum("MASSA_AI_SCHEDULER_MAX_CONCURRENT", fileScheduler.maxConcurrent ?? 2),
1708
+ jobs: Object.fromEntries(SCHEDULER_JOB_KINDS.map((kind) => [
1709
+ kind,
1710
+ resolveSchedulerJob(kind, fileScheduler.jobs)
1711
+ ]))
1712
+ };
1713
+ })(),
1615
1714
  synapse: {
1616
1715
  enabled: process.env.SYNAPSE_ENABLED !== "false",
1617
1716
  inhibition: {
@@ -6948,13 +7047,190 @@ var init_types = __esm(() => {
6948
7047
  // ../../packages/shared/dist/types/interfaces.js
6949
7048
  var init_interfaces = () => {};
6950
7049
 
6951
- // ../../packages/shared/dist/utils/logger.js
7050
+ // ../../packages/shared/dist/utils/log-sink.js
6952
7051
  import fs4 from "fs";
7052
+ import path7 from "path";
7053
+ function getState(filePath) {
7054
+ let state = pathState.get(filePath);
7055
+ if (!state) {
7056
+ state = { trackedSize: 0, deltaSinceStat: 0, primed: false };
7057
+ pathState.set(filePath, state);
7058
+ }
7059
+ return state;
7060
+ }
7061
+ function ensureDir(filePath) {
7062
+ const dir = path7.dirname(filePath);
7063
+ if (ensuredDirs.has(dir))
7064
+ return;
7065
+ fs4.mkdirSync(dir, { recursive: true });
7066
+ ensuredDirs.add(dir);
7067
+ }
7068
+ function restat(filePath, state) {
7069
+ try {
7070
+ state.trackedSize = fs4.statSync(filePath).size;
7071
+ } catch {
7072
+ state.trackedSize = 0;
7073
+ }
7074
+ state.deltaSinceStat = 0;
7075
+ state.primed = true;
7076
+ }
7077
+ function rotate(filePath, maxFiles) {
7078
+ if (maxFiles <= 0) {
7079
+ if (fs4.existsSync(filePath))
7080
+ fs4.unlinkSync(filePath);
7081
+ return;
7082
+ }
7083
+ const oldest = `${filePath}.${maxFiles}`;
7084
+ if (fs4.existsSync(oldest))
7085
+ fs4.unlinkSync(oldest);
7086
+ for (let n2 = maxFiles - 1;n2 >= 1; n2--) {
7087
+ const src = `${filePath}.${n2}`;
7088
+ const dest = `${filePath}.${n2 + 1}`;
7089
+ if (fs4.existsSync(src))
7090
+ fs4.renameSync(src, dest);
7091
+ }
7092
+ if (fs4.existsSync(filePath))
7093
+ fs4.renameSync(filePath, `${filePath}.1`);
7094
+ }
7095
+ function appendLine(opts, line) {
7096
+ const { filePath, maxFileSizeBytes, maxFiles } = opts;
7097
+ try {
7098
+ ensureDir(filePath);
7099
+ const state = getState(filePath);
7100
+ const lineBytes = Buffer.byteLength(line + `
7101
+ `, "utf8");
7102
+ if (!state.primed || state.deltaSinceStat >= STAT_DELTA_THRESHOLD_BYTES || state.trackedSize + state.deltaSinceStat >= maxFileSizeBytes) {
7103
+ restat(filePath, state);
7104
+ }
7105
+ if (maxFileSizeBytes > 0 && state.trackedSize >= maxFileSizeBytes) {
7106
+ rotate(filePath, maxFiles);
7107
+ state.trackedSize = 0;
7108
+ state.deltaSinceStat = 0;
7109
+ state.primed = true;
7110
+ }
7111
+ fs4.appendFileSync(filePath, line + `
7112
+ `);
7113
+ state.trackedSize += lineBytes;
7114
+ state.deltaSinceStat += lineBytes;
7115
+ } catch (err) {
7116
+ lastError = err;
7117
+ }
7118
+ }
7119
+ function sinkFiles(filePath, maxFiles) {
7120
+ const files = [];
7121
+ try {
7122
+ if (fs4.existsSync(filePath))
7123
+ files.push(filePath);
7124
+ for (let n2 = 1;n2 <= maxFiles; n2++) {
7125
+ const rotated = `${filePath}.${n2}`;
7126
+ if (fs4.existsSync(rotated))
7127
+ files.push(rotated);
7128
+ }
7129
+ } catch (err) {
7130
+ lastError = err;
7131
+ }
7132
+ return files;
7133
+ }
7134
+ var STAT_DELTA_THRESHOLD_BYTES, ensuredDirs, pathState, lastError;
7135
+ var init_log_sink = __esm(() => {
7136
+ STAT_DELTA_THRESHOLD_BYTES = 1024 * 1024;
7137
+ ensuredDirs = new Set;
7138
+ pathState = new Map;
7139
+ });
7140
+
7141
+ // ../../packages/shared/dist/utils/log-buffer.js
7142
+ class LogBufferImpl {
7143
+ capacity = DEFAULT_CAPACITY;
7144
+ entries = [];
7145
+ subscribers = new Set;
7146
+ nextSeq = 0;
7147
+ dispatching = false;
7148
+ pending = [];
7149
+ push(entry) {
7150
+ if (this.dispatching) {
7151
+ this.pending.push(entry);
7152
+ return;
7153
+ }
7154
+ this.dispatching = true;
7155
+ try {
7156
+ this.pushOne(entry);
7157
+ while (this.pending.length > 0) {
7158
+ const next = this.pending.shift();
7159
+ this.pushOne(next);
7160
+ }
7161
+ } finally {
7162
+ this.dispatching = false;
7163
+ }
7164
+ }
7165
+ pushOne(entry) {
7166
+ const full = { ...entry, seq: this.nextSeq++ };
7167
+ this.entries.push(full);
7168
+ while (this.entries.length > this.capacity) {
7169
+ this.entries.shift();
7170
+ }
7171
+ for (const fn of this.subscribers) {
7172
+ try {
7173
+ fn(full);
7174
+ } catch {}
7175
+ }
7176
+ }
7177
+ snapshot(opts) {
7178
+ const from = opts?.from;
7179
+ const to = opts?.to;
7180
+ const level = opts?.level;
7181
+ const q = opts?.q?.toLowerCase();
7182
+ const result = [];
7183
+ for (let i = this.entries.length - 1;i >= 0; i--) {
7184
+ const e = this.entries[i];
7185
+ if (from !== undefined && e.seq < from)
7186
+ continue;
7187
+ if (to !== undefined && e.seq > to)
7188
+ continue;
7189
+ if (level !== undefined && e.level !== level)
7190
+ continue;
7191
+ if (q !== undefined && !e.message.toLowerCase().includes(q))
7192
+ continue;
7193
+ result.push(e);
7194
+ }
7195
+ return result;
7196
+ }
7197
+ subscribe(fn) {
7198
+ this.subscribers.add(fn);
7199
+ return () => {
7200
+ this.subscribers.delete(fn);
7201
+ };
7202
+ }
7203
+ setCapacity(n2) {
7204
+ this.capacity = n2 > 0 ? n2 : 0;
7205
+ while (this.entries.length > this.capacity) {
7206
+ this.entries.shift();
7207
+ }
7208
+ }
7209
+ size() {
7210
+ return this.entries.length;
7211
+ }
7212
+ _resetForTesting() {
7213
+ this.entries = [];
7214
+ this.subscribers.clear();
7215
+ this.nextSeq = 0;
7216
+ this.dispatching = false;
7217
+ this.pending = [];
7218
+ this.capacity = DEFAULT_CAPACITY;
7219
+ }
7220
+ }
7221
+ var DEFAULT_CAPACITY = 2000, logBuffer;
7222
+ var init_log_buffer = __esm(() => {
7223
+ logBuffer = new LogBufferImpl;
7224
+ });
6953
7225
 
7226
+ // ../../packages/shared/dist/utils/logger.js
6954
7227
  class Logger {
6955
7228
  _level;
6956
7229
  _enableMetrics;
6957
7230
  _logFilePath;
7231
+ _enableFileSink;
7232
+ _maxFileSizeBytes;
7233
+ _maxFiles;
6958
7234
  _initialized = false;
6959
7235
  constructor() {}
6960
7236
  ensureInitialized() {
@@ -6964,10 +7240,18 @@ class Logger {
6964
7240
  this._level = this.parseLogLevel(loggingConfig.level);
6965
7241
  this._enableMetrics = loggingConfig.enableMetrics;
6966
7242
  this._logFilePath = loggingConfig.file;
7243
+ this._enableFileSink = loggingConfig.enableFileSink;
7244
+ this._maxFileSizeBytes = loggingConfig.maxFileSizeMb * 1024 * 1024;
7245
+ this._maxFiles = loggingConfig.maxFiles;
7246
+ logBuffer.setCapacity(loggingConfig.bufferSize);
6967
7247
  } catch {
6968
7248
  this._level = LogLevel.INFO;
6969
7249
  this._enableMetrics = false;
6970
7250
  this._logFilePath = undefined;
7251
+ this._enableFileSink = false;
7252
+ this._maxFileSizeBytes = 32 * 1024 * 1024;
7253
+ this._maxFiles = 5;
7254
+ logBuffer.setCapacity(2000);
6971
7255
  }
6972
7256
  this._initialized = true;
6973
7257
  }
@@ -6984,6 +7268,18 @@ class Logger {
6984
7268
  this.ensureInitialized();
6985
7269
  return this._logFilePath;
6986
7270
  }
7271
+ get enableFileSink() {
7272
+ this.ensureInitialized();
7273
+ return this._enableFileSink;
7274
+ }
7275
+ get maxFileSizeBytes() {
7276
+ this.ensureInitialized();
7277
+ return this._maxFileSizeBytes;
7278
+ }
7279
+ get maxFiles() {
7280
+ this.ensureInitialized();
7281
+ return this._maxFiles;
7282
+ }
6987
7283
  parseLogLevel(level) {
6988
7284
  const levels = {
6989
7285
  debug: LogLevel.DEBUG,
@@ -6996,34 +7292,40 @@ class Logger {
6996
7292
  shouldLog(level) {
6997
7293
  return level >= this.level;
6998
7294
  }
6999
- formatMessage(level, message, meta) {
7000
- const timestamp = new Date().toISOString();
7295
+ formatMessage(level, message, meta, timestamp = new Date().toISOString()) {
7001
7296
  const metaStr = meta ? ` ${JSON.stringify(meta)}` : "";
7002
7297
  return `[${timestamp}] [${level}] ${message}${metaStr}`;
7003
7298
  }
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 {}
7299
+ emit(level, message, meta) {
7300
+ const ts = new Date().toISOString();
7301
+ const line = this.formatMessage(LOG_LEVEL_LABELS[level], message, meta, ts);
7302
+ console.error(line);
7303
+ if (this.enableFileSink) {
7304
+ const filePath = this.logFilePath;
7305
+ if (filePath) {
7306
+ appendLine({ filePath, maxFileSizeBytes: this.maxFileSizeBytes, maxFiles: this.maxFiles }, line);
7307
+ }
7012
7308
  }
7309
+ logBuffer.push({
7310
+ ts,
7311
+ level: LOG_LEVEL_BUFFER_TAGS[level],
7312
+ message,
7313
+ ...meta ? { meta } : {}
7314
+ });
7013
7315
  }
7014
7316
  debug(message, meta) {
7015
7317
  if (this.shouldLog(LogLevel.DEBUG)) {
7016
- this.write(this.formatMessage("DEBUG", message, meta), LogLevel.DEBUG);
7318
+ this.emit(LogLevel.DEBUG, message, meta);
7017
7319
  }
7018
7320
  }
7019
7321
  info(message, meta) {
7020
7322
  if (this.shouldLog(LogLevel.INFO)) {
7021
- this.write(this.formatMessage("INFO", message, meta), LogLevel.INFO);
7323
+ this.emit(LogLevel.INFO, message, meta);
7022
7324
  }
7023
7325
  }
7024
7326
  warn(message, meta) {
7025
7327
  if (this.shouldLog(LogLevel.WARN)) {
7026
- this.write(this.formatMessage("WARN", message, meta), LogLevel.WARN);
7328
+ this.emit(LogLevel.WARN, message, meta);
7027
7329
  }
7028
7330
  }
7029
7331
  error(message, error, meta) {
@@ -7036,7 +7338,7 @@ class Logger {
7036
7338
  stack: error.stack
7037
7339
  }
7038
7340
  } : meta;
7039
- this.write(this.formatMessage("ERROR", message, errorMeta), LogLevel.ERROR);
7341
+ this.emit(LogLevel.ERROR, message, errorMeta);
7040
7342
  }
7041
7343
  }
7042
7344
  metric(name, value, unit) {
@@ -7065,15 +7367,29 @@ class Logger {
7065
7367
  return childLogger;
7066
7368
  }
7067
7369
  }
7068
- var LogLevel, logger;
7370
+ var LogLevel, LOG_LEVEL_LABELS, LOG_LEVEL_BUFFER_TAGS, logger;
7069
7371
  var init_logger = __esm(() => {
7070
7372
  init_config();
7373
+ init_log_sink();
7374
+ init_log_buffer();
7071
7375
  (function(LogLevel2) {
7072
7376
  LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
7073
7377
  LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
7074
7378
  LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
7075
7379
  LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
7076
7380
  })(LogLevel || (LogLevel = {}));
7381
+ LOG_LEVEL_LABELS = {
7382
+ [LogLevel.DEBUG]: "DEBUG",
7383
+ [LogLevel.INFO]: "INFO",
7384
+ [LogLevel.WARN]: "WARN",
7385
+ [LogLevel.ERROR]: "ERROR"
7386
+ };
7387
+ LOG_LEVEL_BUFFER_TAGS = {
7388
+ [LogLevel.DEBUG]: "debug",
7389
+ [LogLevel.INFO]: "info",
7390
+ [LogLevel.WARN]: "warn",
7391
+ [LogLevel.ERROR]: "error"
7392
+ };
7077
7393
  logger = new Logger;
7078
7394
  });
7079
7395
 
@@ -7356,6 +7672,8 @@ var init_rate_limiter = __esm(() => {
7356
7672
  // ../../packages/shared/dist/utils/index.js
7357
7673
  var init_utils = __esm(() => {
7358
7674
  init_logger();
7675
+ init_log_buffer();
7676
+ init_log_sink();
7359
7677
  init_sanitizer();
7360
7678
  init_metrics();
7361
7679
  init_rate_limiter();
@@ -7363,7 +7681,7 @@ var init_utils = __esm(() => {
7363
7681
 
7364
7682
  // ../../packages/shared/dist/profile-switch/hosts.js
7365
7683
  import os3 from "os";
7366
- import path7 from "path";
7684
+ import path8 from "path";
7367
7685
  function isHost(v) {
7368
7686
  return typeof v === "string" && HOSTS.includes(v);
7369
7687
  }
@@ -7374,7 +7692,7 @@ function fileLayout(host, activeDir, activeGlob, variantsRoot) {
7374
7692
  activeDir,
7375
7693
  activeGlob,
7376
7694
  variantsRoot,
7377
- variantDir: (profile) => path7.join(variantsRoot, profile)
7695
+ variantDir: (profile) => path8.join(variantsRoot, profile)
7378
7696
  };
7379
7697
  }
7380
7698
  function resolveHostLayout(host, opts = {}) {
@@ -7384,25 +7702,37 @@ function resolveHostLayout(host, opts = {}) {
7384
7702
  case "cursor":
7385
7703
  return { host, route: "skip", reason: CURSOR_SKIP_REASON };
7386
7704
  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"));
7705
+ const marketplaceRoot = opts.marketplaceRoot?.claude;
7706
+ if (override === undefined && marketplaceRoot !== undefined) {
7707
+ return fileLayout(host, path8.join(marketplaceRoot, "agents"), "massa-ai-*.md", path8.join(marketplaceRoot, "agent-profiles"));
7708
+ }
7709
+ const root = override ?? path8.join(targetHome, ".claude");
7710
+ return fileLayout(host, path8.join(root, "agents"), "massa-ai-*.md", path8.join(root, "massa-ai", "agent-profiles"));
7389
7711
  }
7390
7712
  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"));
7713
+ const root = override ?? path8.join(targetHome, ".codex");
7714
+ return fileLayout(host, path8.join(root, "agents"), "massa-ai-*.toml", path8.join(root, "massa-ai", "agent-profiles"));
7393
7715
  }
7394
7716
  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"));
7717
+ const root = override ?? path8.join(targetHome, ".config", "opencode");
7718
+ const pluginsDir = path8.join(root, "plugins", "massa-ai");
7719
+ return fileLayout(host, path8.join(root, "agents"), "massa-ai-*.md", path8.join(pluginsDir, "agent-profiles"));
7398
7720
  }
7399
7721
  }
7400
7722
  }
7401
- function detectRoute(platform) {
7723
+ function detectRoute(platform, host) {
7402
7724
  const route = platform?.installRoute;
7403
7725
  if (route === "file")
7404
7726
  return { kind: "proceed" };
7405
7727
  if (route === "marketplace") {
7728
+ if (host === "claude")
7729
+ return { kind: "proceed" };
7730
+ if (host === "codex") {
7731
+ return {
7732
+ kind: "refuse",
7733
+ 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."
7734
+ };
7735
+ }
7406
7736
  return {
7407
7737
  kind: "refuse",
7408
7738
  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 +7750,7 @@ var init_hosts = __esm(() => {
7420
7750
 
7421
7751
  // ../../packages/shared/dist/profile-switch/state.js
7422
7752
  import fs5 from "fs";
7423
- import path8 from "path";
7753
+ import path9 from "path";
7424
7754
  function namedError(name, message) {
7425
7755
  const err = new InstallStateError(message);
7426
7756
  err.name = name;
@@ -7466,7 +7796,7 @@ function writeInstallState(filePath, state) {
7466
7796
  const text = `${JSON.stringify(validated, null, 2)}
7467
7797
  `;
7468
7798
  try {
7469
- fs5.mkdirSync(path8.dirname(filePath), { recursive: true });
7799
+ fs5.mkdirSync(path9.dirname(filePath), { recursive: true });
7470
7800
  fs5.writeFileSync(filePath, text);
7471
7801
  } catch (err) {
7472
7802
  throw UnwritableInstallStateError(filePath, err.message);
@@ -7495,7 +7825,7 @@ var init_state = __esm(() => {
7495
7825
 
7496
7826
  // ../../packages/shared/dist/profile-switch/lock.js
7497
7827
  import fs6 from "fs";
7498
- import path9 from "path";
7828
+ import path10 from "path";
7499
7829
  import os4 from "os";
7500
7830
  import crypto4 from "crypto";
7501
7831
  import { execFileSync } from "child_process";
@@ -7527,7 +7857,7 @@ function releaseIfOwned(lockDir, ownerPath, token) {
7527
7857
  }
7528
7858
  function acquireLock(stateFilePath, options = {}) {
7529
7859
  const lockDir = `${stateFilePath}.switch.lock`;
7530
- const ownerPath = path9.join(lockDir, "owner.json");
7860
+ const ownerPath = path10.join(lockDir, "owner.json");
7531
7861
  const clock = options.clock ?? DEFAULT_CLOCK;
7532
7862
  const identity = options.identity ?? DEFAULT_IDENTITY;
7533
7863
  const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
@@ -7547,7 +7877,7 @@ function acquireLock(stateFilePath, options = {}) {
7547
7877
  token,
7548
7878
  timestamp: clock.now()
7549
7879
  };
7550
- fs6.mkdirSync(path9.dirname(ownerPath), { recursive: true });
7880
+ fs6.mkdirSync(path10.dirname(ownerPath), { recursive: true });
7551
7881
  fs6.writeFileSync(ownerPath, JSON.stringify(record));
7552
7882
  return { lockDir, release: () => releaseIfOwned(lockDir, ownerPath, token) };
7553
7883
  };
@@ -7600,10 +7930,59 @@ var init_lock = __esm(() => {
7600
7930
  };
7601
7931
  });
7602
7932
 
7603
- // ../../packages/shared/dist/profile-switch/engine.js
7933
+ // ../../packages/shared/dist/profile-switch/claude-marketplace.js
7604
7934
  import fs7 from "fs";
7605
- import path10 from "path";
7606
7935
  import os5 from "os";
7936
+ import path11 from "path";
7937
+ function selectRecord(records) {
7938
+ if (records.length === 0)
7939
+ return;
7940
+ const userScoped = records.filter((r2) => r2.scope === "user");
7941
+ const pool = userScoped.length > 0 ? userScoped : records;
7942
+ let best;
7943
+ let bestTime = -Infinity;
7944
+ for (const record of pool) {
7945
+ const parsed = record.lastUpdated ? Date.parse(record.lastUpdated) : NaN;
7946
+ if (Number.isFinite(parsed) && parsed >= bestTime) {
7947
+ best = record;
7948
+ bestTime = parsed;
7949
+ }
7950
+ }
7951
+ return best ?? pool[pool.length - 1];
7952
+ }
7953
+ function resolveClaudeMarketplaceRoot(opts = {}) {
7954
+ const targetHome = opts.targetHome ?? os5.homedir();
7955
+ const pluginKey = opts.pluginKey ?? DEFAULT_PLUGIN_KEY;
7956
+ const registryPath = path11.join(targetHome, ".claude", "plugins", "installed_plugins.json");
7957
+ let records;
7958
+ try {
7959
+ const raw2 = fs7.readFileSync(registryPath, "utf8");
7960
+ const parsed = JSON.parse(raw2);
7961
+ records = parsed?.plugins?.[pluginKey];
7962
+ } catch {
7963
+ return null;
7964
+ }
7965
+ if (!Array.isArray(records) || records.length === 0)
7966
+ return null;
7967
+ const selected = selectRecord(records);
7968
+ const installPath = selected?.installPath;
7969
+ if (!installPath)
7970
+ return null;
7971
+ try {
7972
+ if (!fs7.existsSync(installPath))
7973
+ return null;
7974
+ } catch {
7975
+ return null;
7976
+ }
7977
+ return installPath;
7978
+ }
7979
+ var DEFAULT_PLUGIN_KEY = "massa-ai@massa-ai";
7980
+ var init_claude_marketplace = () => {};
7981
+
7982
+ // ../../packages/shared/dist/profile-switch/engine.js
7983
+ import fs8 from "fs";
7984
+ import path12 from "path";
7985
+ import os6 from "os";
7607
7986
  import crypto5 from "crypto";
7608
7987
  function namedError3(name, message) {
7609
7988
  const err = new SwitchEngineError(message);
@@ -7611,19 +7990,39 @@ function namedError3(name, message) {
7611
7990
  return err;
7612
7991
  }
7613
7992
  function defaultStatePath(targetHome) {
7614
- return path10.join(targetHome, ".config", "massa-ai", "install-state.json");
7993
+ return path12.join(targetHome, ".config", "massa-ai", "install-state.json");
7615
7994
  }
7616
7995
  function resolveCommon(opts) {
7617
- const targetHome = opts.targetHome ?? os5.homedir();
7996
+ const targetHome = opts.targetHome ?? os6.homedir();
7618
7997
  const stateFilePath = opts.stateFilePath ?? defaultStatePath(targetHome);
7619
7998
  return { targetHome, stateFilePath };
7620
7999
  }
8000
+ function marketplaceRoots(targetHome, state) {
8001
+ return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
8002
+ }
8003
+ function claudeMarketplaceUnresolvedReason(targetHome) {
8004
+ const registryPath = path12.join(targetHome, ".claude", "plugins", "installed_plugins.json");
8005
+ 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";
8006
+ }
7621
8007
  function listProfiles(opts = {}) {
7622
8008
  const { targetHome, stateFilePath } = resolveCommon(opts);
7623
8009
  const state = readInstallState(stateFilePath);
8010
+ const roots = marketplaceRoots(targetHome, state);
7624
8011
  const universe = opts.hosts ?? HOSTS;
7625
8012
  const hosts = universe.map((host) => {
7626
- const layout = resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot });
8013
+ if (host === "claude" && state.platforms.claude?.installRoute === "marketplace" && roots.claude === undefined) {
8014
+ const platform2 = state.platforms.claude;
8015
+ return {
8016
+ host,
8017
+ installed: false,
8018
+ skipped: false,
8019
+ skipReason: null,
8020
+ activeProfile: platform2.modelProfile?.profile ?? opts.hostDefaults?.[host] ?? "balanced",
8021
+ bundleVersion: platform2.plugin?.version ?? null,
8022
+ availableProfiles: []
8023
+ };
8024
+ }
8025
+ const layout = resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot, marketplaceRoot: roots });
7627
8026
  if (layout.route === "skip") {
7628
8027
  return {
7629
8028
  host,
@@ -7635,7 +8034,7 @@ function listProfiles(opts = {}) {
7635
8034
  availableProfiles: []
7636
8035
  };
7637
8036
  }
7638
- const installed = fs7.existsSync(layout.activeDir);
8037
+ const installed = fs8.existsSync(layout.activeDir);
7639
8038
  const availableProfiles = listVariantProfiles(layout);
7640
8039
  const platform = state.platforms[host];
7641
8040
  return {
@@ -7651,9 +8050,9 @@ function listProfiles(opts = {}) {
7651
8050
  return { hosts };
7652
8051
  }
7653
8052
  function listVariantProfiles(layout) {
7654
- if (!fs7.existsSync(layout.variantsRoot))
8053
+ if (!fs8.existsSync(layout.variantsRoot))
7655
8054
  return [];
7656
- return fs7.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
8055
+ return fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
7657
8056
  }
7658
8057
  function matchesGlob(filename, glob) {
7659
8058
  const starIdx = glob.indexOf("*");
@@ -7664,50 +8063,50 @@ function matchesGlob(filename, glob) {
7664
8063
  return filename.length >= prefix.length + suffix.length && filename.startsWith(prefix) && filename.endsWith(suffix);
7665
8064
  }
7666
8065
  function assertStateWritable(stateFilePath) {
7667
- const dir = path10.dirname(stateFilePath);
8066
+ const dir = path12.dirname(stateFilePath);
7668
8067
  try {
7669
- fs7.mkdirSync(dir, { recursive: true });
8068
+ fs8.mkdirSync(dir, { recursive: true });
7670
8069
  } catch (err) {
7671
8070
  throw UnwritableInstallStateError(stateFilePath, err.message);
7672
8071
  }
7673
- const checkPath = fs7.existsSync(stateFilePath) ? stateFilePath : dir;
8072
+ const checkPath = fs8.existsSync(stateFilePath) ? stateFilePath : dir;
7674
8073
  try {
7675
- fs7.accessSync(checkPath, fs7.constants.W_OK);
8074
+ fs8.accessSync(checkPath, fs8.constants.W_OK);
7676
8075
  } catch (err) {
7677
8076
  throw UnwritableInstallStateError(stateFilePath, err.message);
7678
8077
  }
7679
8078
  }
7680
8079
  function copyFileRouteVariant(layout, variantDir) {
7681
- fs7.mkdirSync(layout.activeDir, { recursive: true });
8080
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
7682
8081
  let changed = 0;
7683
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
8082
+ for (const entry of fs8.readdirSync(variantDir, { withFileTypes: true })) {
7684
8083
  if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
7685
8084
  continue;
7686
- fs7.copyFileSync(path10.join(variantDir, entry.name), path10.join(layout.activeDir, entry.name));
8085
+ fs8.copyFileSync(path12.join(variantDir, entry.name), path12.join(layout.activeDir, entry.name));
7687
8086
  changed++;
7688
8087
  }
7689
8088
  return changed;
7690
8089
  }
7691
8090
  function repointOpencodeVariant(layout, variantDir) {
7692
- fs7.mkdirSync(layout.activeDir, { recursive: true });
8091
+ fs8.mkdirSync(layout.activeDir, { recursive: true });
7693
8092
  let changed = 0;
7694
- for (const entry of fs7.readdirSync(variantDir, { withFileTypes: true })) {
8093
+ for (const entry of fs8.readdirSync(variantDir, { withFileTypes: true })) {
7695
8094
  if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
7696
8095
  continue;
7697
- const dest = path10.join(layout.activeDir, entry.name);
7698
- const target = path10.resolve(path10.join(variantDir, entry.name));
8096
+ const dest = path12.join(layout.activeDir, entry.name);
8097
+ const target = path12.resolve(path12.join(variantDir, entry.name));
7699
8098
  let destExists = true;
7700
8099
  let destIsSymlink = false;
7701
8100
  try {
7702
- destIsSymlink = fs7.lstatSync(dest).isSymbolicLink();
8101
+ destIsSymlink = fs8.lstatSync(dest).isSymbolicLink();
7703
8102
  } catch {
7704
8103
  destExists = false;
7705
8104
  }
7706
8105
  if (destExists && !destIsSymlink)
7707
8106
  continue;
7708
8107
  const tmp = `${dest}.massa-ai-switch.${crypto5.randomUUID()}`;
7709
- fs7.symlinkSync(target, tmp);
7710
- fs7.renameSync(tmp, dest);
8108
+ fs8.symlinkSync(target, tmp);
8109
+ fs8.renameSync(tmp, dest);
7711
8110
  changed++;
7712
8111
  }
7713
8112
  return changed;
@@ -7723,19 +8122,37 @@ function switchProfile(opts) {
7723
8122
  const state = readInstallState(stateFilePath);
7724
8123
  if (!dryRun)
7725
8124
  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 }));
8125
+ const roots = marketplaceRoots(targetHome, state);
8126
+ const unresolvedRows = [];
8127
+ const resolvableUniverse = universe.filter((host) => {
8128
+ if (host !== "claude")
8129
+ return true;
8130
+ if (state.platforms.claude?.installRoute !== "marketplace")
8131
+ return true;
8132
+ if (roots.claude !== undefined)
8133
+ return true;
8134
+ unresolvedRows.push({ host, status: "failed", reason: claudeMarketplaceUnresolvedReason(targetHome) });
8135
+ return false;
8136
+ });
8137
+ const layouts = resolvableUniverse.map((host) => ({
8138
+ host,
8139
+ layout: resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot, marketplaceRoot: roots })
8140
+ }));
8141
+ const skipRows = [
8142
+ ...unresolvedRows,
8143
+ ...layouts.filter((l2) => l2.layout.route === "skip").map((l2) => ({ host: l2.host, status: "skipped", reason: l2.layout.reason }))
8144
+ ];
7728
8145
  const fileHosts = layouts.filter((l2) => l2.layout.route === "files");
7729
8146
  if (fileHosts.length === 0) {
7730
8147
  return { profile: opts.profile, dryRun, hosts: orderRows(universe, skipRows), restartRequired: false };
7731
8148
  }
7732
- const installedFileHosts = fileHosts.filter((h) => fs7.existsSync(h.layout.activeDir));
8149
+ const installedFileHosts = fileHosts.filter((h) => fs8.existsSync(h.layout.activeDir));
7733
8150
  if (installedFileHosts.length === 0)
7734
8151
  throw NoHostsDetectedError();
7735
8152
  const withAvailability = fileHosts.map((h) => {
7736
- const variantsRootExists = fs7.existsSync(h.layout.variantsRoot);
8153
+ const variantsRootExists = fs8.existsSync(h.layout.variantsRoot);
7737
8154
  const variantDir = h.layout.variantDir(opts.profile);
7738
- const available = variantsRootExists && fs7.existsSync(variantDir) && fs7.statSync(variantDir).isDirectory();
8155
+ const available = variantsRootExists && fs8.existsSync(variantDir) && fs8.statSync(variantDir).isDirectory();
7739
8156
  return { ...h, variantsRootExists, variantDir, available };
7740
8157
  });
7741
8158
  if (!withAvailability.some((h) => h.available)) {
@@ -7765,7 +8182,7 @@ function switchProfile(opts) {
7765
8182
  });
7766
8183
  continue;
7767
8184
  }
7768
- const route = detectRoute(state.platforms[h.host]);
8185
+ const route = detectRoute(state.platforms[h.host], h.host);
7769
8186
  if (route.kind === "refuse") {
7770
8187
  rows.push({ host: h.host, status: "failed", reason: route.reason });
7771
8188
  continue;
@@ -7800,6 +8217,7 @@ var init_engine = __esm(() => {
7800
8217
  init_hosts();
7801
8218
  init_state();
7802
8219
  init_lock();
8220
+ init_claude_marketplace();
7803
8221
  SwitchEngineError = class SwitchEngineError extends Error {
7804
8222
  constructor(message) {
7805
8223
  super(message);
@@ -7814,18 +8232,25 @@ function reportSucceeded(report) {
7814
8232
  }
7815
8233
 
7816
8234
  // ../../packages/shared/dist/profile-switch/variant-sync.js
7817
- import fs8 from "fs";
7818
- import path11 from "path";
8235
+ import fs9 from "fs";
8236
+ import path13 from "path";
8237
+ import os7 from "os";
7819
8238
  import crypto6 from "crypto";
8239
+ function defaultStatePath2(targetHome) {
8240
+ return path13.join(targetHome, ".config", "massa-ai", "install-state.json");
8241
+ }
8242
+ function marketplaceRoots2(targetHome, state) {
8243
+ return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
8244
+ }
7820
8245
  function writeFileIntoDirAtomically(destDir, destName, content) {
7821
8246
  const unique = `${process.pid}.${++tempFileCounter2}.${crypto6.randomBytes(6).toString("hex")}`;
7822
- const tempFile = path11.join(destDir, `.${destName}.${unique}.tmp`);
8247
+ const tempFile = path13.join(destDir, `.${destName}.${unique}.tmp`);
7823
8248
  try {
7824
- fs8.writeFileSync(tempFile, content);
7825
- fs8.renameSync(tempFile, path11.join(destDir, destName));
8249
+ fs9.writeFileSync(tempFile, content);
8250
+ fs9.renameSync(tempFile, path13.join(destDir, destName));
7826
8251
  } catch (error) {
7827
8252
  try {
7828
- fs8.unlinkSync(tempFile);
8253
+ fs9.unlinkSync(tempFile);
7829
8254
  } catch {}
7830
8255
  throw error;
7831
8256
  }
@@ -7833,20 +8258,20 @@ function writeFileIntoDirAtomically(destDir, destName, content) {
7833
8258
  function isSafeDirName(name) {
7834
8259
  if (name === "." || name === "..")
7835
8260
  return false;
7836
- if (name.includes("/") || name.includes("\\") || name.includes(path11.sep))
8261
+ if (name.includes("/") || name.includes("\\") || name.includes(path13.sep))
7837
8262
  return false;
7838
- return path11.basename(name) === name;
8263
+ return path13.basename(name) === name;
7839
8264
  }
7840
- function syncHost(host, sourceRoot, targetHome) {
7841
- const layout = resolveHostLayout(host, { targetHome });
8265
+ function syncHost(host, sourceRoot, targetHome, marketplaceRoot) {
8266
+ const layout = resolveHostLayout(host, { targetHome, marketplaceRoot });
7842
8267
  if (layout.route === "skip") {
7843
8268
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: layout.reason };
7844
8269
  }
7845
- const srcDir = path11.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
7846
- if (!fs8.existsSync(srcDir) || !fs8.statSync(srcDir).isDirectory()) {
8270
+ const srcDir = path13.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
8271
+ if (!fs9.existsSync(srcDir) || !fs9.statSync(srcDir).isDirectory()) {
7847
8272
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: "no generated variants for this host" };
7848
8273
  }
7849
- if (!fs8.existsSync(layout.variantsRoot)) {
8274
+ if (!fs9.existsSync(layout.variantsRoot)) {
7850
8275
  return {
7851
8276
  host,
7852
8277
  status: "skipped",
@@ -7858,24 +8283,24 @@ function syncHost(host, sourceRoot, targetHome) {
7858
8283
  }
7859
8284
  const profiles = [];
7860
8285
  let files = 0;
7861
- for (const entry of fs8.readdirSync(srcDir, { withFileTypes: true })) {
8286
+ for (const entry of fs9.readdirSync(srcDir, { withFileTypes: true })) {
7862
8287
  if (!entry.isDirectory())
7863
8288
  continue;
7864
8289
  if (!isSafeDirName(entry.name))
7865
8290
  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 })) {
8291
+ const srcProfileDir = path13.join(srcDir, entry.name);
8292
+ const destProfileDir = path13.join(layout.variantsRoot, entry.name);
8293
+ fs9.mkdirSync(destProfileDir, { recursive: true });
8294
+ for (const fileEntry of fs9.readdirSync(srcProfileDir, { withFileTypes: true })) {
7870
8295
  if (!fileEntry.isFile())
7871
8296
  continue;
7872
- const content = fs8.readFileSync(path11.join(srcProfileDir, fileEntry.name));
8297
+ const content = fs9.readFileSync(path13.join(srcProfileDir, fileEntry.name));
7873
8298
  writeFileIntoDirAtomically(destProfileDir, fileEntry.name, content);
7874
8299
  files++;
7875
8300
  }
7876
8301
  profiles.push(entry.name);
7877
8302
  }
7878
- const retained = fs8.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
8303
+ const retained = fs9.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
7879
8304
  return { host, status: "synced", profiles: profiles.sort(), retained, files };
7880
8305
  }
7881
8306
  function syncGeneratedVariants(opts) {
@@ -7891,9 +8316,12 @@ function syncGeneratedVariants(opts) {
7891
8316
  }));
7892
8317
  }
7893
8318
  const sourceRoot = opts.sourceRoot;
8319
+ const targetHome = opts.targetHome ?? os7.homedir();
8320
+ const state = readInstallState(defaultStatePath2(targetHome));
8321
+ const roots = marketplaceRoots2(targetHome, state);
7894
8322
  return hosts.map((host) => {
7895
8323
  try {
7896
- return syncHost(host, sourceRoot, opts.targetHome);
8324
+ return syncHost(host, sourceRoot, opts.targetHome, roots);
7897
8325
  } catch (err) {
7898
8326
  return { host, status: "failed", profiles: [], retained: [], files: 0, error: err.message };
7899
8327
  }
@@ -7902,17 +8330,19 @@ function syncGeneratedVariants(opts) {
7902
8330
  var tempFileCounter2 = 0;
7903
8331
  var init_variant_sync = __esm(() => {
7904
8332
  init_hosts();
8333
+ init_state();
8334
+ init_claude_marketplace();
7905
8335
  });
7906
8336
 
7907
8337
  // ../../packages/shared/dist/profile-switch/repo-root.js
7908
- import fs9 from "fs";
7909
- import path12 from "path";
8338
+ import fs10 from "fs";
8339
+ import path14 from "path";
7910
8340
  function findRepoRootWithMarker(startDir, marker, maxLevels) {
7911
8341
  let dir = startDir;
7912
8342
  for (let i = 0;i <= maxLevels; i++) {
7913
- if (fs9.existsSync(path12.join(dir, marker)))
8343
+ if (fs10.existsSync(path14.join(dir, marker)))
7914
8344
  return dir;
7915
- const parent = path12.dirname(dir);
8345
+ const parent = path14.dirname(dir);
7916
8346
  if (parent === dir)
7917
8347
  break;
7918
8348
  dir = parent;
@@ -9452,7 +9882,7 @@ var import_brace_expansion, minimatch = (p, pattern, options = {}) => {
9452
9882
  }, qmarksTestNoExtDot = ([$0]) => {
9453
9883
  const len = $0.length;
9454
9884
  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) => {
9885
+ }, 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
9886
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
9457
9887
  return minimatch;
9458
9888
  }
@@ -9510,11 +9940,11 @@ var init_esm = __esm(() => {
9510
9940
  starRE = /^\*+$/;
9511
9941
  qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
9512
9942
  defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
9513
- path13 = {
9943
+ path15 = {
9514
9944
  win32: { sep: "\\" },
9515
9945
  posix: { sep: "/" }
9516
9946
  };
9517
- sep = defaultPlatform === "win32" ? path13.win32.sep : path13.posix.sep;
9947
+ sep = defaultPlatform === "win32" ? path15.win32.sep : path15.posix.sep;
9518
9948
  minimatch.sep = sep;
9519
9949
  GLOBSTAR = Symbol("globstar **");
9520
9950
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -11480,12 +11910,12 @@ var init_esm4 = __esm(() => {
11480
11910
  childrenCache() {
11481
11911
  return this.#children;
11482
11912
  }
11483
- resolve(path14) {
11484
- if (!path14) {
11913
+ resolve(path16) {
11914
+ if (!path16) {
11485
11915
  return this;
11486
11916
  }
11487
- const rootPath = this.getRootString(path14);
11488
- const dir = path14.substring(rootPath.length);
11917
+ const rootPath = this.getRootString(path16);
11918
+ const dir = path16.substring(rootPath.length);
11489
11919
  const dirParts = dir.split(this.splitSep);
11490
11920
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
11491
11921
  return result;
@@ -12013,8 +12443,8 @@ var init_esm4 = __esm(() => {
12013
12443
  newChild(name, type = UNKNOWN, opts = {}) {
12014
12444
  return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
12015
12445
  }
12016
- getRootString(path14) {
12017
- return win32.parse(path14).root;
12446
+ getRootString(path16) {
12447
+ return win32.parse(path16).root;
12018
12448
  }
12019
12449
  getRoot(rootPath) {
12020
12450
  rootPath = uncToDrive(rootPath.toUpperCase());
@@ -12039,8 +12469,8 @@ var init_esm4 = __esm(() => {
12039
12469
  constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
12040
12470
  super(name, type, root, roots, nocase, children, opts);
12041
12471
  }
12042
- getRootString(path14) {
12043
- return path14.startsWith("/") ? "/" : "";
12472
+ getRootString(path16) {
12473
+ return path16.startsWith("/") ? "/" : "";
12044
12474
  }
12045
12475
  getRoot(_rootPath) {
12046
12476
  return this.root;
@@ -12059,8 +12489,8 @@ var init_esm4 = __esm(() => {
12059
12489
  #children;
12060
12490
  nocase;
12061
12491
  #fs;
12062
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs10 = defaultFS } = {}) {
12063
- this.#fs = fsFromOption(fs10);
12492
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs11 = defaultFS } = {}) {
12493
+ this.#fs = fsFromOption(fs11);
12064
12494
  if (cwd instanceof URL || cwd.startsWith("file://")) {
12065
12495
  cwd = fileURLToPath(cwd);
12066
12496
  }
@@ -12096,11 +12526,11 @@ var init_esm4 = __esm(() => {
12096
12526
  }
12097
12527
  this.cwd = prev;
12098
12528
  }
12099
- depth(path14 = this.cwd) {
12100
- if (typeof path14 === "string") {
12101
- path14 = this.cwd.resolve(path14);
12529
+ depth(path16 = this.cwd) {
12530
+ if (typeof path16 === "string") {
12531
+ path16 = this.cwd.resolve(path16);
12102
12532
  }
12103
- return path14.depth();
12533
+ return path16.depth();
12104
12534
  }
12105
12535
  childrenCache() {
12106
12536
  return this.#children;
@@ -12516,9 +12946,9 @@ var init_esm4 = __esm(() => {
12516
12946
  process2();
12517
12947
  return results;
12518
12948
  }
12519
- chdir(path14 = this.cwd) {
12949
+ chdir(path16 = this.cwd) {
12520
12950
  const oldCwd = this.cwd;
12521
- this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
12951
+ this.cwd = typeof path16 === "string" ? this.cwd.resolve(path16) : path16;
12522
12952
  this.cwd[setAsCwd](oldCwd);
12523
12953
  }
12524
12954
  };
@@ -12535,8 +12965,8 @@ var init_esm4 = __esm(() => {
12535
12965
  parseRootPath(dir) {
12536
12966
  return win32.parse(dir).root.toUpperCase();
12537
12967
  }
12538
- newRoot(fs10) {
12539
- return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs10 });
12968
+ newRoot(fs11) {
12969
+ return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs11 });
12540
12970
  }
12541
12971
  isAbsolute(p) {
12542
12972
  return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
@@ -12552,8 +12982,8 @@ var init_esm4 = __esm(() => {
12552
12982
  parseRootPath(_dir) {
12553
12983
  return "/";
12554
12984
  }
12555
- newRoot(fs10) {
12556
- return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs10 });
12985
+ newRoot(fs11) {
12986
+ return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs11 });
12557
12987
  }
12558
12988
  isAbsolute(p) {
12559
12989
  return p.startsWith("/");
@@ -12810,8 +13240,8 @@ class MatchRecord {
12810
13240
  this.store.set(target, current === undefined ? n2 : n2 & current);
12811
13241
  }
12812
13242
  entries() {
12813
- return [...this.store.entries()].map(([path14, n2]) => [
12814
- path14,
13243
+ return [...this.store.entries()].map(([path16, n2]) => [
13244
+ path16,
12815
13245
  !!(n2 & 2),
12816
13246
  !!(n2 & 1)
12817
13247
  ]);
@@ -13015,9 +13445,9 @@ class GlobUtil {
13015
13445
  signal;
13016
13446
  maxDepth;
13017
13447
  includeChildMatches;
13018
- constructor(patterns, path14, opts) {
13448
+ constructor(patterns, path16, opts) {
13019
13449
  this.patterns = patterns;
13020
- this.path = path14;
13450
+ this.path = path16;
13021
13451
  this.opts = opts;
13022
13452
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
13023
13453
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -13036,11 +13466,11 @@ class GlobUtil {
13036
13466
  });
13037
13467
  }
13038
13468
  }
13039
- #ignored(path14) {
13040
- return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
13469
+ #ignored(path16) {
13470
+ return this.seen.has(path16) || !!this.#ignore?.ignored?.(path16);
13041
13471
  }
13042
- #childrenIgnored(path14) {
13043
- return !!this.#ignore?.childrenIgnored?.(path14);
13472
+ #childrenIgnored(path16) {
13473
+ return !!this.#ignore?.childrenIgnored?.(path16);
13044
13474
  }
13045
13475
  pause() {
13046
13476
  this.paused = true;
@@ -13257,8 +13687,8 @@ var init_walker = __esm(() => {
13257
13687
  init_processor();
13258
13688
  GlobWalker = class GlobWalker extends GlobUtil {
13259
13689
  matches = new Set;
13260
- constructor(patterns, path14, opts) {
13261
- super(patterns, path14, opts);
13690
+ constructor(patterns, path16, opts) {
13691
+ super(patterns, path16, opts);
13262
13692
  }
13263
13693
  matchEmit(e) {
13264
13694
  this.matches.add(e);
@@ -13295,8 +13725,8 @@ var init_walker = __esm(() => {
13295
13725
  };
13296
13726
  GlobStream = class GlobStream extends GlobUtil {
13297
13727
  results;
13298
- constructor(patterns, path14, opts) {
13299
- super(patterns, path14, opts);
13728
+ constructor(patterns, path16, opts) {
13729
+ super(patterns, path16, opts);
13300
13730
  this.results = new Minipass({
13301
13731
  signal: this.signal,
13302
13732
  objectMode: true
@@ -13724,20 +14154,20 @@ var require_ignore = __commonJS((exports, module) => {
13724
14154
  var throwError = (message, Ctor) => {
13725
14155
  throw new Ctor(message);
13726
14156
  };
13727
- var checkPath = (path14, originalPath, doThrow) => {
13728
- if (!isString(path14)) {
14157
+ var checkPath = (path16, originalPath, doThrow) => {
14158
+ if (!isString(path16)) {
13729
14159
  return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
13730
14160
  }
13731
- if (!path14) {
14161
+ if (!path16) {
13732
14162
  return doThrow(`path must not be empty`, TypeError);
13733
14163
  }
13734
- if (checkPath.isNotRelative(path14)) {
14164
+ if (checkPath.isNotRelative(path16)) {
13735
14165
  const r2 = "`path.relative()`d";
13736
14166
  return doThrow(`path should be a ${r2} string, but got "${originalPath}"`, RangeError);
13737
14167
  }
13738
14168
  return true;
13739
14169
  };
13740
- var isNotRelative = (path14) => REGEX_TEST_INVALID_PATH.test(path14);
14170
+ var isNotRelative = (path16) => REGEX_TEST_INVALID_PATH.test(path16);
13741
14171
  checkPath.isNotRelative = isNotRelative;
13742
14172
  checkPath.convert = (p) => p;
13743
14173
 
@@ -13780,7 +14210,7 @@ var require_ignore = __commonJS((exports, module) => {
13780
14210
  addPattern(pattern) {
13781
14211
  return this.add(pattern);
13782
14212
  }
13783
- _testOne(path14, checkUnignored) {
14213
+ _testOne(path16, checkUnignored) {
13784
14214
  let ignored = false;
13785
14215
  let unignored = false;
13786
14216
  this._rules.forEach((rule) => {
@@ -13788,7 +14218,7 @@ var require_ignore = __commonJS((exports, module) => {
13788
14218
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
13789
14219
  return;
13790
14220
  }
13791
- const matched = rule.regex.test(path14);
14221
+ const matched = rule.regex.test(path16);
13792
14222
  if (matched) {
13793
14223
  ignored = !negative;
13794
14224
  unignored = negative;
@@ -13800,39 +14230,39 @@ var require_ignore = __commonJS((exports, module) => {
13800
14230
  };
13801
14231
  }
13802
14232
  _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);
14233
+ const path16 = originalPath && checkPath.convert(originalPath);
14234
+ checkPath(path16, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
14235
+ return this._t(path16, cache, checkUnignored, slices);
13806
14236
  }
13807
- _t(path14, cache, checkUnignored, slices) {
13808
- if (path14 in cache) {
13809
- return cache[path14];
14237
+ _t(path16, cache, checkUnignored, slices) {
14238
+ if (path16 in cache) {
14239
+ return cache[path16];
13810
14240
  }
13811
14241
  if (!slices) {
13812
- slices = path14.split(SLASH);
14242
+ slices = path16.split(SLASH);
13813
14243
  }
13814
14244
  slices.pop();
13815
14245
  if (!slices.length) {
13816
- return cache[path14] = this._testOne(path14, checkUnignored);
14246
+ return cache[path16] = this._testOne(path16, checkUnignored);
13817
14247
  }
13818
14248
  const parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
13819
- return cache[path14] = parent.ignored ? parent : this._testOne(path14, checkUnignored);
14249
+ return cache[path16] = parent.ignored ? parent : this._testOne(path16, checkUnignored);
13820
14250
  }
13821
- ignores(path14) {
13822
- return this._test(path14, this._ignoreCache, false).ignored;
14251
+ ignores(path16) {
14252
+ return this._test(path16, this._ignoreCache, false).ignored;
13823
14253
  }
13824
14254
  createFilter() {
13825
- return (path14) => !this.ignores(path14);
14255
+ return (path16) => !this.ignores(path16);
13826
14256
  }
13827
14257
  filter(paths) {
13828
14258
  return makeArray(paths).filter(this.createFilter());
13829
14259
  }
13830
- test(path14) {
13831
- return this._test(path14, this._testCache, true);
14260
+ test(path16) {
14261
+ return this._test(path16, this._testCache, true);
13832
14262
  }
13833
14263
  }
13834
14264
  var factory = (options) => new Ignore2(options);
13835
- var isPathValid = (path14) => checkPath(path14 && checkPath.convert(path14), path14, RETURN_FALSE);
14265
+ var isPathValid = (path16) => checkPath(path16 && checkPath.convert(path16), path16, RETURN_FALSE);
13836
14266
  factory.isPathValid = isPathValid;
13837
14267
  factory.default = factory;
13838
14268
  module.exports = factory;
@@ -13840,7 +14270,7 @@ var require_ignore = __commonJS((exports, module) => {
13840
14270
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
13841
14271
  checkPath.convert = makePosix;
13842
14272
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
13843
- checkPath.isNotRelative = (path14) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path14) || isNotRelative(path14);
14273
+ checkPath.isNotRelative = (path16) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path16) || isNotRelative(path16);
13844
14274
  }
13845
14275
  });
13846
14276
 
@@ -13902,13 +14332,13 @@ function validatePolicy(policy, opts = {}) {
13902
14332
  }
13903
14333
  }
13904
14334
  }
13905
- function matchesGlob2(path14, pattern) {
14335
+ function matchesGlob2(path16, pattern) {
13906
14336
  let re = regexCache.get(pattern);
13907
14337
  if (!re) {
13908
14338
  re = globToRegex(pattern);
13909
14339
  regexCache.set(pattern, re);
13910
14340
  }
13911
- return re.test(path14);
14341
+ return re.test(path16);
13912
14342
  }
13913
14343
  var MAX_MATCH_WORK = 1e5, MAX_IGNORE_PATTERNS2 = 1024, DEFAULT_POLICY, applyPolicy = (filePath, policy) => {
13914
14344
  const normalized = filePath.trim();
@@ -13959,8 +14389,8 @@ var init_capture_policy = __esm(() => {
13959
14389
  });
13960
14390
 
13961
14391
  // ../../packages/core/dist/services/search/ignore-patterns.js
13962
- import fs10 from "fs/promises";
13963
- import path14 from "path";
14392
+ import fs11 from "fs/promises";
14393
+ import path16 from "path";
13964
14394
  function buildExtensionGlob(extensions2) {
13965
14395
  return extensions2.map((ext2) => `**/*${ext2}`);
13966
14396
  }
@@ -13983,8 +14413,8 @@ async function loadProjectIgnore(projectPath) {
13983
14413
  const ig = ignore();
13984
14414
  ig.add(DEFAULT_IGNORES);
13985
14415
  try {
13986
- const gitignorePath = path14.join(projectPath, ".gitignore");
13987
- const gitignoreContent = await fs10.readFile(gitignorePath, "utf8");
14416
+ const gitignorePath = path16.join(projectPath, ".gitignore");
14417
+ const gitignoreContent = await fs11.readFile(gitignorePath, "utf8");
13988
14418
  const rules = gitignoreContent.split(`
13989
14419
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
13990
14420
  ig.add(rules);
@@ -14235,8 +14665,8 @@ var init_alias_resolver = __esm(() => {
14235
14665
  });
14236
14666
 
14237
14667
  // ../../packages/core/dist/services/search/index-manager.js
14238
- import fs11 from "fs";
14239
- import path15 from "path";
14668
+ import fs12 from "fs";
14669
+ import path17 from "path";
14240
14670
 
14241
14671
  class IndexManager {
14242
14672
  metadataCache = new Map;
@@ -14329,9 +14759,9 @@ class IndexManager {
14329
14759
  const fileMetadata = {};
14330
14760
  let totalSize = 0;
14331
14761
  for (const filePath of indexedFiles) {
14332
- const fullPath = path15.join(projectPath, filePath);
14762
+ const fullPath = path17.join(projectPath, filePath);
14333
14763
  try {
14334
- const stat2 = await fs11.promises.stat(fullPath);
14764
+ const stat2 = await fs12.promises.stat(fullPath);
14335
14765
  fileMetadata[filePath] = {
14336
14766
  path: filePath,
14337
14767
  mtime: stat2.mtimeMs,
@@ -14382,9 +14812,9 @@ class IndexManager {
14382
14812
  if (ig.ignores(match2)) {
14383
14813
  continue;
14384
14814
  }
14385
- const fullPath = path15.join(projectPath, match2);
14815
+ const fullPath = path17.join(projectPath, match2);
14386
14816
  try {
14387
- const stat2 = await fs11.promises.stat(fullPath);
14817
+ const stat2 = await fs12.promises.stat(fullPath);
14388
14818
  files.set(match2, {
14389
14819
  path: match2,
14390
14820
  mtime: stat2.mtimeMs,
@@ -14835,10 +15265,10 @@ function mergeDefs(...defs) {
14835
15265
  function cloneDef(schema) {
14836
15266
  return mergeDefs(schema._zod.def);
14837
15267
  }
14838
- function getElementAtPath(obj, path16) {
14839
- if (!path16)
15268
+ function getElementAtPath(obj, path18) {
15269
+ if (!path18)
14840
15270
  return obj;
14841
- return path16.reduce((acc, key) => acc?.[key], obj);
15271
+ return path18.reduce((acc, key) => acc?.[key], obj);
14842
15272
  }
14843
15273
  function promiseAllObject(promisesObj) {
14844
15274
  const keys = Object.keys(promisesObj);
@@ -15166,11 +15596,11 @@ function explicitlyAborted(x, startIndex = 0) {
15166
15596
  }
15167
15597
  return false;
15168
15598
  }
15169
- function prefixIssues(path16, issues) {
15599
+ function prefixIssues(path18, issues) {
15170
15600
  return issues.map((iss) => {
15171
15601
  var _a4;
15172
15602
  (_a4 = iss).path ?? (_a4.path = []);
15173
- iss.path.unshift(path16);
15603
+ iss.path.unshift(path18);
15174
15604
  return iss;
15175
15605
  });
15176
15606
  }
@@ -15383,16 +15813,16 @@ function flattenError(error, mapper = (issue2) => issue2.message) {
15383
15813
  }
15384
15814
  function formatError(error, mapper = (issue2) => issue2.message) {
15385
15815
  const fieldErrors = { _errors: [] };
15386
- const processError = (error2, path16 = []) => {
15816
+ const processError = (error2, path18 = []) => {
15387
15817
  for (const issue2 of error2.issues) {
15388
15818
  if (issue2.code === "invalid_union" && issue2.errors.length) {
15389
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
15819
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
15390
15820
  } else if (issue2.code === "invalid_key") {
15391
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15821
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15392
15822
  } else if (issue2.code === "invalid_element") {
15393
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15823
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15394
15824
  } else {
15395
- const fullpath = [...path16, ...issue2.path];
15825
+ const fullpath = [...path18, ...issue2.path];
15396
15826
  if (fullpath.length === 0) {
15397
15827
  fieldErrors._errors.push(mapper(issue2));
15398
15828
  } else {
@@ -15419,17 +15849,17 @@ function formatError(error, mapper = (issue2) => issue2.message) {
15419
15849
  }
15420
15850
  function treeifyError(error, mapper = (issue2) => issue2.message) {
15421
15851
  const result = { errors: [] };
15422
- const processError = (error2, path16 = []) => {
15852
+ const processError = (error2, path18 = []) => {
15423
15853
  var _a4, _b;
15424
15854
  for (const issue2 of error2.issues) {
15425
15855
  if (issue2.code === "invalid_union" && issue2.errors.length) {
15426
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
15856
+ issue2.errors.map((issues) => processError({ issues }, [...path18, ...issue2.path]));
15427
15857
  } else if (issue2.code === "invalid_key") {
15428
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15858
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15429
15859
  } else if (issue2.code === "invalid_element") {
15430
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
15860
+ processError({ issues: issue2.issues }, [...path18, ...issue2.path]);
15431
15861
  } else {
15432
- const fullpath = [...path16, ...issue2.path];
15862
+ const fullpath = [...path18, ...issue2.path];
15433
15863
  if (fullpath.length === 0) {
15434
15864
  result.errors.push(mapper(issue2));
15435
15865
  continue;
@@ -15461,8 +15891,8 @@ function treeifyError(error, mapper = (issue2) => issue2.message) {
15461
15891
  }
15462
15892
  function toDotPath(_path) {
15463
15893
  const segs = [];
15464
- const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
15465
- for (const seg of path16) {
15894
+ const path18 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
15895
+ for (const seg of path18) {
15466
15896
  if (typeof seg === "number")
15467
15897
  segs.push(`[${seg}]`);
15468
15898
  else if (typeof seg === "symbol")
@@ -28465,13 +28895,13 @@ function resolveRef(ref, ctx) {
28465
28895
  if (!ref.startsWith("#")) {
28466
28896
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
28467
28897
  }
28468
- const path16 = ref.slice(1).split("/").filter(Boolean);
28469
- if (path16.length === 0) {
28898
+ const path18 = ref.slice(1).split("/").filter(Boolean);
28899
+ if (path18.length === 0) {
28470
28900
  return ctx.rootSchema;
28471
28901
  }
28472
28902
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
28473
- if (path16[0] === defsKey) {
28474
- const key = path16[1];
28903
+ if (path18[0] === defsKey) {
28904
+ const key = path18[1];
28475
28905
  if (!key || !ctx.defs[key]) {
28476
28906
  throw new Error(`Reference not found: ${ref}`);
28477
28907
  }
@@ -29960,8 +30390,8 @@ class ParseStatus2 {
29960
30390
  }
29961
30391
  }
29962
30392
  var makeIssue2 = (params) => {
29963
- const { data, path: path16, errorMaps, issueData } = params;
29964
- const fullPath = [...path16, ...issueData.path || []];
30393
+ const { data, path: path18, errorMaps, issueData } = params;
30394
+ const fullPath = [...path18, ...issueData.path || []];
29965
30395
  const fullIssue = {
29966
30396
  ...issueData,
29967
30397
  path: fullPath
@@ -30006,11 +30436,11 @@ var init_errorUtil = __esm(() => {
30006
30436
 
30007
30437
  // ../../node_modules/zod/v3/types.js
30008
30438
  class ParseInputLazyPath2 {
30009
- constructor(parent, value, path16, key) {
30439
+ constructor(parent, value, path18, key) {
30010
30440
  this._cachedPath = [];
30011
30441
  this.parent = parent;
30012
30442
  this.data = value;
30013
- this._path = path16;
30443
+ this._path = path18;
30014
30444
  this._key = key;
30015
30445
  }
30016
30446
  get path() {
@@ -36007,19 +36437,19 @@ var require_token_io = __commonJS((exports, module) => {
36007
36437
  getUserDataDir: () => getUserDataDir
36008
36438
  });
36009
36439
  module.exports = __toCommonJS2(token_io_exports);
36010
- var import_path10 = __toESM2(__require("path"));
36011
- var import_fs7 = __toESM2(__require("fs"));
36440
+ var import_path11 = __toESM2(__require("path"));
36441
+ var import_fs8 = __toESM2(__require("fs"));
36012
36442
  var import_os3 = __toESM2(__require("os"));
36013
36443
  var import_token_error = require_token_error();
36014
36444
  function findRootDir() {
36015
36445
  try {
36016
36446
  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)) {
36447
+ while (dir !== import_path11.default.dirname(dir)) {
36448
+ const pkgPath = import_path11.default.join(dir, ".vercel");
36449
+ if (import_fs8.default.existsSync(pkgPath)) {
36020
36450
  return dir;
36021
36451
  }
36022
- dir = import_path10.default.dirname(dir);
36452
+ dir = import_path11.default.dirname(dir);
36023
36453
  }
36024
36454
  } catch (e) {
36025
36455
  throw new import_token_error.VercelOidcTokenError("Token refresh only supported in node server environments");
@@ -36032,9 +36462,9 @@ var require_token_io = __commonJS((exports, module) => {
36032
36462
  }
36033
36463
  switch (import_os3.default.platform()) {
36034
36464
  case "darwin":
36035
- return import_path10.default.join(import_os3.default.homedir(), "Library/Application Support");
36465
+ return import_path11.default.join(import_os3.default.homedir(), "Library/Application Support");
36036
36466
  case "linux":
36037
- return import_path10.default.join(import_os3.default.homedir(), ".local/share");
36467
+ return import_path11.default.join(import_os3.default.homedir(), ".local/share");
36038
36468
  case "win32":
36039
36469
  if (process.env.LOCALAPPDATA) {
36040
36470
  return process.env.LOCALAPPDATA;
@@ -36075,23 +36505,23 @@ var require_auth_config = __commonJS((exports, module) => {
36075
36505
  writeAuthConfig: () => writeAuthConfig
36076
36506
  });
36077
36507
  module.exports = __toCommonJS2(auth_config_exports);
36078
- var fs12 = __toESM2(__require("fs"));
36079
- var path16 = __toESM2(__require("path"));
36508
+ var fs13 = __toESM2(__require("fs"));
36509
+ var path18 = __toESM2(__require("path"));
36080
36510
  var import_token_util = require_token_util();
36081
36511
  function getAuthConfigPath() {
36082
36512
  const dataDir = (0, import_token_util.getVercelDataDir)();
36083
36513
  if (!dataDir) {
36084
36514
  throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);
36085
36515
  }
36086
- return path16.join(dataDir, "auth.json");
36516
+ return path18.join(dataDir, "auth.json");
36087
36517
  }
36088
36518
  function readAuthConfig() {
36089
36519
  try {
36090
36520
  const authPath = getAuthConfigPath();
36091
- if (!fs12.existsSync(authPath)) {
36521
+ if (!fs13.existsSync(authPath)) {
36092
36522
  return null;
36093
36523
  }
36094
- const content = fs12.readFileSync(authPath, "utf8");
36524
+ const content = fs13.readFileSync(authPath, "utf8");
36095
36525
  if (!content) {
36096
36526
  return null;
36097
36527
  }
@@ -36102,11 +36532,11 @@ var require_auth_config = __commonJS((exports, module) => {
36102
36532
  }
36103
36533
  function writeAuthConfig(config3) {
36104
36534
  const authPath = getAuthConfigPath();
36105
- const authDir = path16.dirname(authPath);
36106
- if (!fs12.existsSync(authDir)) {
36107
- fs12.mkdirSync(authDir, { mode: 504, recursive: true });
36535
+ const authDir = path18.dirname(authPath);
36536
+ if (!fs13.existsSync(authDir)) {
36537
+ fs13.mkdirSync(authDir, { mode: 504, recursive: true });
36108
36538
  }
36109
- fs12.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
36539
+ fs13.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
36110
36540
  }
36111
36541
  function isValidAccessToken(authConfig, expirationBufferMs = 0) {
36112
36542
  if (!authConfig.token)
@@ -36281,8 +36711,8 @@ var require_token_util = __commonJS((exports, module) => {
36281
36711
  saveToken: () => saveToken
36282
36712
  });
36283
36713
  module.exports = __toCommonJS2(token_util_exports);
36284
- var path16 = __toESM2(__require("path"));
36285
- var fs12 = __toESM2(__require("fs"));
36714
+ var path18 = __toESM2(__require("path"));
36715
+ var fs13 = __toESM2(__require("fs"));
36286
36716
  var import_token_error = require_token_error();
36287
36717
  var import_token_io = require_token_io();
36288
36718
  var import_auth_config = require_auth_config();
@@ -36294,7 +36724,7 @@ var require_token_util = __commonJS((exports, module) => {
36294
36724
  if (!dataDir) {
36295
36725
  return null;
36296
36726
  }
36297
- return path16.join(dataDir, vercelFolder);
36727
+ return path18.join(dataDir, vercelFolder);
36298
36728
  }
36299
36729
  async function getVercelToken2(options) {
36300
36730
  const authConfig = (0, import_auth_config.readAuthConfig)();
@@ -36362,11 +36792,11 @@ var require_token_util = __commonJS((exports, module) => {
36362
36792
  if (!dir) {
36363
36793
  throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");
36364
36794
  }
36365
- const prjPath = path16.join(dir, ".vercel", "project.json");
36366
- if (!fs12.existsSync(prjPath)) {
36795
+ const prjPath = path18.join(dir, ".vercel", "project.json");
36796
+ if (!fs13.existsSync(prjPath)) {
36367
36797
  throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");
36368
36798
  }
36369
- const prj = JSON.parse(fs12.readFileSync(prjPath, "utf8"));
36799
+ const prj = JSON.parse(fs13.readFileSync(prjPath, "utf8"));
36370
36800
  if (typeof prj.projectId !== "string" && typeof prj.orgId !== "string") {
36371
36801
  throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");
36372
36802
  }
@@ -36377,11 +36807,11 @@ var require_token_util = __commonJS((exports, module) => {
36377
36807
  if (!dir) {
36378
36808
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
36379
36809
  }
36380
- const tokenPath = path16.join(dir, "com.vercel.token", `${projectId}.json`);
36810
+ const tokenPath = path18.join(dir, "com.vercel.token", `${projectId}.json`);
36381
36811
  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);
36812
+ fs13.mkdirSync(path18.dirname(tokenPath), { mode: 504, recursive: true });
36813
+ fs13.writeFileSync(tokenPath, tokenJson);
36814
+ fs13.chmodSync(tokenPath, 432);
36385
36815
  return;
36386
36816
  }
36387
36817
  function loadToken(projectId) {
@@ -36389,11 +36819,11 @@ var require_token_util = __commonJS((exports, module) => {
36389
36819
  if (!dir) {
36390
36820
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
36391
36821
  }
36392
- const tokenPath = path16.join(dir, "com.vercel.token", `${projectId}.json`);
36393
- if (!fs12.existsSync(tokenPath)) {
36822
+ const tokenPath = path18.join(dir, "com.vercel.token", `${projectId}.json`);
36823
+ if (!fs13.existsSync(tokenPath)) {
36394
36824
  return null;
36395
36825
  }
36396
- const token = JSON.parse(fs12.readFileSync(tokenPath, "utf8"));
36826
+ const token = JSON.parse(fs13.readFileSync(tokenPath, "utf8"));
36397
36827
  assertVercelOidcTokenResponse(token);
36398
36828
  return token;
36399
36829
  }
@@ -47235,37 +47665,37 @@ function createOpenAI(options = {}) {
47235
47665
  }, `ai-sdk/openai/${VERSION4}`);
47236
47666
  const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
47237
47667
  provider: `${providerName}.chat`,
47238
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47668
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47239
47669
  headers: getHeaders,
47240
47670
  fetch: options.fetch
47241
47671
  });
47242
47672
  const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
47243
47673
  provider: `${providerName}.completion`,
47244
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47674
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47245
47675
  headers: getHeaders,
47246
47676
  fetch: options.fetch
47247
47677
  });
47248
47678
  const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
47249
47679
  provider: `${providerName}.embedding`,
47250
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47680
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47251
47681
  headers: getHeaders,
47252
47682
  fetch: options.fetch
47253
47683
  });
47254
47684
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
47255
47685
  provider: `${providerName}.image`,
47256
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47686
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47257
47687
  headers: getHeaders,
47258
47688
  fetch: options.fetch
47259
47689
  });
47260
47690
  const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
47261
47691
  provider: `${providerName}.transcription`,
47262
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47692
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47263
47693
  headers: getHeaders,
47264
47694
  fetch: options.fetch
47265
47695
  });
47266
47696
  const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
47267
47697
  provider: `${providerName}.speech`,
47268
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47698
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47269
47699
  headers: getHeaders,
47270
47700
  fetch: options.fetch
47271
47701
  });
@@ -47278,7 +47708,7 @@ function createOpenAI(options = {}) {
47278
47708
  const createResponsesModel = (modelId) => {
47279
47709
  return new OpenAIResponsesLanguageModel(modelId, {
47280
47710
  provider: `${providerName}.responses`,
47281
- url: ({ path: path16 }) => `${baseURL}${path16}`,
47711
+ url: ({ path: path18 }) => `${baseURL}${path18}`,
47282
47712
  headers: getHeaders,
47283
47713
  fetch: options.fetch,
47284
47714
  fileIdPrefixes: ["file-"]
@@ -63823,26 +64253,26 @@ var require_process = __commonJS((exports, module) => {
63823
64253
 
63824
64254
  // ../../node_modules/detect-libc/lib/filesystem.js
63825
64255
  var require_filesystem = __commonJS((exports, module) => {
63826
- var fs12 = __require("fs");
64256
+ var fs13 = __require("fs");
63827
64257
  var LDD_PATH = "/usr/bin/ldd";
63828
64258
  var SELF_PATH = "/proc/self/exe";
63829
64259
  var MAX_LENGTH = 2048;
63830
- var readFileSync2 = (path16) => {
63831
- const fd = fs12.openSync(path16, "r");
64260
+ var readFileSync2 = (path18) => {
64261
+ const fd = fs13.openSync(path18, "r");
63832
64262
  const buffer = Buffer.alloc(MAX_LENGTH);
63833
- const bytesRead = fs12.readSync(fd, buffer, 0, MAX_LENGTH, 0);
63834
- fs12.close(fd, () => {});
64263
+ const bytesRead = fs13.readSync(fd, buffer, 0, MAX_LENGTH, 0);
64264
+ fs13.close(fd, () => {});
63835
64265
  return buffer.subarray(0, bytesRead);
63836
64266
  };
63837
- var readFile = (path16) => new Promise((resolve4, reject) => {
63838
- fs12.open(path16, "r", (err, fd) => {
64267
+ var readFile = (path18) => new Promise((resolve4, reject) => {
64268
+ fs13.open(path18, "r", (err, fd) => {
63839
64269
  if (err) {
63840
64270
  reject(err);
63841
64271
  } else {
63842
64272
  const buffer = Buffer.alloc(MAX_LENGTH);
63843
- fs12.read(fd, buffer, 0, MAX_LENGTH, 0, (_2, bytesRead) => {
64273
+ fs13.read(fd, buffer, 0, MAX_LENGTH, 0, (_2, bytesRead) => {
63844
64274
  resolve4(buffer.subarray(0, bytesRead));
63845
- fs12.close(fd, () => {});
64275
+ fs13.close(fd, () => {});
63846
64276
  });
63847
64277
  }
63848
64278
  });
@@ -63947,11 +64377,11 @@ var require_detect_libc = __commonJS((exports, module) => {
63947
64377
  }
63948
64378
  return null;
63949
64379
  };
63950
- var familyFromInterpreterPath = (path16) => {
63951
- if (path16) {
63952
- if (path16.includes("/ld-musl-")) {
64380
+ var familyFromInterpreterPath = (path18) => {
64381
+ if (path18) {
64382
+ if (path18.includes("/ld-musl-")) {
63953
64383
  return MUSL;
63954
- } else if (path16.includes("/ld-linux-")) {
64384
+ } else if (path18.includes("/ld-linux-")) {
63955
64385
  return GLIBC;
63956
64386
  }
63957
64387
  }
@@ -63996,8 +64426,8 @@ var require_detect_libc = __commonJS((exports, module) => {
63996
64426
  cachedFamilyInterpreter = null;
63997
64427
  try {
63998
64428
  const selfContent = await readFile(SELF_PATH);
63999
- const path16 = interpreterPath(selfContent);
64000
- cachedFamilyInterpreter = familyFromInterpreterPath(path16);
64429
+ const path18 = interpreterPath(selfContent);
64430
+ cachedFamilyInterpreter = familyFromInterpreterPath(path18);
64001
64431
  } catch (e) {}
64002
64432
  return cachedFamilyInterpreter;
64003
64433
  };
@@ -64008,8 +64438,8 @@ var require_detect_libc = __commonJS((exports, module) => {
64008
64438
  cachedFamilyInterpreter = null;
64009
64439
  try {
64010
64440
  const selfContent = readFileSync2(SELF_PATH);
64011
- const path16 = interpreterPath(selfContent);
64012
- cachedFamilyInterpreter = familyFromInterpreterPath(path16);
64441
+ const path18 = interpreterPath(selfContent);
64442
+ cachedFamilyInterpreter = familyFromInterpreterPath(path18);
64013
64443
  } catch (e) {}
64014
64444
  return cachedFamilyInterpreter;
64015
64445
  };
@@ -65671,18 +66101,18 @@ var require_sharp = __commonJS((exports, module) => {
65671
66101
  `@img/sharp-${runtimePlatform}/sharp.node`,
65672
66102
  "@img/sharp-wasm32/sharp.node"
65673
66103
  ];
65674
- var path16;
66104
+ var path18;
65675
66105
  var sharp;
65676
66106
  var errors5 = [];
65677
- for (path16 of paths) {
66107
+ for (path18 of paths) {
65678
66108
  try {
65679
- sharp = __require(path16);
66109
+ sharp = __require(path18);
65680
66110
  break;
65681
66111
  } catch (err) {
65682
66112
  errors5.push(err);
65683
66113
  }
65684
66114
  }
65685
- if (sharp && path16.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
66115
+ if (sharp && path18.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
65686
66116
  const err = new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");
65687
66117
  err.code = "Unsupported CPU";
65688
66118
  errors5.push(err);
@@ -65691,7 +66121,7 @@ var require_sharp = __commonJS((exports, module) => {
65691
66121
  if (sharp) {
65692
66122
  module.exports = sharp;
65693
66123
  } else {
65694
- const [isLinux, isMacOs, isWindows] = ["linux", "darwin", "win32"].map((os6) => runtimePlatform.startsWith(os6));
66124
+ const [isLinux, isMacOs, isWindows] = ["linux", "darwin", "win32"].map((os8) => runtimePlatform.startsWith(os8));
65695
66125
  const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`];
65696
66126
  errors5.forEach((err) => {
65697
66127
  if (err.code !== "MODULE_NOT_FOUND") {
@@ -65704,9 +66134,9 @@ var require_sharp = __commonJS((exports, module) => {
65704
66134
  const { found, expected } = isUnsupportedNodeRuntime();
65705
66135
  help.push("- Please upgrade Node.js:", ` Found ${found}`, ` Requires ${expected}`);
65706
66136
  } 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`);
66137
+ const [os8, cpu] = runtimePlatform.split("-");
66138
+ const libc = os8.endsWith("musl") ? " --libc=musl" : "";
66139
+ 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
66140
  } else {
65711
66141
  help.push(`- Manually install libvips >= ${minimumLibvipsVersion}`, "- Add experimental WebAssembly-based dependencies:", " npm install --cpu=wasm32 sharp", " npm install @img/sharp-wasm32");
65712
66142
  }
@@ -66966,7 +67396,7 @@ var require_operation = __commonJS((exports, module) => {
66966
67396
  float: "float",
66967
67397
  approximate: "approximate"
66968
67398
  };
66969
- function rotate(angle, options) {
67399
+ function rotate2(angle, options) {
66970
67400
  if (!is.defined(angle)) {
66971
67401
  return this.autoOrient();
66972
67402
  }
@@ -67393,7 +67823,7 @@ var require_operation = __commonJS((exports, module) => {
67393
67823
  module.exports = (Sharp) => {
67394
67824
  Object.assign(Sharp.prototype, {
67395
67825
  autoOrient,
67396
- rotate,
67826
+ rotate: rotate2,
67397
67827
  flip,
67398
67828
  flop,
67399
67829
  affine,
@@ -68544,15 +68974,15 @@ var require_color = __commonJS((exports, module) => {
68544
68974
  };
68545
68975
  }
68546
68976
  function wrapConversion(toModel, graph) {
68547
- const path16 = [graph[toModel].parent, toModel];
68977
+ const path18 = [graph[toModel].parent, toModel];
68548
68978
  let fn = conversions_default[graph[toModel].parent][toModel];
68549
68979
  let cur = graph[toModel].parent;
68550
68980
  while (graph[cur].parent) {
68551
- path16.unshift(graph[cur].parent);
68981
+ path18.unshift(graph[cur].parent);
68552
68982
  fn = link(conversions_default[graph[cur].parent][cur], fn);
68553
68983
  cur = graph[cur].parent;
68554
68984
  }
68555
- fn.conversion = path16;
68985
+ fn.conversion = path18;
68556
68986
  return fn;
68557
68987
  }
68558
68988
  function route(fromModel) {
@@ -69157,7 +69587,7 @@ var require_output = __commonJS((exports, module) => {
69157
69587
  Copyright 2013 Lovell Fuller and others.
69158
69588
  SPDX-License-Identifier: Apache-2.0
69159
69589
  */
69160
- var path16 = __require("path");
69590
+ var path18 = __require("path");
69161
69591
  var is = require_is();
69162
69592
  var sharp = require_sharp();
69163
69593
  var formats = new Map([
@@ -69188,9 +69618,9 @@ var require_output = __commonJS((exports, module) => {
69188
69618
  let err;
69189
69619
  if (!is.string(fileOut)) {
69190
69620
  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)) {
69621
+ } else if (is.string(this.options.input.file) && path18.resolve(this.options.input.file) === path18.resolve(fileOut)) {
69192
69622
  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) {
69623
+ } else if (jp2Regex.test(path18.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
69194
69624
  err = errJp2Save();
69195
69625
  }
69196
69626
  if (err) {
@@ -76437,11 +76867,11 @@ var init_transformers_node = __esm(() => {
76437
76867
  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
76868
  }
76439
76869
  for (let i = 0;i < num_chunks; ++i) {
76440
- const path16 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
76441
- const fullPath = `${options.subfolder ?? ""}/${path16}`;
76870
+ const path18 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
76871
+ const fullPath = `${options.subfolder ?? ""}/${path18}`;
76442
76872
  externalDataPromises.push(new Promise(async (resolve4, reject) => {
76443
76873
  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);
76874
+ resolve4(data instanceof Uint8Array ? { path: path18, data } : path18);
76445
76875
  }));
76446
76876
  }
76447
76877
  } else if (session_options.externalData !== undefined) {
@@ -89505,7 +89935,7 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
89505
89935
  const blob = new Blob([wav], { type: "audio/wav" });
89506
89936
  return blob;
89507
89937
  }
89508
- async save(path16) {
89938
+ async save(path18) {
89509
89939
  let fn;
89510
89940
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_BROWSER_ENV) {
89511
89941
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_WEBWORKER_ENV) {
@@ -89513,14 +89943,14 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
89513
89943
  }
89514
89944
  fn = _core_js__WEBPACK_IMPORTED_MODULE_2__.saveBlob;
89515
89945
  } else if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_FS_AVAILABLE) {
89516
- fn = async (path17, blob) => {
89946
+ fn = async (path19, blob) => {
89517
89947
  let buffer = await blob.arrayBuffer();
89518
- node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path17, Buffer.from(buffer));
89948
+ node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path19, Buffer.from(buffer));
89519
89949
  };
89520
89950
  } else {
89521
89951
  throw new Error("Unable to save because filesystem is disabled in this environment.");
89522
89952
  }
89523
- await fn(path16, this.toBlob());
89953
+ await fn(path18, this.toBlob());
89524
89954
  }
89525
89955
  }
89526
89956
  },
@@ -89616,11 +90046,11 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
89616
90046
  function calculateReflectOffset(i, w) {
89617
90047
  return Math.abs((i + w) % (2 * w) - w);
89618
90048
  }
89619
- function saveBlob(path16, blob) {
90049
+ function saveBlob(path18, blob) {
89620
90050
  const dataURL = URL.createObjectURL(blob);
89621
90051
  const downloadLink = document.createElement("a");
89622
90052
  downloadLink.href = dataURL;
89623
- downloadLink.download = path16;
90053
+ downloadLink.download = path18;
89624
90054
  downloadLink.click();
89625
90055
  downloadLink.remove();
89626
90056
  URL.revokeObjectURL(dataURL);
@@ -90221,8 +90651,8 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
90221
90651
  }
90222
90652
 
90223
90653
  class FileCache {
90224
- constructor(path16) {
90225
- this.path = path16;
90654
+ constructor(path18) {
90655
+ this.path = path18;
90226
90656
  }
90227
90657
  async match(request) {
90228
90658
  let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].join(this.path, request);
@@ -90978,20 +91408,20 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
90978
91408
  }
90979
91409
  return this;
90980
91410
  }
90981
- async save(path16) {
91411
+ async save(path18) {
90982
91412
  if (IS_BROWSER_OR_WEBWORKER) {
90983
91413
  if (_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV) {
90984
91414
  throw new Error("Unable to save an image from a Web Worker.");
90985
91415
  }
90986
- const extension = path16.split(".").pop().toLowerCase();
91416
+ const extension = path18.split(".").pop().toLowerCase();
90987
91417
  const mime2 = CONTENT_TYPE_MAP.get(extension) ?? "image/png";
90988
91418
  const blob = await this.toBlob(mime2);
90989
- (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path16, blob);
91419
+ (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path18, blob);
90990
91420
  } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) {
90991
91421
  throw new Error("Unable to save the image because filesystem is disabled in this environment.");
90992
91422
  } else {
90993
91423
  const img = this.toSharp();
90994
- return await img.toFile(path16);
91424
+ return await img.toFile(path18);
90995
91425
  }
90996
91426
  }
90997
91427
  toSharp() {
@@ -94518,20 +94948,20 @@ function getRetryDelay(attempt, config3) {
94518
94948
  return Math.min(delay2, config3.maxDelay);
94519
94949
  }
94520
94950
  async function withRetry(fn, config3, context2) {
94521
- let lastError;
94951
+ let lastError2;
94522
94952
  for (let attempt = 0;attempt <= config3.maxRetries; attempt++) {
94523
94953
  try {
94524
94954
  return await fn();
94525
94955
  } catch (error51) {
94526
- lastError = error51;
94956
+ lastError2 = error51;
94527
94957
  if (attempt < config3.maxRetries) {
94528
94958
  const delay2 = getRetryDelay(attempt, config3);
94529
- logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError.message });
94959
+ logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError2.message });
94530
94960
  await sleep(delay2);
94531
94961
  }
94532
94962
  }
94533
94963
  }
94534
- throw new Error(`${context2} failed after ${config3.maxRetries + 1} attempts: ${lastError?.message}`);
94964
+ throw new Error(`${context2} failed after ${config3.maxRetries + 1} attempts: ${lastError2?.message}`);
94535
94965
  }
94536
94966
  async function withTimeout(fn, timeoutMs, context2) {
94537
94967
  let timeoutId;
@@ -100217,7 +100647,7 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a12;
100217
100647
  function ns(e = Yo, t2 = Yo) {
100218
100648
  return (r2) => e(t2(r2));
100219
100649
  }
100220
- function os6({ dataPath: e, modelName: t2, args: r2, runtimeDataModel: n2 }) {
100650
+ function os8({ dataPath: e, modelName: t2, args: r2, runtimeDataModel: n2 }) {
100221
100651
  let i = { modelName: t2, args: r2 ?? {} }, o = dp(e);
100222
100652
  if (!o || o.length === 0)
100223
100653
  return i;
@@ -100522,10 +100952,10 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a12;
100522
100952
  super(t2, "P2023", r2);
100523
100953
  }
100524
100954
  };
100525
- var fs12 = new WeakMap;
100955
+ var fs13 = new WeakMap;
100526
100956
  function Ep(e) {
100527
- let t2 = fs12.get(e);
100528
- return t2 || (t2 = Object.entries(e), fs12.set(e, t2)), t2;
100957
+ let t2 = fs13.get(e);
100958
+ return t2 || (t2 = Object.entries(e), fs13.set(e, t2)), t2;
100529
100959
  }
100530
100960
  function hs(e, t2, r2) {
100531
100961
  switch (t2.type) {
@@ -104090,7 +104520,7 @@ new PrismaClient({
104090
104520
  let m2 = await es(this, d);
104091
104521
  if (!d.model)
104092
104522
  return m2;
104093
- let g = os6({ dataPath: d.dataPath, modelName: d.model, args: d.args, runtimeDataModel: this._runtimeDataModel });
104523
+ let g = os8({ dataPath: d.dataPath, modelName: d.model, args: d.args, runtimeDataModel: this._runtimeDataModel });
104094
104524
  return Wo({ result: m2, modelName: g.modelName, args: g.args, extensions: this._extensions, runtimeDataModel: this._runtimeDataModel, globalOmit: this._globalOmit });
104095
104525
  };
104096
104526
  return this._tracingHelper.runInChildSpan(s.operation, () => new zl.AsyncResource("prisma-client-request").runInAsyncScope(() => a12(o)));
@@ -104493,7 +104923,7 @@ var require_prisma = __commonJS((exports) => {
104493
104923
  Prisma.JsonNull = JsonNull2;
104494
104924
  Prisma.AnyNull = AnyNull2;
104495
104925
  Prisma.NullTypes = NullTypes2;
104496
- var path16 = __require("path");
104926
+ var path18 = __require("path");
104497
104927
  exports.Prisma.TransactionIsolationLevel = makeStrictEnum2({
104498
104928
  ReadUncommitted: "ReadUncommitted",
104499
104929
  ReadCommitted: "ReadCommitted",
@@ -110641,7 +111071,7 @@ async function upsertWorkspace(ws) {
110641
111071
  }, { timeout: 60000, maxWait: 1e4 });
110642
111072
  }
110643
111073
  async function updateWorkspaceStatus(projectId, status2, opts) {
110644
- const lastError = typeof opts === "string" ? opts : opts?.lastError ?? null;
111074
+ const lastError2 = typeof opts === "string" ? opts : opts?.lastError ?? null;
110645
111075
  const filesCount = typeof opts === "object" ? opts?.filesCount : undefined;
110646
111076
  const chunksCount = typeof opts === "object" ? opts?.chunksCount : undefined;
110647
111077
  const symbolsCount = typeof opts === "object" ? opts?.symbolsCount : undefined;
@@ -110651,7 +111081,7 @@ async function updateWorkspaceStatus(projectId, status2, opts) {
110651
111081
  await tx.$executeRaw`
110652
111082
  UPDATE workspaces SET
110653
111083
  status = ${status2},
110654
- last_error = ${lastError},
111084
+ last_error = ${lastError2},
110655
111085
  last_indexed_at = ${lastIndexedAt ?? null},
110656
111086
  files_count = COALESCE(${filesCount ?? null}, files_count),
110657
111087
  chunks_count = COALESCE(${chunksCount ?? null}, chunks_count),
@@ -115995,10 +116425,10 @@ var init_chunker_code = __esm(() => {
115995
116425
  });
115996
116426
 
115997
116427
  // ../../packages/core/dist/services/search/smart-chunker.js
115998
- import path16 from "path";
116428
+ import path18 from "path";
115999
116429
  function smartChunk(content, filePath, config3 = {}) {
116000
116430
  const cfg = { ...DEFAULT_CONFIG, ...config3 };
116001
- const ext2 = path16.extname(filePath).toLowerCase();
116431
+ const ext2 = path18.extname(filePath).toLowerCase();
116002
116432
  const relativePath = filePath;
116003
116433
  const fileImports = isCodeFile(ext2) ? extractFileImports(content, ext2) : undefined;
116004
116434
  let chunks;
@@ -116305,8 +116735,8 @@ var init_managed_run_repository_pg = __esm(() => {
116305
116735
  });
116306
116736
 
116307
116737
  // ../../packages/core/dist/services/search/project-indexer.js
116308
- import fs12 from "fs/promises";
116309
- import path17 from "path";
116738
+ import fs13 from "fs/promises";
116739
+ import path19 from "path";
116310
116740
  import { randomUUID as randomUUID3 } from "crypto";
116311
116741
  async function runWithIndexLock(lockMap, projectId, work) {
116312
116742
  const prevLock = lockMap.get(projectId);
@@ -116349,7 +116779,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
116349
116779
  dot: false
116350
116780
  });
116351
116781
  const filteredFiles = files.filter((file3) => {
116352
- const relativePath = path17.relative(projectPath, file3);
116782
+ const relativePath = path19.relative(projectPath, file3);
116353
116783
  const shouldIgnore = ig.ignores(relativePath);
116354
116784
  if (shouldIgnore) {
116355
116785
  logger.debug("Ignoring file per .gitignore during indexing", {
@@ -116389,7 +116819,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
116389
116819
  });
116390
116820
  }
116391
116821
  }
116392
- const indexedFilesList = filteredFiles.map((f) => path17.relative(projectPath, f));
116822
+ const indexedFilesList = filteredFiles.map((f) => path19.relative(projectPath, f));
116393
116823
  await deps.indexManager.updateIndexMetadata(projectId, projectPath, indexedFilesList);
116394
116824
  logger.info("Project indexing completed", {
116395
116825
  projectId,
@@ -116514,7 +116944,7 @@ async function ensureFreshIndex(deps, projectId, projectPath, options = {}) {
116514
116944
  let errors5 = 0;
116515
116945
  for (const relativeFilePath of filesToReindex) {
116516
116946
  try {
116517
- const fullPath = path17.join(projectPath, relativeFilePath);
116947
+ const fullPath = path19.join(projectPath, relativeFilePath);
116518
116948
  const result = await deps.indexFile(fullPath, projectId, projectPath, centralityMap);
116519
116949
  filesIndexed++;
116520
116950
  chunksIndexed += result.chunks;
@@ -116565,8 +116995,8 @@ async function checkSearchAdmission(deps, projectId, projectPath) {
116565
116995
  }
116566
116996
  async function indexFile(deps, filePath, projectId, projectRoot, centralityMap) {
116567
116997
  projectId = await getProjectIdentityAliasResolver().resolve(projectId);
116568
- const content = await fs12.readFile(filePath, "utf-8");
116569
- const relativePath = path17.relative(projectRoot, filePath);
116998
+ const content = await fs13.readFile(filePath, "utf-8");
116999
+ const relativePath = path19.relative(projectRoot, filePath);
116570
117000
  const maxFileSize = config.get("security").maxFileSize || 1024 * 1024;
116571
117001
  if (content.length > maxFileSize) {
116572
117002
  logger.warn("File too large, skipping", {
@@ -116586,7 +117016,7 @@ async function indexFile(deps, filePath, projectId, projectRoot, centralityMap)
116586
117016
  chunkIndex: i,
116587
117017
  totalChunks: chunks.length,
116588
117018
  type: chunk.type,
116589
- language: path17.extname(filePath).slice(1),
117019
+ language: path19.extname(filePath).slice(1),
116590
117020
  lineStart: chunk.lineStart,
116591
117021
  lineEnd: chunk.lineEnd,
116592
117022
  label: chunk.label,
@@ -117431,8 +117861,8 @@ function stripNul(content) {
117431
117861
  }
117432
117862
 
117433
117863
  // ../../packages/core/dist/services/etl/stages/discover.js
117434
- import fs13 from "fs/promises";
117435
- import path18 from "path";
117864
+ import fs14 from "fs/promises";
117865
+ import path20 from "path";
117436
117866
  import { createHash as createHash5 } from "crypto";
117437
117867
 
117438
117868
  class DiscoverStage {
@@ -117458,7 +117888,7 @@ class DiscoverStage {
117458
117888
  dot: false,
117459
117889
  absolute: false
117460
117890
  });
117461
- relPaths = found.map((p) => path18.isAbsolute(p) ? path18.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
117891
+ relPaths = found.map((p) => path20.isAbsolute(p) ? path20.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
117462
117892
  }
117463
117893
  if (ctx.resumeCursor?.path) {
117464
117894
  const cursorPath = ctx.resumeCursor.path;
@@ -117517,10 +117947,10 @@ class DiscoverStage {
117517
117947
  return discovered;
117518
117948
  }
117519
117949
  async processFile(ctx, relativePath, forceReindex) {
117520
- const absolutePath = path18.join(ctx.projectPath, relativePath);
117950
+ const absolutePath = path20.join(ctx.projectPath, relativePath);
117521
117951
  try {
117522
- const stat2 = await fs13.stat(absolutePath);
117523
- const content = stripNul(await fs13.readFile(absolutePath, "utf-8"));
117952
+ const stat2 = await fs14.stat(absolutePath);
117953
+ const content = stripNul(await fs14.readFile(absolutePath, "utf-8"));
117524
117954
  const contentHash = createHash5("sha256").update(content).digest("hex");
117525
117955
  let needsReparse = forceReindex;
117526
117956
  if (!forceReindex) {
@@ -117563,8 +117993,8 @@ class DiscoverStage {
117563
117993
  ig.add(pattern);
117564
117994
  }
117565
117995
  try {
117566
- const gitignorePath = path18.join(projectPath, ".gitignore");
117567
- const gitignoreContent = await fs13.readFile(gitignorePath, "utf8");
117996
+ const gitignorePath = path20.join(projectPath, ".gitignore");
117997
+ const gitignoreContent = await fs14.readFile(gitignorePath, "utf8");
117568
117998
  const rules = gitignoreContent.split(`
117569
117999
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
117570
118000
  ig.add(rules);
@@ -118919,8 +119349,8 @@ function rustUseLeaves(node2, source, prefix = []) {
118919
119349
  }
118920
119350
  if (node2.type === "use_wildcard")
118921
119351
  return [{ path: [...prefix, "*"], glob: true }];
118922
- const path19 = rustPathSegments(node2, source);
118923
- return path19.length ? [{ path: [...prefix, ...path19] }] : [];
119352
+ const path21 = rustPathSegments(node2, source);
119353
+ return path21.length ? [{ path: [...prefix, ...path21] }] : [];
118924
119354
  }
118925
119355
  function functionalCaptures(captures, source, family) {
118926
119356
  if (family !== "clojure")
@@ -119892,8 +120322,8 @@ var init_structural_runtime = __esm(() => {
119892
120322
  });
119893
120323
 
119894
120324
  // ../../packages/core/dist/services/etl/stages/parse.js
119895
- import path19 from "path";
119896
- import fs14 from "fs/promises";
120325
+ import path21 from "path";
120326
+ import fs15 from "fs/promises";
119897
120327
  function resolveChunkerMaxChars() {
119898
120328
  const global2 = Number(process.env.EMBEDDING_MAX_CHARS);
119899
120329
  if (Number.isFinite(global2) && global2 > 0)
@@ -119921,8 +120351,8 @@ class ParseStage {
119921
120351
  const results = new Map;
119922
120352
  let processed = 0;
119923
120353
  const phases = [
119924
- files.filter((file3) => path19.extname(file3.relativePath).toLowerCase() !== ".h"),
119925
- files.filter((file3) => path19.extname(file3.relativePath).toLowerCase() === ".h")
120354
+ files.filter((file3) => path21.extname(file3.relativePath).toLowerCase() !== ".h"),
120355
+ files.filter((file3) => path21.extname(file3.relativePath).toLowerCase() === ".h")
119926
120356
  ];
119927
120357
  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
120358
  for (const batch of batches) {
@@ -119960,19 +120390,19 @@ class ParseStage {
119960
120390
  return files.map((file3) => results.get(file3.relativePath));
119961
120391
  }
119962
120392
  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)));
120393
+ const knownHeaders = new Set(files.filter((file3) => path21.extname(file3.relativePath).toLowerCase() === ".h").map((file3) => path21.posix.normalize(file3.relativePath)));
119964
120394
  const mutable = {
119965
120395
  ...ctx.structuralHeaderEvidenceByFile
119966
120396
  };
119967
120397
  for (const parsed of parsedFiles) {
119968
- const extension = path19.extname(parsed.file.relativePath).toLowerCase();
120398
+ const extension = path21.extname(parsed.file.relativePath).toLowerCase();
119969
120399
  const key = extension === ".c" ? "cImporters" : [".cpp", ".hpp"].includes(extension) ? "cppImporters" : undefined;
119970
120400
  if (!key)
119971
120401
  continue;
119972
120402
  for (const imported of parsed.rawImports) {
119973
120403
  if (!["c_include", "cpp_include"].includes(imported.form) || imported.specifier.startsWith("<"))
119974
120404
  continue;
119975
- const header = path19.posix.normalize(path19.posix.join(path19.posix.dirname(parsed.file.relativePath), imported.specifier));
120405
+ const header = path21.posix.normalize(path21.posix.join(path21.posix.dirname(parsed.file.relativePath), imported.specifier));
119976
120406
  if (!knownHeaders.has(header))
119977
120407
  continue;
119978
120408
  const existing = mutable[header] ?? {};
@@ -119983,9 +120413,9 @@ class ParseStage {
119983
120413
  }
119984
120414
  async parseFile(ctx, file3) {
119985
120415
  if (!file3.needsReparse) {
119986
- const extension = path19.extname(file3.relativePath).toLowerCase();
120416
+ const extension = path21.extname(file3.relativePath).toLowerCase();
119987
120417
  if ([".c", ".cpp", ".hpp"].includes(extension)) {
119988
- const content = file3.snapshotContent ?? await fs14.readFile(file3.absolutePath, "utf8");
120418
+ const content = file3.snapshotContent ?? await fs15.readFile(file3.absolutePath, "utf8");
119989
120419
  const outcome = await this.runtime.parse({ extension, source: Buffer.from(content) });
119990
120420
  if (outcome.status === "failed")
119991
120421
  throw new StructuralEtlParseError(file3.relativePath, outcome.failureKind, `Structural evidence parse failed (${outcome.failureKind})`, outcome.diagnosticCount, outcome.diagnostics.slice(0, 10));
@@ -119997,8 +120427,8 @@ class ParseStage {
119997
120427
  return { file: file3, chunks: [], symbols: [], rawImports: [], rawEdges: [] };
119998
120428
  }
119999
120429
  try {
120000
- const content = file3.snapshotContent ?? await fs14.readFile(file3.absolutePath, "utf-8");
120001
- const ext2 = path19.extname(file3.relativePath).toLowerCase();
120430
+ const content = file3.snapshotContent ?? await fs15.readFile(file3.absolutePath, "utf-8");
120431
+ const ext2 = path21.extname(file3.relativePath).toLowerCase();
120002
120432
  const chunkerMaxChars = resolveChunkerMaxChars();
120003
120433
  const chunks = smartChunk(content, file3.relativePath, chunkerMaxChars ? { maxChunkChars: chunkerMaxChars } : {});
120004
120434
  let symbols;
@@ -120552,7 +120982,7 @@ var init_resolver = __esm(() => {
120552
120982
  });
120553
120983
 
120554
120984
  // ../../packages/core/dist/services/structural/resolvers/typescript.js
120555
- import path20 from "path";
120985
+ import path22 from "path";
120556
120986
  function candidates(identities) {
120557
120987
  return Object.freeze(identities.map((identity) => Object.freeze({
120558
120988
  fqn: identity.fqn,
@@ -120647,7 +121077,7 @@ function probe(base, known, dialect = "typescript") {
120647
121077
  const bases = /\.[cm]?jsx?$/u.test(base) ? [base.replace(/\.[cm]?jsx?$/u, ".ts"), base.replace(/\.[cm]?jsx?$/u, ".tsx"), base] : [base];
120648
121078
  for (const candidateBase of bases)
120649
121079
  for (const suffix of DIALECT_PROBES[dialect] ?? [""]) {
120650
- const value = path20.posix.normalize(`${candidateBase}${suffix}`);
121080
+ const value = path22.posix.normalize(`${candidateBase}${suffix}`);
120651
121081
  if (!value.startsWith("../") && value !== ".." && known.has(value))
120652
121082
  return value;
120653
121083
  }
@@ -120656,7 +121086,7 @@ function probe(base, known, dialect = "typescript") {
120656
121086
  function resolveStructuralSpecifier(specifier, fromFile, build, dialect = "typescript") {
120657
121087
  const known = new Set(build.knownFiles.map(normalizeStructuralFile));
120658
121088
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
120659
- return probe(path20.posix.join(path20.posix.dirname(fromFile), specifier), known, dialect);
121089
+ return probe(path22.posix.join(path22.posix.dirname(fromFile), specifier), known, dialect);
120660
121090
  }
120661
121091
  const aliases = build.pathAliasesByFile?.[normalizeStructuralFile(fromFile)] ?? build.pathAliases ?? [];
120662
121092
  for (const alias of aliases) {
@@ -120920,7 +121350,7 @@ var init_scripting2 = __esm(() => {
120920
121350
  });
120921
121351
 
120922
121352
  // ../../packages/core/dist/services/structural/resolvers/systems.js
120923
- import path21 from "path";
121353
+ import path23 from "path";
120924
121354
  var DIALECTS, SYSTEMS_LANGUAGE_RESOLVER;
120925
121355
  var init_systems2 = __esm(() => {
120926
121356
  init_typescript2();
@@ -120939,7 +121369,7 @@ var init_systems2 = __esm(() => {
120939
121369
  const bindings = item.bindings.map((binding) => binding.imported === "*" && binding.local === "*" && unresolvedTarget && !unresolvedTarget.qualifier ? { ...binding, imported: unresolvedTarget.name, local: unresolvedTarget.name } : binding);
120940
121370
  if (item.specifier === "crate" || item.specifier.startsWith("crate/")) {
120941
121371
  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, "")))}` };
121372
+ return { ...item, bindings, specifier: `./${path23.posix.relative(path23.posix.dirname(file3.file), path23.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
120943
121373
  }
120944
121374
  if (item.specifier === "self" || item.specifier.startsWith("self/"))
120945
121375
  return { ...item, bindings, specifier: `./${item.specifier.replace(/^self\/?/u, "")}` };
@@ -121037,8 +121467,8 @@ var init_data_document2 = __esm(() => {
121037
121467
  });
121038
121468
 
121039
121469
  // ../../packages/core/dist/services/etl/stages/resolve.js
121040
- import path22 from "path";
121041
- import fs15 from "fs";
121470
+ import path24 from "path";
121471
+ import fs16 from "fs";
121042
121472
 
121043
121473
  class ResolveStage {
121044
121474
  symbolRepository;
@@ -121062,7 +121492,7 @@ class ResolveStage {
121062
121492
  const structuralDocuments = files.flatMap((file3) => {
121063
121493
  if (!file3.structure)
121064
121494
  return [];
121065
- const language = resolveStructuralLanguage(path22.extname(file3.file.relativePath));
121495
+ const language = resolveStructuralLanguage(path24.extname(file3.file.relativePath));
121066
121496
  if (language.status !== "supported")
121067
121497
  throw new Error(`structural_manifest_missing:${file3.file.relativePath}`);
121068
121498
  return [{
@@ -121074,13 +121504,13 @@ class ResolveStage {
121074
121504
  }];
121075
121505
  });
121076
121506
  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));
121507
+ 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
121508
  const pathAliasesByFile = Object.fromEntries([...knownRelPaths].map((file3) => [
121079
121509
  file3,
121080
121510
  this.structuralAliasesFor(file3, rootAliases, monorepoPackages)
121081
121511
  ]));
121082
121512
  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));
121513
+ 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
121514
  const seedIds = new Set;
121085
121515
  for (const definition of seedRows) {
121086
121516
  if (seedIds.has(definition.id))
@@ -121173,7 +121603,7 @@ class ResolveStage {
121173
121603
  if (parsed.file !== definition.file_path) {
121174
121604
  throw new Error(`structural_repository_seed_file_mismatch:${definition.id}`);
121175
121605
  }
121176
- const language = resolveStructuralLanguage(path22.extname(definition.file_path));
121606
+ const language = resolveStructuralLanguage(path24.extname(definition.file_path));
121177
121607
  if (language.status !== "supported")
121178
121608
  throw new Error(`structural_repository_seed_language:${definition.id}`);
121179
121609
  let identity;
@@ -121225,7 +121655,7 @@ class ResolveStage {
121225
121655
  });
121226
121656
  }
121227
121657
  resolveFile(parsed, projectPath, knownRelPaths, rootAliases, monorepoPackages, symbolIndex, knownFqns) {
121228
- const fromDir = path22.dirname(path22.join(projectPath, parsed.file.relativePath));
121658
+ const fromDir = path24.dirname(path24.join(projectPath, parsed.file.relativePath));
121229
121659
  const packageAliases = this.getPackageAliases(parsed.file.relativePath, monorepoPackages);
121230
121660
  const allAliases = [...packageAliases, ...rootAliases];
121231
121661
  const resolvedImports = parsed.rawImports.map((raw2) => {
@@ -121296,7 +121726,7 @@ class ResolveStage {
121296
121726
  index.set(def.name, `${def.file_path}#${def.name}`);
121297
121727
  }
121298
121728
  } catch (err) {
121299
- const skippedStructural = files.some((file3) => !file3.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path22.extname(file3.file.relativePath).toLowerCase()));
121729
+ const skippedStructural = files.some((file3) => !file3.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path24.extname(file3.file.relativePath).toLowerCase()));
121300
121730
  if (skippedStructural)
121301
121731
  throw new Error("structural_repository_seed_failed", { cause: err });
121302
121732
  logger.warn("buildSymbolIndex: repo seed failed, in-batch only", {
@@ -121320,7 +121750,7 @@ class ResolveStage {
121320
121750
  }
121321
121751
  resolveSpecifier(specifier, fromDir, projectPath, knownRelPaths, aliases) {
121322
121752
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
121323
- const resolved = this.probeExtensions(path22.resolve(fromDir, specifier), projectPath, knownRelPaths);
121753
+ const resolved = this.probeExtensions(path24.resolve(fromDir, specifier), projectPath, knownRelPaths);
121324
121754
  return { resolvedPath: resolved, external: false };
121325
121755
  }
121326
121756
  for (const alias of aliases) {
@@ -121328,8 +121758,8 @@ class ResolveStage {
121328
121758
  const suffix = specifier.slice(alias.prefix.length);
121329
121759
  for (const target of alias.targets) {
121330
121760
  const cleanTarget = target.replace(/\/\*$/, "");
121331
- const basePath = alias.packagePath ? path22.join(projectPath, alias.packagePath) : projectPath;
121332
- const absPath = path22.join(basePath, cleanTarget + suffix);
121761
+ const basePath = alias.packagePath ? path24.join(projectPath, alias.packagePath) : projectPath;
121762
+ const absPath = path24.join(basePath, cleanTarget + suffix);
121333
121763
  const resolved = this.probeExtensions(absPath, projectPath, knownRelPaths);
121334
121764
  if (resolved)
121335
121765
  return { resolvedPath: resolved, external: false };
@@ -121345,7 +121775,7 @@ class ResolveStage {
121345
121775
  ...TS_EXTENSIONS.map((ext2) => absPath.replace(/\.[^.]+$/, ext2))
121346
121776
  ];
121347
121777
  for (const candidate2 of candidates2) {
121348
- const rel = path22.relative(projectPath, candidate2).replace(/\\/g, "/");
121778
+ const rel = path24.relative(projectPath, candidate2).replace(/\\/g, "/");
121349
121779
  if (knownRelPaths.has(rel))
121350
121780
  return rel;
121351
121781
  }
@@ -121353,9 +121783,9 @@ class ResolveStage {
121353
121783
  }
121354
121784
  loadTsConfigPaths(projectPath, packageBase) {
121355
121785
  const aliases = [];
121356
- const tsconfigPath = path22.join(projectPath, "tsconfig.json");
121786
+ const tsconfigPath = path24.join(projectPath, "tsconfig.json");
121357
121787
  try {
121358
- const raw2 = fs15.readFileSync(tsconfigPath, "utf-8");
121788
+ const raw2 = fs16.readFileSync(tsconfigPath, "utf-8");
121359
121789
  const stripped = raw2.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
121360
121790
  const tsconfig = JSON.parse(stripped);
121361
121791
  const paths = tsconfig?.compilerOptions?.paths ?? {};
@@ -121384,7 +121814,7 @@ class ResolveStage {
121384
121814
  }
121385
121815
  }
121386
121816
  for (const packageRelPath of packagePaths) {
121387
- const absPackagePath = path22.join(projectPath, packageRelPath);
121817
+ const absPackagePath = path24.join(projectPath, packageRelPath);
121388
121818
  const aliases = this.loadTsConfigPaths(absPackagePath, packageRelPath);
121389
121819
  if (aliases.length > 0) {
121390
121820
  packages.push({
@@ -121414,7 +121844,7 @@ class ResolveStage {
121414
121844
  structuralAliasesFor(filePath, rootAliases, packages) {
121415
121845
  return [...this.getPackageAliases(filePath, packages), ...rootAliases].map((alias) => ({
121416
121846
  pattern: alias.prefix + (alias.targets.some((target) => target.includes("*")) ? "/*" : ""),
121417
- targets: alias.targets.map((target) => alias.packagePath ? path22.posix.join(alias.packagePath, target) : target)
121847
+ targets: alias.targets.map((target) => alias.packagePath ? path24.posix.join(alias.packagePath, target) : target)
121418
121848
  }));
121419
121849
  }
121420
121850
  }
@@ -121478,7 +121908,7 @@ var init_with_deadlock_retry = __esm(() => {
121478
121908
  });
121479
121909
 
121480
121910
  // ../../packages/core/dist/services/etl/stages/load.js
121481
- import path23 from "path";
121911
+ import path25 from "path";
121482
121912
  function formatDuration(ms) {
121483
121913
  const totalSec = Math.max(0, Math.round(ms / 1000));
121484
121914
  if (totalSec < 60)
@@ -121755,7 +122185,7 @@ class LoadStage {
121755
122185
  const filePath = file3.file.relativePath;
121756
122186
  const batch = buildSymbolPersistenceBatch(ctx.projectId, file3);
121757
122187
  if (ctx.graphGenerationLease) {
121758
- const manifest = getLanguageManifestEntry(path23.extname(filePath));
122188
+ const manifest = getLanguageManifestEntry(path25.extname(filePath));
121759
122189
  const diagnostics2 = (file3.structuralDiagnostics ?? []).slice(0, 10).map((diagnostic2) => ({
121760
122190
  code: diagnostic2.code,
121761
122191
  severity: diagnostic2.severity,
@@ -122212,9 +122642,9 @@ var init_graph_generation_coordinator = __esm(() => {
122212
122642
  // ../../packages/core/dist/services/etl/pipeline.js
122213
122643
  import { createHash as createHash7 } from "crypto";
122214
122644
  import { setTimeout as delay2 } from "timers/promises";
122215
- import path24 from "path";
122645
+ import path26 from "path";
122216
122646
  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)));
122647
+ const headers = new Set(files.filter((file3) => path26.posix.extname(file3.relativePath).toLowerCase() === ".h").map((file3) => path26.posix.normalize(file3.relativePath)));
122218
122648
  const mutable = new Map;
122219
122649
  const entry2 = (header) => {
122220
122650
  let value = mutable.get(header);
@@ -122225,7 +122655,7 @@ function buildHeaderLanguageEvidence(files) {
122225
122655
  return value;
122226
122656
  };
122227
122657
  for (const file3 of files) {
122228
- if (path24.posix.basename(file3.relativePath) !== "compile_commands.json" || file3.snapshotContent === undefined)
122658
+ if (path26.posix.basename(file3.relativePath) !== "compile_commands.json" || file3.snapshotContent === undefined)
122229
122659
  continue;
122230
122660
  let commands;
122231
122661
  try {
@@ -122241,11 +122671,11 @@ function buildHeaderLanguageEvidence(files) {
122241
122671
  const record2 = command;
122242
122672
  if (typeof record2.file !== "string")
122243
122673
  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, "/"));
122674
+ const projectRoot = path26.resolve(file3.absolutePath, ...file3.relativePath.split("/").map(() => ".."));
122675
+ const commandDirectory = typeof record2.directory === "string" ? path26.resolve(projectRoot, record2.directory) : projectRoot;
122676
+ const absoluteInput = path26.resolve(commandDirectory, record2.file);
122677
+ const relative2 = path26.relative(projectRoot, absoluteInput);
122678
+ const header = path26.posix.normalize(relative2.replaceAll(path26.sep, "/"));
122249
122679
  if (!headers.has(header))
122250
122680
  continue;
122251
122681
  const invocation = typeof record2.command === "string" ? record2.command : Array.isArray(record2.arguments) ? record2.arguments.join(" ") : "";
@@ -123404,16 +123834,16 @@ function detectRoutes(httpEdges, defs, opts = {}) {
123404
123834
  const seen = new Set;
123405
123835
  const out = [];
123406
123836
  for (const e of httpEdges) {
123407
- const path26 = e.route;
123408
- if (!path26)
123837
+ const path28 = e.route;
123838
+ if (!path28)
123409
123839
  continue;
123410
123840
  const method = (e.method ?? "ANY").toUpperCase();
123411
- const key = method + " " + path26;
123841
+ const key = method + " " + path28;
123412
123842
  if (seen.has(key))
123413
123843
  continue;
123414
123844
  seen.add(key);
123415
123845
  out.push({
123416
- path: path26,
123846
+ path: path28,
123417
123847
  method: e.method,
123418
123848
  file: e.fromFile,
123419
123849
  handler: e.targetFqn ?? e.symbolName
@@ -123424,12 +123854,12 @@ function detectRoutes(httpEdges, defs, opts = {}) {
123424
123854
  continue;
123425
123855
  const parsed = parseRouteName(d.name);
123426
123856
  const method = parsed?.method ?? "ANY";
123427
- const path26 = parsed?.path ?? d.name;
123428
- const key = method + " " + path26;
123857
+ const path28 = parsed?.path ?? d.name;
123858
+ const key = method + " " + path28;
123429
123859
  if (seen.has(key))
123430
123860
  continue;
123431
123861
  seen.add(key);
123432
- out.push({ path: path26, method: parsed?.method, file: d.filePath, handler: d.name });
123862
+ out.push({ path: path28, method: parsed?.method, file: d.filePath, handler: d.name });
123433
123863
  }
123434
123864
  for (const d of defs) {
123435
123865
  const parsed = parseRouteName(d.name);
@@ -123650,8 +124080,8 @@ __export(exports_symbol_graph_service, {
123650
124080
  symbolGraphService: () => symbolGraphService,
123651
124081
  SymbolGraphService: () => SymbolGraphService
123652
124082
  });
123653
- import path26 from "path";
123654
- import fs16 from "fs/promises";
124083
+ import path28 from "path";
124084
+ import fs17 from "fs/promises";
123655
124085
 
123656
124086
  class SymbolGraphService {
123657
124087
  identityLookup;
@@ -123979,7 +124409,7 @@ class SymbolGraphService {
123979
124409
  async readSnippet(relativePath, lineStart, lineEnd, projectId) {
123980
124410
  try {
123981
124411
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
123982
- const content = await fs16.readFile(absolutePath, "utf-8");
124412
+ const content = await fs17.readFile(absolutePath, "utf-8");
123983
124413
  const lines = content.split(`
123984
124414
  `);
123985
124415
  return lines.slice(Math.max(0, lineStart - 1), Math.min(lines.length, lineEnd)).join(`
@@ -123991,7 +124421,7 @@ class SymbolGraphService {
123991
124421
  async readContext(relativePath, lineNumber, contextLines, projectId) {
123992
124422
  try {
123993
124423
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
123994
- const content = await fs16.readFile(absolutePath, "utf-8");
124424
+ const content = await fs17.readFile(absolutePath, "utf-8");
123995
124425
  const lines = content.split(`
123996
124426
  `);
123997
124427
  const start = Math.max(0, lineNumber - contextLines - 1);
@@ -124004,7 +124434,7 @@ class SymbolGraphService {
124004
124434
  }
124005
124435
  async resolveToAbsolute(relativePath, projectId) {
124006
124436
  const root = await this.getProjectRoot(projectId);
124007
- return root ? path26.resolve(root, relativePath) : relativePath;
124437
+ return root ? path28.resolve(root, relativePath) : relativePath;
124008
124438
  }
124009
124439
  async getProjectRoot(projectId) {
124010
124440
  const cached2 = this.projectRootCache.get(projectId);
@@ -127998,31 +128428,31 @@ class TracePathService {
127998
128428
  const chains = [];
127999
128429
  const seen = new Set;
128000
128430
  let walks = 0;
128001
- const walk = (fqn, path29) => {
128431
+ const walk = (fqn, path31) => {
128002
128432
  if (chains.length >= CHAIN_CAP)
128003
128433
  return;
128004
128434
  if (walks >= MAX_WALKS)
128005
128435
  return;
128006
128436
  walks++;
128007
- const key = path29.join("\u2192");
128437
+ const key = path31.join("\u2192");
128008
128438
  if (seen.has(key))
128009
128439
  return;
128010
128440
  seen.add(key);
128011
128441
  const next = adj.get(fqn);
128012
128442
  if (!next || next.length === 0 || !whoHasChild.has(fqn)) {
128013
- if (path29.length > 1)
128014
- chains.push(path29.map((n2) => this.fqnToName(n2)).join(" \u2192 "));
128443
+ if (path31.length > 1)
128444
+ chains.push(path31.map((n2) => this.fqnToName(n2)).join(" \u2192 "));
128015
128445
  return;
128016
128446
  }
128017
128447
  for (const child of next) {
128018
128448
  if (chains.length >= CHAIN_CAP || walks >= MAX_WALKS)
128019
128449
  return;
128020
- if (path29.includes(child)) {
128021
- const cycled = [...path29, `${this.fqnToName(child)}\u21BA`];
128450
+ if (path31.includes(child)) {
128451
+ const cycled = [...path31, `${this.fqnToName(child)}\u21BA`];
128022
128452
  chains.push(cycled.map((n2) => n2).join(" \u2192 "));
128023
128453
  continue;
128024
128454
  }
128025
- walk(child, [...path29, child]);
128455
+ walk(child, [...path31, child]);
128026
128456
  }
128027
128457
  };
128028
128458
  for (const seed of seeds) {
@@ -131164,9 +131594,9 @@ var init_l1_memory_cache = __esm(() => {
131164
131594
  });
131165
131595
 
131166
131596
  // ../../packages/core/dist/services/health/local-health-checker.js
131167
- import fs19 from "fs/promises";
131597
+ import fs20 from "fs/promises";
131168
131598
  import { existsSync as existsSync3 } from "fs";
131169
- import path31 from "path";
131599
+ import path33 from "path";
131170
131600
 
131171
131601
  class LocalHealthChecker {
131172
131602
  ollamaBaseUrl = process.env.OLLAMA_BASE_URL || "http://localhost:11434";
@@ -131200,10 +131630,10 @@ class LocalHealthChecker {
131200
131630
  const start = Date.now();
131201
131631
  try {
131202
131632
  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);
131633
+ await fs20.mkdir(this.dataDir, { recursive: true });
131634
+ const probe2 = path33.join(this.dataDir, ".health-check-test");
131635
+ await fs20.writeFile(probe2, "ok");
131636
+ await fs20.unlink(probe2);
131207
131637
  return { available: true, latency: Date.now() - start, details: { path: this.dataDir, writable: true } };
131208
131638
  } catch (error51) {
131209
131639
  return { available: false, latency: Date.now() - start, error: `Data directory error: ${error51.message}` };
@@ -131599,10 +132029,18 @@ var init_scheduler_store_factory = __esm(() => {
131599
132029
  });
131600
132030
 
131601
132031
  // ../../packages/core/dist/services/scheduler/scheduler.js
131602
- function readEnabled() {
132032
+ function readEnabledEnv() {
131603
132033
  const raw2 = process.env.MASSA_AI_SCHEDULER_ENABLED;
132034
+ if (raw2 === undefined)
132035
+ return;
131604
132036
  return raw2 === "true" || raw2 === "1";
131605
132037
  }
132038
+ function envPositiveInt(raw2) {
132039
+ if (raw2 === undefined || raw2 === "")
132040
+ return;
132041
+ const parsed = parsePositiveIntEnv(raw2, NaN);
132042
+ return Number.isNaN(parsed) ? undefined : parsed;
132043
+ }
131606
132044
 
131607
132045
  class Scheduler {
131608
132046
  store;
@@ -131616,9 +132054,10 @@ class Scheduler {
131616
132054
  started = false;
131617
132055
  constructor(opts = {}) {
131618
132056
  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();
132057
+ const schedulerConfig = config.get("scheduler");
132058
+ this.tickIntervalMs = opts.tickIntervalMs ?? envPositiveInt(process.env.MASSA_AI_SCHEDULER_TICK_MS) ?? schedulerConfig?.tickMs ?? DEFAULTS.tickMs;
132059
+ this.maxConcurrent = opts.maxConcurrent ?? envPositiveInt(process.env.MASSA_AI_SCHEDULER_MAX_CONCURRENT) ?? schedulerConfig?.maxConcurrent ?? DEFAULTS.maxConcurrent;
132060
+ this.enabled = opts.enabled ?? readEnabledEnv() ?? schedulerConfig?.enabled ?? false;
131622
132061
  }
131623
132062
  registerHandler(jobKind, handler) {
131624
132063
  this.handlers.set(jobKind, handler);
@@ -132982,21 +133421,31 @@ var init_observation_consolidation_job = __esm(() => {
132982
133421
  });
132983
133422
 
132984
133423
  // ../../packages/core/dist/services/scheduler/scheduler-defaults.js
132985
- function envBool2(key, fallback) {
133424
+ function envBool2(key, fileValue, fallback) {
132986
133425
  const raw2 = process.env[key];
132987
133426
  if (raw2 === undefined)
132988
- return fallback;
133427
+ return fileValue ?? fallback;
132989
133428
  return raw2 === "true" || raw2 === "1";
132990
133429
  }
132991
- function envNum2(key, fallback) {
133430
+ function envNum2(key, fileValue, fallback) {
132992
133431
  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;
133432
+ if (raw2 !== undefined && raw2 !== "") {
133433
+ const n2 = Number(raw2);
133434
+ if (Number.isFinite(n2) && n2 > 0)
133435
+ return n2;
133436
+ }
133437
+ return fileValue ?? fallback;
133438
+ }
133439
+ function readFileSchedulerJobs() {
133440
+ try {
133441
+ const raw2 = loadConfigSafe().scheduler?.jobs;
133442
+ return raw2;
133443
+ } catch {
133444
+ return;
133445
+ }
132997
133446
  }
132998
133447
  function applySafeDefaults(job) {
132999
- if (!envBool2("MASSA_AI_SCHEDULER_SAFE_DEFAULTS", false)) {
133448
+ if (!envBool2("MASSA_AI_SCHEDULER_SAFE_DEFAULTS", undefined, false)) {
133000
133449
  return job;
133001
133450
  }
133002
133451
  if (job.jobKind === "memory-consolidation") {
@@ -133043,10 +133492,12 @@ function registerDefaultJobs(scheduler) {
133043
133492
  const count = CheckpointManager2.getInstance().purgeExpired();
133044
133493
  logger.info("Scheduled checkpoint purge completed", { count });
133045
133494
  });
133495
+ const fileJobs = readFileSchedulerJobs();
133046
133496
  for (const rawDef of DEFAULT_SCHEDULED_JOBS) {
133047
133497
  const def = applySafeDefaults(rawDef);
133048
- const enabled2 = envBool2(def.enableEnvVar, def.defaultEnabled);
133049
- const intervalMs = envNum2(def.intervalEnvVar, def.schedule.intervalMs ?? THIRTY_MIN);
133498
+ const fileJob = fileJobs?.[def.jobKind];
133499
+ const enabled2 = envBool2(def.enableEnvVar, fileJob?.enabled, def.defaultEnabled);
133500
+ const intervalMs = envNum2(def.intervalEnvVar, fileJob?.intervalMs, def.schedule.intervalMs ?? THIRTY_MIN);
133050
133501
  const schedule = { type: "interval", intervalMs };
133051
133502
  scheduler.registerOrResumeJob({
133052
133503
  id: def.id,
@@ -133127,9 +133578,9 @@ var init_scheduler2 = __esm(() => {
133127
133578
  });
133128
133579
 
133129
133580
  // ../../packages/core/dist/services/pricing/models-dev-client.js
133130
- import fs20 from "fs/promises";
133581
+ import fs21 from "fs/promises";
133131
133582
  import { existsSync as existsSync4 } from "fs";
133132
- import path32 from "path";
133583
+ import path34 from "path";
133133
133584
  function getModelsDevClient() {
133134
133585
  if (!clientInstance) {
133135
133586
  clientInstance = new ModelsDevClient;
@@ -133149,7 +133600,7 @@ var init_models_dev_client = __esm(() => {
133149
133600
  memoryCacheTimestamp = 0;
133150
133601
  getLocalCachePath() {
133151
133602
  const dataDir = config.get("dataDir");
133152
- return path32.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
133603
+ return path34.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
133153
133604
  }
133154
133605
  async loadLocalCache() {
133155
133606
  const cachePath = this.getLocalCachePath();
@@ -133157,7 +133608,7 @@ var init_models_dev_client = __esm(() => {
133157
133608
  if (!existsSync4(cachePath)) {
133158
133609
  return null;
133159
133610
  }
133160
- const content = await fs20.readFile(cachePath, "utf-8");
133611
+ const content = await fs21.readFile(cachePath, "utf-8");
133161
133612
  const data = JSON.parse(content);
133162
133613
  const age = Date.now() - data.timestamp;
133163
133614
  if (age > ModelsDevClient.LOCAL_CACHE_TTL) {
@@ -133184,14 +133635,14 @@ var init_models_dev_client = __esm(() => {
133184
133635
  async saveLocalCache(models) {
133185
133636
  const cachePath = this.getLocalCachePath();
133186
133637
  try {
133187
- const dir = path32.dirname(cachePath);
133188
- await fs20.mkdir(dir, { recursive: true });
133638
+ const dir = path34.dirname(cachePath);
133639
+ await fs21.mkdir(dir, { recursive: true });
133189
133640
  const data = {
133190
133641
  timestamp: Date.now(),
133191
133642
  version: "1.0.0",
133192
133643
  models: Object.fromEntries(models)
133193
133644
  };
133194
- await fs20.writeFile(cachePath, JSON.stringify(data), "utf-8");
133645
+ await fs21.writeFile(cachePath, JSON.stringify(data), "utf-8");
133195
133646
  logger.debug("Saved pricing to local cache", {
133196
133647
  models: models.size,
133197
133648
  path: cachePath
@@ -133520,7 +133971,7 @@ var init_models_dev_client = __esm(() => {
133520
133971
  const cachePath = this.getLocalCachePath();
133521
133972
  try {
133522
133973
  if (existsSync4(cachePath)) {
133523
- await fs20.unlink(cachePath);
133974
+ await fs21.unlink(cachePath);
133524
133975
  logger.debug("Local pricing cache file deleted");
133525
133976
  }
133526
133977
  } catch (error51) {
@@ -139075,33 +139526,33 @@ var require_URL = __commonJS((exports, module) => {
139075
139526
  else
139076
139527
  return basepath.substring(0, lastslash + 1) + refpath;
139077
139528
  }
139078
- function remove_dot_segments(path33) {
139079
- if (!path33)
139080
- return path33;
139529
+ function remove_dot_segments(path35) {
139530
+ if (!path35)
139531
+ return path35;
139081
139532
  var output = "";
139082
- while (path33.length > 0) {
139083
- if (path33 === "." || path33 === "..") {
139084
- path33 = "";
139533
+ while (path35.length > 0) {
139534
+ if (path35 === "." || path35 === "..") {
139535
+ path35 = "";
139085
139536
  break;
139086
139537
  }
139087
- var twochars = path33.substring(0, 2);
139088
- var threechars = path33.substring(0, 3);
139089
- var fourchars = path33.substring(0, 4);
139538
+ var twochars = path35.substring(0, 2);
139539
+ var threechars = path35.substring(0, 3);
139540
+ var fourchars = path35.substring(0, 4);
139090
139541
  if (threechars === "../") {
139091
- path33 = path33.substring(3);
139542
+ path35 = path35.substring(3);
139092
139543
  } else if (twochars === "./") {
139093
- path33 = path33.substring(2);
139544
+ path35 = path35.substring(2);
139094
139545
  } 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);
139546
+ path35 = "/" + path35.substring(3);
139547
+ } else if (twochars === "/." && path35.length === 2) {
139548
+ path35 = "/";
139549
+ } else if (fourchars === "/../" || threechars === "/.." && path35.length === 3) {
139550
+ path35 = "/" + path35.substring(4);
139100
139551
  output = output.replace(/\/?[^\/]*$/, "");
139101
139552
  } else {
139102
- var segment = path33.match(/(\/?([^\/]*))/)[0];
139553
+ var segment = path35.match(/(\/?([^\/]*))/)[0];
139103
139554
  output += segment;
139104
- path33 = path33.substring(segment.length);
139555
+ path35 = path35.substring(segment.length);
139105
139556
  }
139106
139557
  }
139107
139558
  return output;
@@ -151171,21 +151622,21 @@ function jsonToKeyPathChunks(value, label = "$") {
151171
151622
  walk(value, label, out);
151172
151623
  return out;
151173
151624
  }
151174
- function walk(val, path33, out) {
151625
+ function walk(val, path35, out) {
151175
151626
  if (val === null || val === undefined)
151176
151627
  return;
151177
151628
  if (Array.isArray(val)) {
151178
151629
  if (val.length === 0) {
151179
- out.push({ path: path33, content: `**${path33}** = _[]_` });
151630
+ out.push({ path: path35, content: `**${path35}** = _[]_` });
151180
151631
  return;
151181
151632
  }
151182
151633
  if (val.every((v) => v !== null && typeof v === "object")) {
151183
- val.forEach((v, i) => walk(v, `${path33}[${i}]`, out));
151634
+ val.forEach((v, i) => walk(v, `${path35}[${i}]`, out));
151184
151635
  return;
151185
151636
  }
151186
151637
  const items = val.map((v) => `- \`${String(v)}\``).join(`
151187
151638
  `);
151188
- out.push({ path: path33, content: `**${path33}**
151639
+ out.push({ path: path35, content: `**${path35}**
151189
151640
 
151190
151641
  ${items}` });
151191
151642
  return;
@@ -151193,16 +151644,16 @@ ${items}` });
151193
151644
  if (typeof val === "object") {
151194
151645
  const entries = Object.entries(val);
151195
151646
  if (entries.length === 0) {
151196
- out.push({ path: path33, content: `**${path33}** = _{}_` });
151647
+ out.push({ path: path35, content: `**${path35}** = _{}_` });
151197
151648
  return;
151198
151649
  }
151199
151650
  for (const [k2, v] of entries) {
151200
151651
  const safeKey = /^[A-Za-z_$][\w$]*$/.test(k2) ? k2 : JSON.stringify(k2);
151201
- walk(v, `${path33}.${safeKey}`, out);
151652
+ walk(v, `${path35}.${safeKey}`, out);
151202
151653
  }
151203
151654
  return;
151204
151655
  }
151205
- out.push({ path: path33, content: `**${path33}** = \`${String(val)}\`` });
151656
+ out.push({ path: path35, content: `**${path35}** = \`${String(val)}\`` });
151206
151657
  }
151207
151658
  var gfm, STRIP_SELECTORS, tdCache = null;
151208
151659
  var init_html_to_md = __esm(() => {
@@ -174193,9 +174644,9 @@ async function acquireIndexingLease(request) {
174193
174644
 
174194
174645
  // ../../packages/core/dist/services/project-identity/project-root-identity.js
174195
174646
  import { realpath as realpath2 } from "fs/promises";
174196
- import path25 from "path";
174647
+ import path27 from "path";
174197
174648
  async function canonicalizeProjectRoot(projectPath, canonicalize = realpath2) {
174198
- return canonicalize(path25.resolve(projectPath));
174649
+ return canonicalize(path27.resolve(projectPath));
174199
174650
  }
174200
174651
  async function assertProjectRootReuse(options) {
174201
174652
  if (!options.storedProjectPath || options.forceReindex)
@@ -174203,9 +174654,9 @@ async function assertProjectRootReuse(options) {
174203
174654
  const canonicalize = options.canonicalize ?? realpath2;
174204
174655
  let storedCanonical;
174205
174656
  try {
174206
- storedCanonical = await canonicalize(path25.resolve(options.storedProjectPath));
174657
+ storedCanonical = await canonicalize(path27.resolve(options.storedProjectPath));
174207
174658
  } catch {
174208
- storedCanonical = path25.resolve(options.storedProjectPath);
174659
+ storedCanonical = path27.resolve(options.storedProjectPath);
174209
174660
  }
174210
174661
  if (storedCanonical !== options.canonicalProjectPath) {
174211
174662
  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 +174666,7 @@ async function assertProjectRootReuse(options) {
174215
174666
  // ../../packages/core/dist/tools/index_project.js
174216
174667
  init_workspace_manager();
174217
174668
  init_parser_readiness();
174218
- import path27 from "path";
174669
+ import path29 from "path";
174219
174670
 
174220
174671
  class IndexProjectTool {
174221
174672
  name = "index_project";
@@ -174263,7 +174714,7 @@ class IndexProjectTool {
174263
174714
  try {
174264
174715
  await assertParserReadyForIndexing();
174265
174716
  const canonicalProjectPath = await canonicalizeProjectRoot(projectPath);
174266
- const finalProjectId = projectId || path27.basename(canonicalProjectPath) || "default";
174717
+ const finalProjectId = projectId || path29.basename(canonicalProjectPath) || "default";
174267
174718
  const existing = await workspaceManager.getWorkspace(finalProjectId);
174268
174719
  await assertProjectRootReuse({
174269
174720
  projectId: finalProjectId,
@@ -174817,17 +175268,17 @@ function applyReplacer(root, replacer) {
174817
175268
  return transformChildren(root, replacer, []);
174818
175269
  return transformChildren(normalizeValue(replacedRoot), replacer, []);
174819
175270
  }
174820
- function transformChildren(value, replacer, path28) {
175271
+ function transformChildren(value, replacer, path30) {
174821
175272
  if (isJsonObject(value))
174822
- return transformObject(value, replacer, path28);
175273
+ return transformObject(value, replacer, path30);
174823
175274
  if (isJsonArray(value))
174824
- return transformArray(value, replacer, path28);
175275
+ return transformArray(value, replacer, path30);
174825
175276
  return value;
174826
175277
  }
174827
- function transformObject(obj, replacer, path28) {
175278
+ function transformObject(obj, replacer, path30) {
174828
175279
  const result = {};
174829
175280
  for (const [key, value] of Object.entries(obj)) {
174830
- const childPath = [...path28, key];
175281
+ const childPath = [...path30, key];
174831
175282
  const replacedValue = replacer(key, value, childPath);
174832
175283
  if (replacedValue === undefined)
174833
175284
  continue;
@@ -174835,11 +175286,11 @@ function transformObject(obj, replacer, path28) {
174835
175286
  }
174836
175287
  return result;
174837
175288
  }
174838
- function transformArray(arr, replacer, path28) {
175289
+ function transformArray(arr, replacer, path30) {
174839
175290
  const result = [];
174840
175291
  for (let i = 0;i < arr.length; i++) {
174841
175292
  const value = arr[i];
174842
- const childPath = [...path28, i];
175293
+ const childPath = [...path30, i];
174843
175294
  const replacedValue = replacer(String(i), value, childPath);
174844
175295
  if (replacedValue === undefined)
174845
175296
  continue;
@@ -176220,9 +176671,9 @@ init_dist();
176220
176671
  init_db_connection();
176221
176672
  init_alias_resolver();
176222
176673
  init_safe_error_summary();
176223
- import fs17 from "fs";
176224
- import os6 from "os";
176225
- import path28 from "path";
176674
+ import fs18 from "fs";
176675
+ import os8 from "os";
176676
+ import path30 from "path";
176226
176677
 
176227
176678
  // ../../packages/core/dist/services/hooks/session-pin-store.js
176228
176679
  var DEFAULT_MAX_SIZE = 1000;
@@ -176321,8 +176772,8 @@ class AttributionResolver {
176321
176772
  this.aliasResolver = options.aliasResolver ?? getProjectIdentityAliasResolver();
176322
176773
  this.pins = options.pins ?? new SessionPinStore;
176323
176774
  this.canonicalize = options.canonicalize ?? defaultCanonicalize;
176324
- this.homedir = options.homedir ?? os6.homedir;
176325
- this.fsRoot = options.fsRoot ?? (() => path28.parse(path28.sep).root);
176775
+ this.homedir = options.homedir ?? os8.homedir;
176776
+ this.fsRoot = options.fsRoot ?? (() => path30.parse(path30.sep).root);
176326
176777
  }
176327
176778
  async resolve(input) {
176328
176779
  const caller = input.callerProjectId;
@@ -176373,7 +176824,7 @@ class AttributionResolver {
176373
176824
  }
176374
176825
  let bestPath = null;
176375
176826
  for (const candidate2 of byPath.keys()) {
176376
- if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path28.sep) ? candidate2 : candidate2 + path28.sep)) {
176827
+ if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path30.sep) ? candidate2 : candidate2 + path30.sep)) {
176377
176828
  if (bestPath === null || candidate2.length > bestPath.length) {
176378
176829
  bestPath = candidate2;
176379
176830
  }
@@ -176396,7 +176847,7 @@ class AttributionResolver {
176396
176847
  return projectPath2;
176397
176848
  const fsRoot = this.fsRoot();
176398
176849
  let normalized = projectPath2;
176399
- while (normalized.length > fsRoot.length && normalized.endsWith(path28.sep)) {
176850
+ while (normalized.length > fsRoot.length && normalized.endsWith(path30.sep)) {
176400
176851
  normalized = normalized.slice(0, -1);
176401
176852
  }
176402
176853
  return normalized;
@@ -176404,10 +176855,10 @@ class AttributionResolver {
176404
176855
  }
176405
176856
  function defaultCanonicalize(cwd) {
176406
176857
  try {
176407
- return fs17.realpathSync(cwd);
176858
+ return fs18.realpathSync(cwd);
176408
176859
  } catch {
176409
176860
  try {
176410
- return path28.resolve(cwd);
176861
+ return path30.resolve(cwd);
176411
176862
  } catch {
176412
176863
  return;
176413
176864
  }
@@ -176944,7 +177395,7 @@ init_code_compressor();
176944
177395
 
176945
177396
  // ../../packages/core/dist/services/file-read/file-content-cache.js
176946
177397
  init_dist();
176947
- import fs18 from "fs/promises";
177398
+ import fs19 from "fs/promises";
176948
177399
 
176949
177400
  class FileContentCache {
176950
177401
  extractMetadata;
@@ -176977,7 +177428,7 @@ class FileContentCache {
176977
177428
  metadata: cached2.metadata
176978
177429
  };
176979
177430
  }
176980
- const content = await fs18.readFile(filePath, "utf-8");
177431
+ const content = await fs19.readFile(filePath, "utf-8");
176981
177432
  const metadata = await this.extractMetadata(content, filePath, options);
176982
177433
  evictOldest(this.fileCache, this.FILE_CACHE_MAX_ENTRIES - 1);
176983
177434
  this.fileCache.set(cacheKey, {
@@ -176992,7 +177443,7 @@ class FileContentCache {
176992
177443
 
176993
177444
  // ../../packages/core/dist/services/file-read/file-metadata.js
176994
177445
  init_dist();
176995
- import path29 from "path";
177446
+ import path31 from "path";
176996
177447
 
176997
177448
  class FileMetadataExtractor {
176998
177449
  symbolGraph;
@@ -177028,7 +177479,7 @@ class FileMetadataExtractor {
177028
177479
  return metadata;
177029
177480
  }
177030
177481
  detectLanguage(filePath) {
177031
- const ext2 = path29.extname(filePath).toLowerCase();
177482
+ const ext2 = path31.extname(filePath).toLowerCase();
177032
177483
  const languageMap2 = {
177033
177484
  ".ts": "TypeScript",
177034
177485
  ".tsx": "TypeScript",
@@ -177145,7 +177596,7 @@ function selectLines(lines, range) {
177145
177596
 
177146
177597
  // ../../packages/core/dist/services/file-read/path-containment.js
177147
177598
  init_dist();
177148
- import path30 from "path";
177599
+ import path32 from "path";
177149
177600
 
177150
177601
  class PathContainment {
177151
177602
  projectRoots;
@@ -177153,14 +177604,14 @@ class PathContainment {
177153
177604
  this.projectRoots = projectRoots;
177154
177605
  }
177155
177606
  async resolveFilePath(filePath, projectId) {
177156
- if (path30.isAbsolute(filePath)) {
177157
- return path30.resolve(filePath);
177607
+ if (path32.isAbsolute(filePath)) {
177608
+ return path32.resolve(filePath);
177158
177609
  }
177159
177610
  if (projectId) {
177160
177611
  const root = await this.projectRoots.getProjectRoot(projectId);
177161
177612
  if (root) {
177162
177613
  const cleaned = sanitizeFilePath(filePath);
177163
- return path30.resolve(root, cleaned);
177614
+ return path32.resolve(root, cleaned);
177164
177615
  }
177165
177616
  return null;
177166
177617
  }
@@ -177171,17 +177622,17 @@ class PathContainment {
177171
177622
  if (projectId) {
177172
177623
  const root = await this.projectRoots.getProjectRoot(projectId);
177173
177624
  if (root)
177174
- roots.push(path30.resolve(root));
177625
+ roots.push(path32.resolve(root));
177175
177626
  }
177176
- roots.push(path30.resolve(process.cwd()));
177627
+ roots.push(path32.resolve(process.cwd()));
177177
177628
  const envRoots = (process.env.MASSA_AI_READ_FILE_ROOTS ?? "").split(":").map((s) => s.trim()).filter((s) => s.length > 0);
177178
177629
  for (const extra of envRoots) {
177179
- roots.push(path30.resolve(extra));
177630
+ roots.push(path32.resolve(extra));
177180
177631
  }
177181
- const target = path30.resolve(absoluteFilePath);
177632
+ const target = path32.resolve(absoluteFilePath);
177182
177633
  for (const root of roots) {
177183
- const rel = path30.relative(root, target);
177184
- if (rel !== "" && !rel.startsWith("..") && !path30.isAbsolute(rel)) {
177634
+ const rel = path32.relative(root, target);
177635
+ if (rel !== "" && !rel.startsWith("..") && !path32.isAbsolute(rel)) {
177185
177636
  return { allowed: true };
177186
177637
  }
177187
177638
  if (rel === "")
@@ -178018,8 +178469,8 @@ init_event_bus();
178018
178469
  init_llm_client();
178019
178470
  init_symbol_graph_service();
178020
178471
  import { randomUUID as randomUUID9 } from "crypto";
178021
- import fs21 from "fs";
178022
- import path33 from "path";
178472
+ import fs22 from "fs";
178473
+ import path35 from "path";
178023
178474
  import { spawn as spawn2 } from "child_process";
178024
178475
  var FALLBACK_BOOTSTRAP = {
178025
178476
  enabled: true,
@@ -178203,9 +178654,9 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
178203
178654
  }
178204
178655
  try {
178205
178656
  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);
178657
+ const p = path35.join(projectRoot, name26);
178658
+ if (fs22.existsSync(p) && fs22.statSync(p).isFile()) {
178659
+ const buf = fs22.readFileSync(p);
178209
178660
  signals.readme = buf.slice(0, MAX_README_BYTES).toString("utf8");
178210
178661
  break;
178211
178662
  }
@@ -178214,14 +178665,14 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
178214
178665
  logger.debug("bootstrap scan: README read failed", { error: e.message });
178215
178666
  }
178216
178667
  try {
178217
- const docsDir = path33.join(projectRoot, "docs");
178218
- if (fs21.existsSync(docsDir) && fs21.statSync(docsDir).isDirectory()) {
178668
+ const docsDir = path35.join(projectRoot, "docs");
178669
+ if (fs22.existsSync(docsDir) && fs22.statSync(docsDir).isDirectory()) {
178219
178670
  const entries = walkMarkdown(docsDir).slice(0, MAX_DOCS);
178220
178671
  for (const rel of entries) {
178221
178672
  try {
178222
- const buf = fs21.readFileSync(rel);
178673
+ const buf = fs22.readFileSync(rel);
178223
178674
  signals.docs.push({
178224
- path: path33.relative(projectRoot, rel),
178675
+ path: path35.relative(projectRoot, rel),
178225
178676
  snippet: buf.slice(0, MAX_DOC_BYTES).toString("utf8")
178226
178677
  });
178227
178678
  } catch {}
@@ -178232,10 +178683,10 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
178232
178683
  }
178233
178684
  try {
178234
178685
  for (const name26 of MANIFEST_FILES) {
178235
- const p = path33.join(projectRoot, name26);
178236
- if (!fs21.existsSync(p) || !fs21.statSync(p).isFile())
178686
+ const p = path35.join(projectRoot, name26);
178687
+ if (!fs22.existsSync(p) || !fs22.statSync(p).isFile())
178237
178688
  continue;
178238
- const raw2 = fs21.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
178689
+ const raw2 = fs22.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
178239
178690
  const kind = name26;
178240
178691
  if (name26 === "package.json") {
178241
178692
  try {
@@ -178275,12 +178726,12 @@ function walkMarkdown(dir) {
178275
178726
  const cur = stack.pop();
178276
178727
  let entries;
178277
178728
  try {
178278
- entries = fs21.readdirSync(cur, { withFileTypes: true });
178729
+ entries = fs22.readdirSync(cur, { withFileTypes: true });
178279
178730
  } catch {
178280
178731
  continue;
178281
178732
  }
178282
178733
  for (const e of entries) {
178283
- const full = path33.join(cur, e.name);
178734
+ const full = path35.join(cur, e.name);
178284
178735
  if (e.isDirectory()) {
178285
178736
  if (e.name === "node_modules" || e.name.startsWith("."))
178286
178737
  continue;
@@ -179349,8 +179800,8 @@ var checkpointRoutes = new Elysia({ prefix: "/api/v1/checkpoints" }).post("/list
179349
179800
 
179350
179801
  // src/routes/project.ts
179351
179802
  init_dist();
179352
- import fs22 from "fs/promises";
179353
- import path34 from "path";
179803
+ import fs23 from "fs/promises";
179804
+ import path36 from "path";
179354
179805
  function isDimensionMismatchError(error51) {
179355
179806
  const message = error51 instanceof Error ? error51.message : String(error51);
179356
179807
  return /dimension mismatch/i.test(message);
@@ -179570,22 +180021,22 @@ var projectRoutes = new Elysia({ prefix: "/api/v1/project" }).get("/list", async
179570
180021
  }).post("/upload-and-index", async ({ body }) => {
179571
180022
  const rawBase = body.projectId || body.projectPath.replace(/\\/g, "/").split("/").filter(Boolean).pop() || "default";
179572
180023
  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 });
180024
+ const uploadRoot = process.env.MASSA_AI_UPLOAD_DIR || path36.join(getGlobalDataDir(), "uploads");
180025
+ const stagingDir = path36.resolve(uploadRoot, finalProjectId);
180026
+ await fs23.rm(stagingDir, { recursive: true, force: true });
180027
+ await fs23.mkdir(stagingDir, { recursive: true });
179577
180028
  const WRITE_BATCH = 20;
179578
180029
  for (let i = 0;i < body.files.length; i += WRITE_BATCH) {
179579
180030
  await Promise.all(body.files.slice(i, i + WRITE_BATCH).map(async (file3) => {
179580
- if (path34.isAbsolute(file3.relativePath) || file3.relativePath.includes("..")) {
180031
+ if (path36.isAbsolute(file3.relativePath) || file3.relativePath.includes("..")) {
179581
180032
  throw new Error(`Invalid file path: ${file3.relativePath}`);
179582
180033
  }
179583
- const dest = path34.resolve(stagingDir, file3.relativePath.replace(/\//g, path34.sep));
179584
- if (!dest.startsWith(stagingDir + path34.sep)) {
180034
+ const dest = path36.resolve(stagingDir, file3.relativePath.replace(/\//g, path36.sep));
180035
+ if (!dest.startsWith(stagingDir + path36.sep)) {
179585
180036
  throw new Error(`Path escapes staging directory: ${file3.relativePath}`);
179586
180037
  }
179587
- await fs22.mkdir(path34.dirname(dest), { recursive: true });
179588
- await fs22.writeFile(dest, file3.content, "utf-8");
180038
+ await fs23.mkdir(path36.dirname(dest), { recursive: true });
180039
+ await fs23.writeFile(dest, file3.content, "utf-8");
179589
180040
  }));
179590
180041
  }
179591
180042
  return await getIndexProjectTool().handle({
@@ -179739,9 +180190,9 @@ var analyticsRoutes = new Elysia({ prefix: "/api/v1/analytics" }).post("/", asyn
179739
180190
 
179740
180191
  // src/routes/system.ts
179741
180192
  init_dist();
179742
- import path35 from "path";
179743
- import fs23 from "fs";
179744
- import os7 from "os";
180193
+ import path37 from "path";
180194
+ import fs24 from "fs";
180195
+ import os9 from "os";
179745
180196
  function databaseUrlParts() {
179746
180197
  const url2 = new URL(process.env.DATABASE_URL);
179747
180198
  return {
@@ -179772,13 +180223,13 @@ var systemRoutes = new Elysia({ prefix: "/api/v1/system" }).get("/info", async (
179772
180223
  version: "1.0.0",
179773
180224
  service: "massa-ai-tools-api",
179774
180225
  node: process.version,
179775
- platform: os7.platform(),
179776
- arch: os7.arch(),
180226
+ platform: os9.platform(),
180227
+ arch: os9.arch(),
179777
180228
  uptime: process.uptime(),
179778
180229
  memory: {
179779
- total: os7.totalmem(),
179780
- free: os7.freemem(),
179781
- used: os7.totalmem() - os7.freemem(),
180230
+ total: os9.totalmem(),
180231
+ free: os9.freemem(),
180232
+ used: os9.totalmem() - os9.freemem(),
179782
180233
  process: process.memoryUsage()
179783
180234
  },
179784
180235
  dataDir: config.get("dataDir"),
@@ -179814,11 +180265,11 @@ var systemRoutes = new Elysia({ prefix: "/api/v1/system" }).get("/info", async (
179814
180265
  description: "Check PostgreSQL, pgvector, Ollama, and local artifact directory health"
179815
180266
  }
179816
180267
  }).get("/metrics", async () => {
179817
- const metricsPath = path35.join(process.cwd(), "data", "metrics.json");
180268
+ const metricsPath = path37.join(process.cwd(), "data", "metrics.json");
179818
180269
  let metrics2 = {};
179819
- if (fs23.existsSync(metricsPath)) {
180270
+ if (fs24.existsSync(metricsPath)) {
179820
180271
  try {
179821
- metrics2 = JSON.parse(fs23.readFileSync(metricsPath, "utf-8"));
180272
+ metrics2 = JSON.parse(fs24.readFileSync(metricsPath, "utf-8"));
179822
180273
  } catch {}
179823
180274
  }
179824
180275
  const database = await getDatabaseInfo();
@@ -179968,8 +180419,8 @@ var eventsRoutes = new Elysia({ prefix: "/api/v1" }).get("/events", async ({ que
179968
180419
  });
179969
180420
 
179970
180421
  // src/routes/workspace.ts
179971
- import fs24 from "fs/promises";
179972
- import path36 from "path";
180422
+ import fs25 from "fs/promises";
180423
+ import path38 from "path";
179973
180424
  import { realpathSync as realpathSync4 } from "fs";
179974
180425
  var indexProjectTool2 = null;
179975
180426
  function getIndexProjectTool2() {
@@ -180011,7 +180462,7 @@ function realpathSafe(p) {
180011
180462
  try {
180012
180463
  return realpathSync4(p);
180013
180464
  } catch {
180014
- return path36.resolve(p);
180465
+ return path38.resolve(p);
180015
180466
  }
180016
180467
  }
180017
180468
  var graphController = null;
@@ -180362,8 +180813,8 @@ var workspaceRoutes = new Elysia({ prefix: "/api/v1" }).get("/workspace/list", a
180362
180813
  }
180363
180814
  const registeredRoot = realpathSafe(workspace.project_path);
180364
180815
  const callerRoot = realpathSafe(projectPath2);
180365
- const rel = path36.relative(registeredRoot, callerRoot);
180366
- const escapes = rel.startsWith("..") || path36.isAbsolute(rel);
180816
+ const rel = path38.relative(registeredRoot, callerRoot);
180817
+ const escapes = rel.startsWith("..") || path38.isAbsolute(rel);
180367
180818
  if (registeredRoot !== callerRoot && escapes) {
180368
180819
  return {
180369
180820
  success: false,
@@ -180493,8 +180944,8 @@ var workspaceRoutes = new Elysia({ prefix: "/api/v1" }).get("/workspace/list", a
180493
180944
  } else {
180494
180945
  end = start + 20;
180495
180946
  }
180496
- const absolutePath = path36.join(workspace.project_path, file3);
180497
- const content = await fs24.readFile(absolutePath, "utf-8");
180947
+ const absolutePath = path38.join(workspace.project_path, file3);
180948
+ const content = await fs25.readFile(absolutePath, "utf-8");
180498
180949
  const lines = content.split(/\r?\n/);
180499
180950
  const slice = lines.slice(start - 1, Math.min(lines.length, end));
180500
180951
  const formatted = slice.map((text3, idx) => ({
@@ -181419,8 +181870,8 @@ var webRoutes = new Elysia({ prefix: "/api/v1/web" }).post("/fetch_and_index", a
181419
181870
  });
181420
181871
 
181421
181872
  // src/routes/web-ui.ts
181422
- import fs25 from "fs/promises";
181423
- import path37 from "path";
181873
+ import fs26 from "fs/promises";
181874
+ import path39 from "path";
181424
181875
  import { fileURLToPath as fileURLToPath3 } from "url";
181425
181876
 
181426
181877
  // src/web-ui-trust.ts
@@ -181464,9 +181915,9 @@ function buildStaticDirCandidates(moduleDir, cwd) {
181464
181915
  for (const root2 of [moduleDir, cwd]) {
181465
181916
  let dir = root2;
181466
181917
  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);
181918
+ candidates2.push(path39.resolve(dir, "apps/web-ui/src/static"));
181919
+ candidates2.push(path39.resolve(dir, "web-ui/src/static"));
181920
+ const parent = path39.dirname(dir);
181470
181921
  if (parent === dir)
181471
181922
  break;
181472
181923
  dir = parent;
@@ -181474,11 +181925,11 @@ function buildStaticDirCandidates(moduleDir, cwd) {
181474
181925
  }
181475
181926
  return [...new Set(candidates2)];
181476
181927
  }
181477
- var STATIC_DIR_CANDIDATES = buildStaticDirCandidates(path37.dirname(fileURLToPath3(import.meta.url)), process.cwd());
181928
+ var STATIC_DIR_CANDIDATES = buildStaticDirCandidates(path39.dirname(fileURLToPath3(import.meta.url)), process.cwd());
181478
181929
  async function resolveStaticDir() {
181479
181930
  for (const dir of STATIC_DIR_CANDIDATES) {
181480
181931
  try {
181481
- const st = await fs25.stat(dir);
181932
+ const st = await fs26.stat(dir);
181482
181933
  if (st.isDirectory())
181483
181934
  return dir;
181484
181935
  } catch {}
@@ -181499,7 +181950,7 @@ var CONTENT_TYPES = {
181499
181950
  ".woff2": "font/woff2"
181500
181951
  };
181501
181952
  function contentTypeFor(filePath) {
181502
- const ext2 = path37.extname(filePath).toLowerCase();
181953
+ const ext2 = path39.extname(filePath).toLowerCase();
181503
181954
  return CONTENT_TYPES[ext2] ?? "application/octet-stream";
181504
181955
  }
181505
181956
  function webUiDisabled() {
@@ -181510,13 +181961,13 @@ function webUiDisabled() {
181510
181961
  }
181511
181962
  async function resolveSafePath(staticDir, sub) {
181512
181963
  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)) {
181964
+ const abs = path39.resolve(staticDir, cleaned);
181965
+ const rel = path39.relative(staticDir, abs);
181966
+ if (rel.startsWith("..") || path39.isAbsolute(rel)) {
181516
181967
  return null;
181517
181968
  }
181518
181969
  try {
181519
- await fs25.stat(abs);
181970
+ await fs26.stat(abs);
181520
181971
  return { abs, exists: true };
181521
181972
  } catch {
181522
181973
  return { abs, exists: false };
@@ -181539,7 +181990,7 @@ function injectAccessMarkup(html, apiKey, trusted) {
181539
181990
  return out;
181540
181991
  }
181541
181992
  async function readShell(indexPath, remoteAddress) {
181542
- const raw2 = await fs25.readFile(indexPath, "utf-8");
181993
+ const raw2 = await fs26.readFile(indexPath, "utf-8");
181543
181994
  const trusted = isTrustedWebUiCaller(remoteAddress);
181544
181995
  return Buffer.from(injectAccessMarkup(raw2, getConfiguredApiKey(), trusted), "utf-8");
181545
181996
  }
@@ -181556,7 +182007,7 @@ var webUiRoutes = new Elysia().get("/ui", async ({ set: set3, request }) => {
181556
182007
  set3.status = 500;
181557
182008
  return { status: 500, error: "web ui static dir not found" };
181558
182009
  }
181559
- const indexPath = path37.join(dir, "index.html");
182010
+ const indexPath = path39.join(dir, "index.html");
181560
182011
  try {
181561
182012
  const body = await readShell(indexPath, remoteAddressOf(request));
181562
182013
  set3.headers["content-type"] = contentTypeFor(indexPath);
@@ -181589,7 +182040,7 @@ var webUiRoutes = new Elysia().get("/ui", async ({ set: set3, request }) => {
181589
182040
  }
181590
182041
  if (resolved.exists) {
181591
182042
  try {
181592
- const body = await fs25.readFile(resolved.abs);
182043
+ const body = await fs26.readFile(resolved.abs);
181593
182044
  set3.headers["content-type"] = contentTypeFor(resolved.abs);
181594
182045
  return body;
181595
182046
  } catch {
@@ -181598,7 +182049,7 @@ var webUiRoutes = new Elysia().get("/ui", async ({ set: set3, request }) => {
181598
182049
  }
181599
182050
  }
181600
182051
  try {
181601
- const body = await readShell(path37.join(dir, "index.html"), remoteAddressOf(request));
182052
+ const body = await readShell(path39.join(dir, "index.html"), remoteAddressOf(request));
181602
182053
  set3.headers["content-type"] = "text/html; charset=utf-8";
181603
182054
  return body;
181604
182055
  } catch {
@@ -181746,8 +182197,8 @@ init_dist();
181746
182197
 
181747
182198
  // src/routes/model-registry-deployment.ts
181748
182199
  init_dist();
181749
- import path38 from "path";
181750
- var MARKER = path38.join("scripts", "generate-subagent-artifacts.ts");
182200
+ import path40 from "path";
182201
+ var MARKER = path40.join("scripts", "generate-subagent-artifacts.ts");
181751
182202
  var MAX_LEVELS2 = 6;
181752
182203
  var cachedRoot;
181753
182204
  function findDeploymentRoot(startDir) {
@@ -181765,8 +182216,8 @@ function deploymentUnavailableMessage(what) {
181765
182216
 
181766
182217
  // src/routes/model-registry.ts
181767
182218
  init_config();
181768
- import fs26 from "fs";
181769
- import path39 from "path";
182219
+ import fs27 from "fs";
182220
+ import path41 from "path";
181770
182221
  import { spawnSync } from "child_process";
181771
182222
  var _profilesLib = null;
181772
182223
  function profilesLib() {
@@ -181775,7 +182226,7 @@ function profilesLib() {
181775
182226
  if (!root2) {
181776
182227
  throw new Error(deploymentUnavailableMessage("scripts/lib/model-profiles.ts"));
181777
182228
  }
181778
- const libPath = path39.join(root2, "scripts", "lib", "model-profiles.ts");
182229
+ const libPath = path41.join(root2, "scripts", "lib", "model-profiles.ts");
181779
182230
  _profilesLib = __require(libPath);
181780
182231
  }
181781
182232
  return _profilesLib;
@@ -181800,7 +182251,7 @@ function generatorLib() {
181800
182251
  if (!root2) {
181801
182252
  throw new Error(deploymentUnavailableMessage("scripts/generate-subagent-artifacts.ts"));
181802
182253
  }
181803
- const libPath = path39.join(root2, "scripts", "generate-subagent-artifacts.ts");
182254
+ const libPath = path41.join(root2, "scripts", "generate-subagent-artifacts.ts");
181804
182255
  _generatorLib = __require(libPath);
181805
182256
  }
181806
182257
  return _generatorLib;
@@ -181817,7 +182268,7 @@ async function loadAgentsInventory() {
181817
182268
  var REGISTRY_DETAIL = {
181818
182269
  tags: ["model-registry"]
181819
182270
  };
181820
- var OVERLAY_PATH = path39.join(configDir("massa-ai"), "model-profiles.json");
182271
+ var OVERLAY_PATH = path41.join(configDir("massa-ai"), "model-profiles.json");
181821
182272
  var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("/", async ({ set: set3 }) => {
181822
182273
  const root2 = getDeploymentRoot();
181823
182274
  if (!root2) {
@@ -181900,7 +182351,7 @@ var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("
181900
182351
  set3.status = 501;
181901
182352
  return { success: false, error: deploymentUnavailableMessage("scripts/generate-subagent-artifacts.ts") };
181902
182353
  }
181903
- const generateScript = path39.join(root2, "scripts", "generate-subagent-artifacts.ts");
182354
+ const generateScript = path41.join(root2, "scripts", "generate-subagent-artifacts.ts");
181904
182355
  try {
181905
182356
  const child = spawnSync("bun", [generateScript], {
181906
182357
  env: { ...process.env },
@@ -181939,8 +182390,8 @@ var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("
181939
182390
  }
181940
182391
  const lib = profilesLib();
181941
182392
  try {
181942
- if (fs26.existsSync(OVERLAY_PATH)) {
181943
- fs26.unlinkSync(OVERLAY_PATH);
182393
+ if (fs27.existsSync(OVERLAY_PATH)) {
182394
+ fs27.unlinkSync(OVERLAY_PATH);
181944
182395
  }
181945
182396
  const builtin = lib.loadRegistry(lib.DEFAULT_REGISTRY_PATH);
181946
182397
  set3.status = 200;
@@ -181966,17 +182417,17 @@ var modelRegistryRoutes = new Elysia({ prefix: "/api/v1/model-registry" }).get("
181966
182417
  }
181967
182418
  });
181968
182419
  function writeOverlayAtomically(overlayPath, data) {
181969
- const dir = path39.dirname(overlayPath);
181970
- if (!fs26.existsSync(dir)) {
181971
- fs26.mkdirSync(dir, { recursive: true });
182420
+ const dir = path41.dirname(overlayPath);
182421
+ if (!fs27.existsSync(dir)) {
182422
+ fs27.mkdirSync(dir, { recursive: true });
181972
182423
  }
181973
182424
  const tmp = `${overlayPath}.${process.pid}.${Date.now()}.tmp`;
181974
182425
  try {
181975
- fs26.writeFileSync(tmp, JSON.stringify(data, null, 2));
181976
- fs26.renameSync(tmp, overlayPath);
182426
+ fs27.writeFileSync(tmp, JSON.stringify(data, null, 2));
182427
+ fs27.renameSync(tmp, overlayPath);
181977
182428
  } catch (e) {
181978
182429
  try {
181979
- fs26.unlinkSync(tmp);
182430
+ fs27.unlinkSync(tmp);
181980
182431
  } catch {}
181981
182432
  throw e;
181982
182433
  }
@@ -182166,7 +182617,7 @@ var configRoutes = new Elysia({ prefix: "/api/v1/config" }).get("/", ({ set: set
182166
182617
  // src/routes/model-registry-stream.ts
182167
182618
  init_config();
182168
182619
  init_dist();
182169
- import path40 from "path";
182620
+ import path42 from "path";
182170
182621
  import { spawn as spawn3 } from "child_process";
182171
182622
  var encoder3 = new TextEncoder;
182172
182623
  function sseFrame(data) {
@@ -182248,7 +182699,7 @@ function createRegenerateStreamHandler() {
182248
182699
  closedRef.closed = true;
182249
182700
  return;
182250
182701
  }
182251
- const generateScript = path40.join(root2, "scripts", "generate-subagent-artifacts.ts");
182702
+ const generateScript = path42.join(root2, "scripts", "generate-subagent-artifacts.ts");
182252
182703
  try {
182253
182704
  child = spawn3("bun", [generateScript], {
182254
182705
  env: { ...process.env },
@@ -182440,13 +182891,324 @@ var restartRoutes = new Elysia({ prefix: "/api/v1/system" }).onAfterResponse(()
182440
182891
  }
182441
182892
  });
182442
182893
 
182894
+ // src/routes/logs.ts
182895
+ init_dist();
182896
+ import fs28 from "fs";
182897
+ var LOGS_DETAIL = { tags: ["logs"] };
182898
+ var MAX_SCAN_BYTES = 64 * 1024 * 1024;
182899
+ var MAX_LIMIT = 1000;
182900
+ var DEFAULT_LIMIT = 200;
182901
+ function isQueryValidationError(v) {
182902
+ return "param" in v;
182903
+ }
182904
+ function parseRangeQuery(query) {
182905
+ const fromRaw = query.from;
182906
+ const toRaw = query.to;
182907
+ const fromMs = fromRaw !== undefined ? Date.parse(fromRaw) : -Infinity;
182908
+ if (fromRaw !== undefined && Number.isNaN(fromMs)) {
182909
+ return { param: "from", message: `"from" is not a parseable ISO-8601 timestamp: "${fromRaw}"` };
182910
+ }
182911
+ const toMs = toRaw !== undefined ? Date.parse(toRaw) : Infinity;
182912
+ if (toRaw !== undefined && Number.isNaN(toMs)) {
182913
+ return { param: "to", message: `"to" is not a parseable ISO-8601 timestamp: "${toRaw}"` };
182914
+ }
182915
+ if (fromMs > toMs) {
182916
+ return { param: "from", message: `"from" (${fromRaw}) is after "to" (${toRaw})` };
182917
+ }
182918
+ let limit = DEFAULT_LIMIT;
182919
+ if (query.limit !== undefined) {
182920
+ const n2 = Number(query.limit);
182921
+ if (!Number.isFinite(n2) || n2 < 0) {
182922
+ return { param: "limit", message: `"limit" must be a non-negative number: "${query.limit}"` };
182923
+ }
182924
+ if (n2 > MAX_LIMIT) {
182925
+ return { param: "limit", message: `"limit" exceeds the maximum of ${MAX_LIMIT}: "${query.limit}"` };
182926
+ }
182927
+ limit = Math.floor(n2);
182928
+ }
182929
+ let offset = 0;
182930
+ if (query.offset !== undefined) {
182931
+ const n2 = Number(query.offset);
182932
+ if (!Number.isFinite(n2) || n2 < 0) {
182933
+ return { param: "offset", message: `"offset" must be a non-negative number: "${query.offset}"` };
182934
+ }
182935
+ offset = Math.floor(n2);
182936
+ }
182937
+ return { fromMs, toMs, fromRaw, toRaw, level: query.level, q: query.q, limit, offset };
182938
+ }
182939
+ var LINE_RE = /^\[(?<ts>[^\]]+)\] \[(?<level>[A-Z]+)\] (?<rest>[\s\S]*)$/;
182940
+ function normalizeLevel(raw2) {
182941
+ const lower2 = raw2.toLowerCase();
182942
+ return lower2 === "debug" || lower2 === "info" || lower2 === "warn" || lower2 === "error" ? lower2 : "raw";
182943
+ }
182944
+ function splitMessageAndMeta(rest) {
182945
+ if (!rest.endsWith("}"))
182946
+ return { message: rest };
182947
+ let searchFrom = rest.length;
182948
+ for (;; ) {
182949
+ const idx = rest.lastIndexOf(" {", searchFrom - 1);
182950
+ if (idx === -1)
182951
+ break;
182952
+ const candidate2 = rest.slice(idx + 1);
182953
+ try {
182954
+ const parsed = JSON.parse(candidate2);
182955
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
182956
+ return { message: rest.slice(0, idx), meta: parsed };
182957
+ }
182958
+ } catch {}
182959
+ searchFrom = idx;
182960
+ }
182961
+ return { message: rest };
182962
+ }
182963
+ function parseLine(line, prevTs) {
182964
+ const match2 = LINE_RE.exec(line);
182965
+ if (!match2 || !match2.groups) {
182966
+ return { entry: { seq: 0, ts: prevTs, level: "raw", message: line }, ts: prevTs };
182967
+ }
182968
+ const { ts, level, rest } = match2.groups;
182969
+ const { message, meta: meta3 } = splitMessageAndMeta(rest);
182970
+ const entry2 = { seq: 0, ts, level: normalizeLevel(level), message, ...meta3 ? { meta: meta3 } : {} };
182971
+ return { entry: entry2, ts };
182972
+ }
182973
+ function realReadTail(filePath, maxBytes) {
182974
+ let size;
182975
+ try {
182976
+ size = fs28.statSync(filePath).size;
182977
+ } catch {
182978
+ return { content: "", truncated: false };
182979
+ }
182980
+ if (size === 0)
182981
+ return { content: "", truncated: false };
182982
+ if (size <= maxBytes) {
182983
+ try {
182984
+ return { content: fs28.readFileSync(filePath, "utf8"), truncated: false };
182985
+ } catch {
182986
+ return { content: "", truncated: false };
182987
+ }
182988
+ }
182989
+ try {
182990
+ const fd = fs28.openSync(filePath, "r");
182991
+ try {
182992
+ const start = size - maxBytes;
182993
+ const buf = Buffer.alloc(maxBytes);
182994
+ fs28.readSync(fd, buf, 0, maxBytes, start);
182995
+ let text3 = buf.toString("utf8");
182996
+ const firstNewline = text3.indexOf(`
182997
+ `);
182998
+ text3 = firstNewline !== -1 ? text3.slice(firstNewline + 1) : "";
182999
+ return { content: text3, truncated: true };
183000
+ } finally {
183001
+ fs28.closeSync(fd);
183002
+ }
183003
+ } catch {
183004
+ return { content: "", truncated: true };
183005
+ }
183006
+ }
183007
+ var realReader = {
183008
+ listFiles(filePath, maxFiles) {
183009
+ return sinkFiles(filePath, maxFiles).filter((f) => {
183010
+ try {
183011
+ fs28.accessSync(f, fs28.constants.R_OK);
183012
+ return true;
183013
+ } catch {
183014
+ return false;
183015
+ }
183016
+ });
183017
+ },
183018
+ readTail: realReadTail
183019
+ };
183020
+ var activeReader = realReader;
183021
+ function scanEntries() {
183022
+ const loggingConfig = config.get("logging");
183023
+ const filePath = loggingConfig.file;
183024
+ const files = filePath ? activeReader.listFiles(filePath, loggingConfig.maxFiles) : [];
183025
+ if (files.length === 0) {
183026
+ return { entries: logBuffer.snapshot(), source: "buffer", truncated: false };
183027
+ }
183028
+ const readFiles = [];
183029
+ let budgetLeft = MAX_SCAN_BYTES;
183030
+ let truncated = false;
183031
+ for (const file3 of files) {
183032
+ if (budgetLeft <= 0) {
183033
+ truncated = true;
183034
+ break;
183035
+ }
183036
+ const { content, truncated: fileTruncated } = activeReader.readTail(file3, budgetLeft);
183037
+ if (fileTruncated)
183038
+ truncated = true;
183039
+ readFiles.push(content);
183040
+ budgetLeft -= Buffer.byteLength(content, "utf8");
183041
+ if (fileTruncated)
183042
+ break;
183043
+ }
183044
+ let prevTs = new Date().toISOString();
183045
+ const chronoEntries = [];
183046
+ for (let i = readFiles.length - 1;i >= 0; i--) {
183047
+ const lines = readFiles[i].split(`
183048
+ `).filter((l2) => l2.length > 0);
183049
+ for (const line of lines) {
183050
+ const { entry: entry2, ts } = parseLine(line, prevTs);
183051
+ prevTs = ts;
183052
+ chronoEntries.push(entry2);
183053
+ }
183054
+ }
183055
+ const entries = chronoEntries.reverse();
183056
+ for (let i = 0;i < entries.length; i++) {
183057
+ entries[i].seq = entries.length - 1 - i;
183058
+ }
183059
+ return { entries, source: "file", truncated };
183060
+ }
183061
+ function matchesFilter(entry2, parsed) {
183062
+ const tsMs = Date.parse(entry2.ts);
183063
+ if (Number.isNaN(tsMs) || tsMs < parsed.fromMs || tsMs > parsed.toMs)
183064
+ return false;
183065
+ if (parsed.level !== undefined && entry2.level !== parsed.level)
183066
+ return false;
183067
+ if (parsed.q !== undefined && !entry2.message.toLowerCase().includes(parsed.q.toLowerCase()))
183068
+ return false;
183069
+ return true;
183070
+ }
183071
+ function filteredEntries(parsed) {
183072
+ const scan = scanEntries();
183073
+ return { ...scan, entries: scan.entries.filter((e) => matchesFilter(e, parsed)) };
183074
+ }
183075
+ function sanitizeForFilename(s) {
183076
+ return s.replace(/[^A-Za-z0-9._-]/g, "-");
183077
+ }
183078
+ function exportFilename(parsed, ext2) {
183079
+ const fromPart = sanitizeForFilename(parsed.fromRaw ?? "all");
183080
+ const toPart = sanitizeForFilename(parsed.toRaw ?? "all");
183081
+ return `massa-ai-logs-${fromPart}_${toPart}.${ext2}`;
183082
+ }
183083
+ function renderTxtLine(entry2) {
183084
+ const metaStr = entry2.meta ? ` ${JSON.stringify(entry2.meta)}` : "";
183085
+ return `[${entry2.ts}] [${entry2.level.toUpperCase()}] ${entry2.message}${metaStr}`;
183086
+ }
183087
+ var SSE_HEARTBEAT_MS_DEFAULT = 15000;
183088
+ var SSE_MAX_DURATION_MS_DEFAULT = 10 * 60 * 1000;
183089
+ var logsRoutes = new Elysia({ prefix: "/api/v1/logs" }).get("/", ({ query, set: set3 }) => {
183090
+ const parsed = parseRangeQuery(query);
183091
+ if (isQueryValidationError(parsed)) {
183092
+ set3.status = 400;
183093
+ return { success: false, error: `invalid "${parsed.param}": ${parsed.message}` };
183094
+ }
183095
+ const { entries, source, truncated } = filteredEntries(parsed);
183096
+ const total = entries.length;
183097
+ const page = entries.slice(parsed.offset, parsed.offset + parsed.limit);
183098
+ set3.status = 200;
183099
+ return { success: true, data: { entries: page, total, source, truncated } };
183100
+ }, {
183101
+ detail: {
183102
+ ...LOGS_DETAIL,
183103
+ summary: "Range/level/substring query over the log sink (or the ring buffer)",
183104
+ 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.'
183105
+ }
183106
+ }).get("/export", ({ query, set: set3 }) => {
183107
+ const parsed = parseRangeQuery(query);
183108
+ if (isQueryValidationError(parsed)) {
183109
+ set3.status = 400;
183110
+ return { success: false, error: `invalid "${parsed.param}": ${parsed.message}` };
183111
+ }
183112
+ const { entries } = filteredEntries(parsed);
183113
+ const format = query.format === "txt" ? "txt" : "jsonl";
183114
+ const ext2 = format === "txt" ? "txt" : "jsonl";
183115
+ const contentType = format === "txt" ? "text/plain" : "application/x-ndjson";
183116
+ const body = format === "txt" ? entries.map(renderTxtLine).join(`
183117
+ `) : entries.map((e) => JSON.stringify(e)).join(`
183118
+ `);
183119
+ const filename = exportFilename(parsed, ext2);
183120
+ return new Response(body, {
183121
+ status: 200,
183122
+ headers: {
183123
+ "Content-Type": contentType,
183124
+ "Content-Disposition": `attachment; filename="${filename}"`
183125
+ }
183126
+ });
183127
+ }, {
183128
+ detail: {
183129
+ ...LOGS_DETAIL,
183130
+ summary: "Download the queried log range as jsonl or txt",
183131
+ 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."
183132
+ }
183133
+ }).get("/stream", () => {
183134
+ const HEARTBEAT_MS = Number(process.env.MASSA_AI_SSE_HEARTBEAT_MS) || SSE_HEARTBEAT_MS_DEFAULT;
183135
+ const MAX_DURATION_MS = Number(process.env.MASSA_AI_SSE_MAX_DURATION_MS) || SSE_MAX_DURATION_MS_DEFAULT;
183136
+ const encoder4 = new TextEncoder;
183137
+ let closed = false;
183138
+ let unsubscribe;
183139
+ let heartbeatTimer;
183140
+ let closeTimer;
183141
+ const stream2 = new ReadableStream({
183142
+ start(controller2) {
183143
+ const enqueue = (data) => {
183144
+ if (closed)
183145
+ return;
183146
+ try {
183147
+ controller2.enqueue(encoder4.encode(`data: ${JSON.stringify(data)}
183148
+
183149
+ `));
183150
+ } catch {
183151
+ closed = true;
183152
+ }
183153
+ };
183154
+ unsubscribe = logBuffer.subscribe((entry2) => {
183155
+ enqueue(entry2);
183156
+ });
183157
+ heartbeatTimer = setInterval(() => {
183158
+ if (closed) {
183159
+ clearInterval(heartbeatTimer);
183160
+ return;
183161
+ }
183162
+ try {
183163
+ controller2.enqueue(encoder4.encode(`: heartbeat
183164
+
183165
+ `));
183166
+ } catch {
183167
+ closed = true;
183168
+ clearInterval(heartbeatTimer);
183169
+ }
183170
+ }, HEARTBEAT_MS);
183171
+ closeTimer = setTimeout(() => {
183172
+ closed = true;
183173
+ unsubscribe?.();
183174
+ clearInterval(heartbeatTimer);
183175
+ try {
183176
+ controller2.close();
183177
+ } catch {}
183178
+ }, MAX_DURATION_MS);
183179
+ },
183180
+ cancel() {
183181
+ closed = true;
183182
+ unsubscribe?.();
183183
+ if (heartbeatTimer)
183184
+ clearInterval(heartbeatTimer);
183185
+ if (closeTimer)
183186
+ clearTimeout(closeTimer);
183187
+ }
183188
+ });
183189
+ return new Response(stream2, {
183190
+ headers: {
183191
+ "Content-Type": "text/event-stream",
183192
+ "Cache-Control": "no-cache",
183193
+ Connection: "keep-alive",
183194
+ "X-Accel-Buffering": "no"
183195
+ }
183196
+ });
183197
+ }, {
183198
+ detail: {
183199
+ ...LOGS_DETAIL,
183200
+ summary: "SSE tail of newly buffered log entries",
183201
+ 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)."
183202
+ }
183203
+ });
183204
+
182443
183205
  // src/middleware/error.ts
182444
183206
  init_dist();
182445
- var errorHandler = new Elysia({ name: "error-handler" }).onError(({ code, error: error51, set: set3, path: path41, request }) => {
183207
+ var errorHandler = new Elysia({ name: "error-handler" }).onError(({ code, error: error51, set: set3, path: path43, request }) => {
182446
183208
  logger.error("[massa-ai-api] Request failed", undefined, {
182447
183209
  ...safeErrorSummary(error51),
182448
183210
  code,
182449
- path: path41,
183211
+ path: path43,
182450
183212
  method: request.method
182451
183213
  });
182452
183214
  if (error51 instanceof SearchServiceError) {
@@ -182548,7 +183310,8 @@ var app = new Elysia({ adapter: node() }).use(cors(buildCorsOptions(config.get("
182548
183310
  { name: "executor", description: "Polyglot sandbox: execute code, run code over files, batch shell commands" },
182549
183311
  { name: "web", description: "SSRF-guarded web fetch + HTML\u2192md + index (fetch_and_index)" },
182550
183312
  { name: "webUi", description: "Read-only memory/search web browser (Phase 8)" },
182551
- { name: "profiles", description: "Model-profile switch: list shipped profiles, switch installed agents" }
183313
+ { name: "profiles", description: "Model-profile switch: list shipped profiles, switch installed agents" },
183314
+ { name: "logs", description: "Log read: range/level/substring query, export, live SSE tail" }
182552
183315
  ],
182553
183316
  components: {
182554
183317
  securitySchemes: {
@@ -182562,7 +183325,7 @@ var app = new Elysia({ adapter: node() }).use(cors(buildCorsOptions(config.get("
182562
183325
  },
182563
183326
  security: [{ ApiKeyAuth: [] }]
182564
183327
  }
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()));
183328
+ })).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
183329
  initAuthOrExit();
182567
183330
  warnIfTrustOverrideEnabled();
182568
183331
  await listenAfterParserValidation({