@massa-ai/mcp-client 1.46.0 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/config-cli.js +958 -467
  2. package/dist/index.js +1007 -516
  3. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -25398,9 +25398,64 @@ var init_xdg = () => {};
25398
25398
 
25399
25399
  // ../../packages/shared/dist/config/massa-ai-config.js
25400
25400
  import path2 from "path";
25401
- var defaultMassaAiConfig;
25401
+ var SCHEDULER_JOB_KINDS, MAX_MATCH_WORK = 1e5, MAX_IGNORE_PATTERNS = 1024, DEFAULT_CAPTURE_POLICY, DEFAULT_SCHEDULER_CONFIG, defaultMassaAiConfig;
25402
25402
  var init_massa_ai_config = __esm(() => {
25403
25403
  init_xdg();
25404
+ SCHEDULER_JOB_KINDS = [
25405
+ "memory-consolidation",
25406
+ "decay-sweep",
25407
+ "auto-improve",
25408
+ "observation-bridge",
25409
+ "checkpoint-purge"
25410
+ ];
25411
+ DEFAULT_CAPTURE_POLICY = {
25412
+ rules: [
25413
+ { pattern: "**/node_modules/**", disposition: "Drop" },
25414
+ { pattern: "**/.git/**", disposition: "Drop" },
25415
+ { pattern: "**/dist/**", disposition: "Drop" },
25416
+ { pattern: "**/build/**", disposition: "Drop" },
25417
+ { pattern: "**/coverage/**", disposition: "Drop" },
25418
+ { pattern: ".env", disposition: "Drop" },
25419
+ { pattern: ".env.*", disposition: "Drop" },
25420
+ { pattern: "**/generated/**", disposition: "Drop" },
25421
+ { pattern: "**/*.generated.*", disposition: "Drop" },
25422
+ { pattern: "**/*.d.ts", disposition: "Drop" },
25423
+ { pattern: "**/__tests__/**", disposition: "Drop" },
25424
+ { pattern: "**/tests/**", disposition: "Drop" },
25425
+ { pattern: "**/*.test.ts", disposition: "Drop" },
25426
+ { pattern: "**/*.test.tsx", disposition: "Drop" },
25427
+ { pattern: "**/*.test.js", disposition: "Drop" },
25428
+ { pattern: "**/*.test.jsx", disposition: "Drop" },
25429
+ { pattern: "**/*.spec.ts", disposition: "Drop" },
25430
+ { pattern: "**/*.spec.tsx", disposition: "Drop" },
25431
+ { pattern: "**/*.spec.js", disposition: "Drop" },
25432
+ { pattern: "**/*.spec.jsx", disposition: "Drop" },
25433
+ { pattern: "**/benchmarks/**", disposition: "Drop" },
25434
+ { pattern: "**/fixtures/**", disposition: "Drop" },
25435
+ { pattern: "**/*.wasm*", disposition: "Drop" },
25436
+ { pattern: "**/*.min.*", disposition: "Drop" },
25437
+ { pattern: "**/*.map", disposition: "Drop" },
25438
+ { pattern: "**/lock.yaml", disposition: "Drop" },
25439
+ { pattern: "**/pnpm-lock.yaml", disposition: "Drop" },
25440
+ { pattern: "**/package-lock.json", disposition: "Drop" },
25441
+ { pattern: "**/bun.lockb", disposition: "Drop" },
25442
+ { pattern: "**/yarn.lock", disposition: "Drop" }
25443
+ ],
25444
+ maxMatchWork: MAX_MATCH_WORK,
25445
+ maxIgnorePatterns: MAX_IGNORE_PATTERNS
25446
+ };
25447
+ DEFAULT_SCHEDULER_CONFIG = {
25448
+ enabled: false,
25449
+ tickMs: 60000,
25450
+ maxConcurrent: 2,
25451
+ jobs: {
25452
+ "memory-consolidation": { enabled: false, intervalMs: 30 * 60 * 1000 },
25453
+ "decay-sweep": { enabled: false, intervalMs: 60 * 60 * 1000 },
25454
+ "auto-improve": { enabled: false, intervalMs: 30 * 60 * 1000 },
25455
+ "observation-bridge": { enabled: false, intervalMs: 30 * 60 * 1000 },
25456
+ "checkpoint-purge": { enabled: false, intervalMs: 60 * 60 * 1000 }
25457
+ }
25458
+ };
25404
25459
  defaultMassaAiConfig = {
25405
25460
  database: {
25406
25461
  url: ""
@@ -25419,7 +25474,7 @@ var init_massa_ai_config = __esm(() => {
25419
25474
  impact: {
25420
25475
  bfsCteEnabled: false
25421
25476
  },
25422
- capturePolicy: undefined,
25477
+ capturePolicy: DEFAULT_CAPTURE_POLICY,
25423
25478
  cache: {
25424
25479
  enabled: true,
25425
25480
  l1MaxSizeMB: 100,
@@ -25542,7 +25597,8 @@ var init_massa_ai_config = __esm(() => {
25542
25597
  },
25543
25598
  security: {
25544
25599
  corsOrigins: []
25545
- }
25600
+ },
25601
+ scheduler: DEFAULT_SCHEDULER_CONFIG
25546
25602
  };
25547
25603
  });
25548
25604
 
@@ -25552,6 +25608,8 @@ __export(exports_config_loader, {
25552
25608
  writeFileAtomically: () => writeFileAtomically,
25553
25609
  saveConfig: () => saveConfig,
25554
25610
  migrateDataDirOnce: () => migrateDataDirOnce,
25611
+ mergeSchedulerSection: () => mergeSchedulerSection,
25612
+ loadRawUserConfig: () => loadRawUserConfig,
25555
25613
  loadConfigSafe: () => loadConfigSafe,
25556
25614
  loadConfig: () => loadConfig,
25557
25615
  initConfig: () => initConfig,
@@ -25574,6 +25632,22 @@ function getConfigPath() {
25574
25632
  function configExists() {
25575
25633
  return fs.existsSync(CONFIG_FILE);
25576
25634
  }
25635
+ function mergeSchedulerJobs(base, incoming) {
25636
+ const defaults = defaultMassaAiConfig.scheduler?.jobs ?? {};
25637
+ const merged = {};
25638
+ for (const kind of Object.keys(defaults)) {
25639
+ merged[kind] = { ...defaults[kind], ...base?.[kind], ...incoming?.[kind] };
25640
+ }
25641
+ return merged;
25642
+ }
25643
+ function mergeSchedulerSection(base, incoming) {
25644
+ return {
25645
+ ...defaultMassaAiConfig.scheduler,
25646
+ ...base,
25647
+ ...incoming,
25648
+ jobs: mergeSchedulerJobs(base?.jobs, incoming?.jobs)
25649
+ };
25650
+ }
25577
25651
  function loadConfig() {
25578
25652
  if (!fs.existsSync(CONFIG_FILE)) {
25579
25653
  return defaultMassaAiConfig;
@@ -25594,13 +25668,27 @@ function loadConfig() {
25594
25668
  memory: { ...defaultMassaAiConfig.memory, ...userConfig.memory },
25595
25669
  hooks: { ...defaultMassaAiConfig.hooks, ...userConfig.hooks },
25596
25670
  handoffs: { ...defaultMassaAiConfig.handoffs, ...userConfig.handoffs },
25597
- security: { ...defaultMassaAiConfig.security, ...userConfig.security }
25671
+ security: { ...defaultMassaAiConfig.security, ...userConfig.security },
25672
+ scheduler: mergeSchedulerSection(undefined, userConfig.scheduler),
25673
+ capturePolicy: userConfig.capturePolicy ?? defaultMassaAiConfig.capturePolicy
25598
25674
  };
25599
25675
  } catch (error51) {
25600
25676
  console.error(`Error loading config from ${CONFIG_FILE}:`, error51);
25601
25677
  return defaultMassaAiConfig;
25602
25678
  }
25603
25679
  }
25680
+ function loadRawUserConfig() {
25681
+ try {
25682
+ if (!fs.existsSync(CONFIG_FILE))
25683
+ return {};
25684
+ const parsed = JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
25685
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
25686
+ return {};
25687
+ return parsed;
25688
+ } catch {
25689
+ return {};
25690
+ }
25691
+ }
25604
25692
  function loadConfigSafe() {
25605
25693
  try {
25606
25694
  return loadConfig();
@@ -25734,6 +25822,7 @@ var init_env = __esm(() => {
25734
25822
  // ../../packages/shared/dist/config/config-writer.js
25735
25823
  var init_config_writer = __esm(() => {
25736
25824
  init_config_loader();
25825
+ init_massa_ai_config();
25737
25826
  });
25738
25827
 
25739
25828
  // ../../packages/shared/dist/config/api-key.js
@@ -25773,6 +25862,31 @@ function parsePositiveIntEnv(raw2, defaultValue, opts) {
25773
25862
  return Number.isInteger(n) && n >= floor ? n : defaultValue;
25774
25863
  }
25775
25864
 
25865
+ // ../../packages/shared/dist/config/embedding-dimensions.js
25866
+ function knownEmbeddingDimensions(model) {
25867
+ if (!model)
25868
+ return;
25869
+ return KNOWN_EMBEDDING_DIMENSIONS[model.trim()];
25870
+ }
25871
+ function resolveEmbeddingDimensions(model, configured, envValue) {
25872
+ if (envValue !== undefined)
25873
+ return { dimensions: envValue };
25874
+ const known = knownEmbeddingDimensions(model);
25875
+ if (known !== undefined) {
25876
+ return configured !== undefined && configured !== known ? { dimensions: known, correctedFrom: configured } : { dimensions: known };
25877
+ }
25878
+ return { dimensions: configured ?? DEFAULT_EMBEDDING_DIMENSIONS };
25879
+ }
25880
+ var KNOWN_EMBEDDING_DIMENSIONS, DEFAULT_EMBEDDING_DIMENSIONS = 2560;
25881
+ var init_embedding_dimensions = __esm(() => {
25882
+ KNOWN_EMBEDDING_DIMENSIONS = {
25883
+ "qwen3-embedding:8b": 4096,
25884
+ "qwen3-embedding:4b": 2560,
25885
+ "qwen3-embedding:0.6b": 1024,
25886
+ "bge-m3": 1024
25887
+ };
25888
+ });
25889
+
25776
25890
  // ../../packages/shared/dist/config/index.js
25777
25891
  import path4 from "path";
25778
25892
  function envNum(key, fallback) {
@@ -25804,6 +25918,22 @@ function envList(key, fallback) {
25804
25918
  const parsed = s.split(",").map((v) => v.trim()).filter((v) => v.length > 0);
25805
25919
  return parsed.length > 0 ? parsed : fallback;
25806
25920
  }
25921
+ function readSchedulerConfig(rawFileConfig) {
25922
+ try {
25923
+ const cfg = rawFileConfig;
25924
+ return cfg?.scheduler ?? {};
25925
+ } catch {
25926
+ return {};
25927
+ }
25928
+ }
25929
+ function resolveSchedulerJob(kind, fileJobs) {
25930
+ const meta3 = SCHEDULER_JOB_ENV[kind];
25931
+ const fileJob = fileJobs?.[kind];
25932
+ return {
25933
+ enabled: envBool(meta3.enabledVar, fileJob?.enabled ?? false),
25934
+ intervalMs: envNum(meta3.intervalVar, fileJob?.intervalMs ?? meta3.defaultIntervalMs)
25935
+ };
25936
+ }
25807
25937
  function validateCapturePolicyConfig(raw2) {
25808
25938
  if (!raw2 || typeof raw2 !== "object")
25809
25939
  throw new TypeError("capturePolicy must be an object");
@@ -25931,6 +26061,11 @@ class Config {
25931
26061
  rateLimit: { ...defaults.rateLimit, ...overrides.rateLimit },
25932
26062
  security: { ...defaults.security, ...overrides.security },
25933
26063
  logging: { ...defaults.logging, ...overrides.logging },
26064
+ scheduler: {
26065
+ ...defaults.scheduler,
26066
+ ...overrides.scheduler,
26067
+ jobs: { ...defaults.scheduler.jobs, ...overrides.scheduler?.jobs }
26068
+ },
25934
26069
  synapse: {
25935
26070
  ...defaults.synapse,
25936
26071
  ...overrides.synapse,
@@ -25999,15 +26134,45 @@ class Config {
25999
26134
  this.config[key] = value;
26000
26135
  }
26001
26136
  }
26002
- 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, config2;
26137
+ var DEFAULT_LLM_MODEL = "qwen2.5:7b-instruct", DEFAULT_LLM_CODE_MODEL = "qwen2.5-coder:7b", SCHEDULER_JOB_ENV, DEFAULT_ALLOWED_EXTENSIONS, fileConfig, fileCacheL1Bytes, fileCacheL2Bytes, resolvedDataDir, defaultConfig, config2;
26003
26138
  var init_config = __esm(() => {
26004
26139
  init_env();
26005
26140
  init_config_loader();
26006
26141
  init_massa_ai_config();
26142
+ init_massa_ai_config();
26143
+ init_massa_ai_config();
26007
26144
  init_config_loader();
26008
26145
  init_config_writer();
26009
26146
  init_xdg();
26010
26147
  init_api_key();
26148
+ init_embedding_dimensions();
26149
+ SCHEDULER_JOB_ENV = {
26150
+ "memory-consolidation": {
26151
+ enabledVar: "MASSA_AI_SCHEDULER_CONSOLIDATION_ENABLED",
26152
+ intervalVar: "MASSA_AI_SCHEDULER_CONSOLIDATION_INTERVAL_MS",
26153
+ defaultIntervalMs: 30 * 60 * 1000
26154
+ },
26155
+ "decay-sweep": {
26156
+ enabledVar: "MASSA_AI_SCHEDULER_DECAY_ENABLED",
26157
+ intervalVar: "MASSA_AI_SCHEDULER_DECAY_INTERVAL_MS",
26158
+ defaultIntervalMs: 60 * 60 * 1000
26159
+ },
26160
+ "auto-improve": {
26161
+ enabledVar: "MASSA_AI_SCHEDULER_AUTO_IMPROVE_ENABLED",
26162
+ intervalVar: "MASSA_AI_SCHEDULER_AUTO_IMPROVE_INTERVAL_MS",
26163
+ defaultIntervalMs: 30 * 60 * 1000
26164
+ },
26165
+ "observation-bridge": {
26166
+ enabledVar: "MASSA_AI_SCHEDULER_OBSERVATION_BRIDGE_ENABLED",
26167
+ intervalVar: "MASSA_AI_SCHEDULER_OBSERVATION_BRIDGE_INTERVAL_MS",
26168
+ defaultIntervalMs: 30 * 60 * 1000
26169
+ },
26170
+ "checkpoint-purge": {
26171
+ enabledVar: "MASSA_AI_SCHEDULER_CHECKPOINT_PURGE_ENABLED",
26172
+ intervalVar: "MASSA_AI_SCHEDULER_CHECKPOINT_PURGE_INTERVAL_MS",
26173
+ defaultIntervalMs: 60 * 60 * 1000
26174
+ }
26175
+ };
26011
26176
  DEFAULT_ALLOWED_EXTENSIONS = [
26012
26177
  ".ts",
26013
26178
  ".js",
@@ -26046,10 +26211,11 @@ var init_config = __esm(() => {
26046
26211
  fileConfig = loadConfigSafe();
26047
26212
  fileCacheL1Bytes = fileConfig.cache?.l1MaxSizeMB ? fileConfig.cache.l1MaxSizeMB * 1024 * 1024 : undefined;
26048
26213
  fileCacheL2Bytes = fileConfig.cache?.l2MaxSizeMB ? fileConfig.cache.l2MaxSizeMB * 1024 * 1024 : undefined;
26214
+ resolvedDataDir = getGlobalDataDir();
26049
26215
  defaultConfig = {
26050
26216
  name: "massa-ai-server",
26051
26217
  version: "1.0.0",
26052
- dataDir: getGlobalDataDir(),
26218
+ dataDir: resolvedDataDir,
26053
26219
  cache: {
26054
26220
  l1: {
26055
26221
  maxSize: envNum("L1_CACHE_MAX_SIZE", fileCacheL1Bytes ?? 100 * 1024 * 1024),
@@ -26173,8 +26339,24 @@ var init_config = __esm(() => {
26173
26339
  logging: {
26174
26340
  level: process.env.LOG_LEVEL || fileConfig.logging?.level || "info",
26175
26341
  enableMetrics: process.env.ENABLE_METRICS === "true" || process.env.ENABLE_METRICS === undefined && !!fileConfig.logging?.enableMetrics,
26176
- file: process.env.MASSA_AI_LOG_FILE || fileConfig.logging?.file || undefined
26177
- },
26342
+ file: process.env.MASSA_AI_LOG_FILE || fileConfig.logging?.file || path4.join(resolvedDataDir, "logs", "massa-ai.log"),
26343
+ enableFileSink: envBool("MASSA_AI_LOG_ENABLE_FILE_SINK", fileConfig.logging?.enableFileSink ?? true),
26344
+ bufferSize: envNum("MASSA_AI_LOG_BUFFER_SIZE", fileConfig.logging?.bufferSize ?? 2000),
26345
+ maxFileSizeMb: envNum("MASSA_AI_LOG_MAX_FILE_SIZE_MB", fileConfig.logging?.maxFileSizeMb ?? 32),
26346
+ maxFiles: envNum("MASSA_AI_LOG_MAX_FILES", fileConfig.logging?.maxFiles ?? 5)
26347
+ },
26348
+ scheduler: (() => {
26349
+ const fileScheduler = readSchedulerConfig(fileConfig);
26350
+ return {
26351
+ enabled: envBool("MASSA_AI_SCHEDULER_ENABLED", fileScheduler.enabled ?? false),
26352
+ tickMs: envNum("MASSA_AI_SCHEDULER_TICK_MS", fileScheduler.tickMs ?? 60000),
26353
+ maxConcurrent: envNum("MASSA_AI_SCHEDULER_MAX_CONCURRENT", fileScheduler.maxConcurrent ?? 2),
26354
+ jobs: Object.fromEntries(SCHEDULER_JOB_KINDS.map((kind) => [
26355
+ kind,
26356
+ resolveSchedulerJob(kind, fileScheduler.jobs)
26357
+ ]))
26358
+ };
26359
+ })(),
26178
26360
  synapse: {
26179
26361
  enabled: process.env.SYNAPSE_ENABLED !== "false",
26180
26362
  inhibition: {
@@ -26326,13 +26508,175 @@ var init_types2 = __esm(() => {
26326
26508
  // ../../packages/shared/dist/types/interfaces.js
26327
26509
  var init_interfaces = () => {};
26328
26510
 
26329
- // ../../packages/shared/dist/utils/logger.js
26511
+ // ../../packages/shared/dist/utils/log-sink.js
26330
26512
  import fs2 from "fs";
26513
+ import path5 from "path";
26514
+ function getState(filePath) {
26515
+ let state = pathState.get(filePath);
26516
+ if (!state) {
26517
+ state = { trackedSize: 0, deltaSinceStat: 0, primed: false };
26518
+ pathState.set(filePath, state);
26519
+ }
26520
+ return state;
26521
+ }
26522
+ function ensureDir(filePath) {
26523
+ const dir = path5.dirname(filePath);
26524
+ if (ensuredDirs.has(dir))
26525
+ return;
26526
+ fs2.mkdirSync(dir, { recursive: true });
26527
+ ensuredDirs.add(dir);
26528
+ }
26529
+ function restat(filePath, state) {
26530
+ try {
26531
+ state.trackedSize = fs2.statSync(filePath).size;
26532
+ } catch {
26533
+ state.trackedSize = 0;
26534
+ }
26535
+ state.deltaSinceStat = 0;
26536
+ state.primed = true;
26537
+ }
26538
+ function rotate(filePath, maxFiles) {
26539
+ if (maxFiles <= 0) {
26540
+ if (fs2.existsSync(filePath))
26541
+ fs2.unlinkSync(filePath);
26542
+ return;
26543
+ }
26544
+ const oldest = `${filePath}.${maxFiles}`;
26545
+ if (fs2.existsSync(oldest))
26546
+ fs2.unlinkSync(oldest);
26547
+ for (let n = maxFiles - 1;n >= 1; n--) {
26548
+ const src = `${filePath}.${n}`;
26549
+ const dest = `${filePath}.${n + 1}`;
26550
+ if (fs2.existsSync(src))
26551
+ fs2.renameSync(src, dest);
26552
+ }
26553
+ if (fs2.existsSync(filePath))
26554
+ fs2.renameSync(filePath, `${filePath}.1`);
26555
+ }
26556
+ function appendLine(opts, line) {
26557
+ const { filePath, maxFileSizeBytes, maxFiles } = opts;
26558
+ try {
26559
+ ensureDir(filePath);
26560
+ const state = getState(filePath);
26561
+ const lineBytes = Buffer.byteLength(line + `
26562
+ `, "utf8");
26563
+ if (!state.primed || state.deltaSinceStat >= STAT_DELTA_THRESHOLD_BYTES || state.trackedSize + state.deltaSinceStat >= maxFileSizeBytes) {
26564
+ restat(filePath, state);
26565
+ }
26566
+ if (maxFileSizeBytes > 0 && state.trackedSize >= maxFileSizeBytes) {
26567
+ rotate(filePath, maxFiles);
26568
+ state.trackedSize = 0;
26569
+ state.deltaSinceStat = 0;
26570
+ state.primed = true;
26571
+ }
26572
+ fs2.appendFileSync(filePath, line + `
26573
+ `);
26574
+ state.trackedSize += lineBytes;
26575
+ state.deltaSinceStat += lineBytes;
26576
+ } catch (err) {
26577
+ lastError = err;
26578
+ }
26579
+ }
26580
+ var STAT_DELTA_THRESHOLD_BYTES, ensuredDirs, pathState, lastError;
26581
+ var init_log_sink = __esm(() => {
26582
+ STAT_DELTA_THRESHOLD_BYTES = 1024 * 1024;
26583
+ ensuredDirs = new Set;
26584
+ pathState = new Map;
26585
+ });
26586
+
26587
+ // ../../packages/shared/dist/utils/log-buffer.js
26588
+ class LogBufferImpl {
26589
+ capacity = DEFAULT_CAPACITY;
26590
+ entries = [];
26591
+ subscribers = new Set;
26592
+ nextSeq = 0;
26593
+ dispatching = false;
26594
+ pending = [];
26595
+ push(entry) {
26596
+ if (this.dispatching) {
26597
+ this.pending.push(entry);
26598
+ return;
26599
+ }
26600
+ this.dispatching = true;
26601
+ try {
26602
+ this.pushOne(entry);
26603
+ while (this.pending.length > 0) {
26604
+ const next = this.pending.shift();
26605
+ this.pushOne(next);
26606
+ }
26607
+ } finally {
26608
+ this.dispatching = false;
26609
+ }
26610
+ }
26611
+ pushOne(entry) {
26612
+ const full = { ...entry, seq: this.nextSeq++ };
26613
+ this.entries.push(full);
26614
+ while (this.entries.length > this.capacity) {
26615
+ this.entries.shift();
26616
+ }
26617
+ for (const fn of this.subscribers) {
26618
+ try {
26619
+ fn(full);
26620
+ } catch {}
26621
+ }
26622
+ }
26623
+ snapshot(opts) {
26624
+ const from = opts?.from;
26625
+ const to = opts?.to;
26626
+ const level = opts?.level;
26627
+ const q = opts?.q?.toLowerCase();
26628
+ const result = [];
26629
+ for (let i = this.entries.length - 1;i >= 0; i--) {
26630
+ const e = this.entries[i];
26631
+ if (from !== undefined && e.seq < from)
26632
+ continue;
26633
+ if (to !== undefined && e.seq > to)
26634
+ continue;
26635
+ if (level !== undefined && e.level !== level)
26636
+ continue;
26637
+ if (q !== undefined && !e.message.toLowerCase().includes(q))
26638
+ continue;
26639
+ result.push(e);
26640
+ }
26641
+ return result;
26642
+ }
26643
+ subscribe(fn) {
26644
+ this.subscribers.add(fn);
26645
+ return () => {
26646
+ this.subscribers.delete(fn);
26647
+ };
26648
+ }
26649
+ setCapacity(n) {
26650
+ this.capacity = n > 0 ? n : 0;
26651
+ while (this.entries.length > this.capacity) {
26652
+ this.entries.shift();
26653
+ }
26654
+ }
26655
+ size() {
26656
+ return this.entries.length;
26657
+ }
26658
+ _resetForTesting() {
26659
+ this.entries = [];
26660
+ this.subscribers.clear();
26661
+ this.nextSeq = 0;
26662
+ this.dispatching = false;
26663
+ this.pending = [];
26664
+ this.capacity = DEFAULT_CAPACITY;
26665
+ }
26666
+ }
26667
+ var DEFAULT_CAPACITY = 2000, logBuffer;
26668
+ var init_log_buffer = __esm(() => {
26669
+ logBuffer = new LogBufferImpl;
26670
+ });
26331
26671
 
26672
+ // ../../packages/shared/dist/utils/logger.js
26332
26673
  class Logger {
26333
26674
  _level;
26334
26675
  _enableMetrics;
26335
26676
  _logFilePath;
26677
+ _enableFileSink;
26678
+ _maxFileSizeBytes;
26679
+ _maxFiles;
26336
26680
  _initialized = false;
26337
26681
  constructor() {}
26338
26682
  ensureInitialized() {
@@ -26342,10 +26686,18 @@ class Logger {
26342
26686
  this._level = this.parseLogLevel(loggingConfig.level);
26343
26687
  this._enableMetrics = loggingConfig.enableMetrics;
26344
26688
  this._logFilePath = loggingConfig.file;
26689
+ this._enableFileSink = loggingConfig.enableFileSink;
26690
+ this._maxFileSizeBytes = loggingConfig.maxFileSizeMb * 1024 * 1024;
26691
+ this._maxFiles = loggingConfig.maxFiles;
26692
+ logBuffer.setCapacity(loggingConfig.bufferSize);
26345
26693
  } catch {
26346
26694
  this._level = LogLevel.INFO;
26347
26695
  this._enableMetrics = false;
26348
26696
  this._logFilePath = undefined;
26697
+ this._enableFileSink = false;
26698
+ this._maxFileSizeBytes = 32 * 1024 * 1024;
26699
+ this._maxFiles = 5;
26700
+ logBuffer.setCapacity(2000);
26349
26701
  }
26350
26702
  this._initialized = true;
26351
26703
  }
@@ -26362,6 +26714,18 @@ class Logger {
26362
26714
  this.ensureInitialized();
26363
26715
  return this._logFilePath;
26364
26716
  }
26717
+ get enableFileSink() {
26718
+ this.ensureInitialized();
26719
+ return this._enableFileSink;
26720
+ }
26721
+ get maxFileSizeBytes() {
26722
+ this.ensureInitialized();
26723
+ return this._maxFileSizeBytes;
26724
+ }
26725
+ get maxFiles() {
26726
+ this.ensureInitialized();
26727
+ return this._maxFiles;
26728
+ }
26365
26729
  parseLogLevel(level) {
26366
26730
  const levels = {
26367
26731
  debug: LogLevel.DEBUG,
@@ -26374,34 +26738,40 @@ class Logger {
26374
26738
  shouldLog(level) {
26375
26739
  return level >= this.level;
26376
26740
  }
26377
- formatMessage(level, message, meta3) {
26378
- const timestamp = new Date().toISOString();
26741
+ formatMessage(level, message, meta3, timestamp = new Date().toISOString()) {
26379
26742
  const metaStr = meta3 ? ` ${JSON.stringify(meta3)}` : "";
26380
26743
  return `[${timestamp}] [${level}] ${message}${metaStr}`;
26381
26744
  }
26382
- write(message, _level) {
26383
- console.error(message);
26384
- const filePath = this.logFilePath;
26385
- if (filePath) {
26386
- try {
26387
- fs2.appendFileSync(filePath, message + `
26388
- `);
26389
- } catch {}
26745
+ emit(level, message, meta3) {
26746
+ const ts = new Date().toISOString();
26747
+ const line = this.formatMessage(LOG_LEVEL_LABELS[level], message, meta3, ts);
26748
+ console.error(line);
26749
+ if (this.enableFileSink) {
26750
+ const filePath = this.logFilePath;
26751
+ if (filePath) {
26752
+ appendLine({ filePath, maxFileSizeBytes: this.maxFileSizeBytes, maxFiles: this.maxFiles }, line);
26753
+ }
26390
26754
  }
26755
+ logBuffer.push({
26756
+ ts,
26757
+ level: LOG_LEVEL_BUFFER_TAGS[level],
26758
+ message,
26759
+ ...meta3 ? { meta: meta3 } : {}
26760
+ });
26391
26761
  }
26392
26762
  debug(message, meta3) {
26393
26763
  if (this.shouldLog(LogLevel.DEBUG)) {
26394
- this.write(this.formatMessage("DEBUG", message, meta3), LogLevel.DEBUG);
26764
+ this.emit(LogLevel.DEBUG, message, meta3);
26395
26765
  }
26396
26766
  }
26397
26767
  info(message, meta3) {
26398
26768
  if (this.shouldLog(LogLevel.INFO)) {
26399
- this.write(this.formatMessage("INFO", message, meta3), LogLevel.INFO);
26769
+ this.emit(LogLevel.INFO, message, meta3);
26400
26770
  }
26401
26771
  }
26402
26772
  warn(message, meta3) {
26403
26773
  if (this.shouldLog(LogLevel.WARN)) {
26404
- this.write(this.formatMessage("WARN", message, meta3), LogLevel.WARN);
26774
+ this.emit(LogLevel.WARN, message, meta3);
26405
26775
  }
26406
26776
  }
26407
26777
  error(message, error51, meta3) {
@@ -26414,7 +26784,7 @@ class Logger {
26414
26784
  stack: error51.stack
26415
26785
  }
26416
26786
  } : meta3;
26417
- this.write(this.formatMessage("ERROR", message, errorMeta), LogLevel.ERROR);
26787
+ this.emit(LogLevel.ERROR, message, errorMeta);
26418
26788
  }
26419
26789
  }
26420
26790
  metric(name, value, unit) {
@@ -26443,15 +26813,29 @@ class Logger {
26443
26813
  return childLogger;
26444
26814
  }
26445
26815
  }
26446
- var LogLevel, logger;
26816
+ var LogLevel, LOG_LEVEL_LABELS, LOG_LEVEL_BUFFER_TAGS, logger;
26447
26817
  var init_logger = __esm(() => {
26448
26818
  init_config();
26819
+ init_log_sink();
26820
+ init_log_buffer();
26449
26821
  (function(LogLevel2) {
26450
26822
  LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
26451
26823
  LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
26452
26824
  LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
26453
26825
  LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
26454
26826
  })(LogLevel || (LogLevel = {}));
26827
+ LOG_LEVEL_LABELS = {
26828
+ [LogLevel.DEBUG]: "DEBUG",
26829
+ [LogLevel.INFO]: "INFO",
26830
+ [LogLevel.WARN]: "WARN",
26831
+ [LogLevel.ERROR]: "ERROR"
26832
+ };
26833
+ LOG_LEVEL_BUFFER_TAGS = {
26834
+ [LogLevel.DEBUG]: "debug",
26835
+ [LogLevel.INFO]: "info",
26836
+ [LogLevel.WARN]: "warn",
26837
+ [LogLevel.ERROR]: "error"
26838
+ };
26455
26839
  logger = new Logger;
26456
26840
  });
26457
26841
 
@@ -26734,6 +27118,8 @@ var init_rate_limiter = __esm(() => {
26734
27118
  // ../../packages/shared/dist/utils/index.js
26735
27119
  var init_utils = __esm(() => {
26736
27120
  init_logger();
27121
+ init_log_buffer();
27122
+ init_log_sink();
26737
27123
  init_sanitizer();
26738
27124
  init_metrics();
26739
27125
  init_rate_limiter();
@@ -26741,7 +27127,7 @@ var init_utils = __esm(() => {
26741
27127
 
26742
27128
  // ../../packages/shared/dist/profile-switch/hosts.js
26743
27129
  import os3 from "os";
26744
- import path5 from "path";
27130
+ import path6 from "path";
26745
27131
  function isHost(v) {
26746
27132
  return typeof v === "string" && HOSTS.includes(v);
26747
27133
  }
@@ -26752,7 +27138,7 @@ function fileLayout(host, activeDir, activeGlob, variantsRoot) {
26752
27138
  activeDir,
26753
27139
  activeGlob,
26754
27140
  variantsRoot,
26755
- variantDir: (profile) => path5.join(variantsRoot, profile)
27141
+ variantDir: (profile) => path6.join(variantsRoot, profile)
26756
27142
  };
26757
27143
  }
26758
27144
  function resolveHostLayout(host, opts = {}) {
@@ -26762,25 +27148,37 @@ function resolveHostLayout(host, opts = {}) {
26762
27148
  case "cursor":
26763
27149
  return { host, route: "skip", reason: CURSOR_SKIP_REASON };
26764
27150
  case "claude": {
26765
- const root = override ?? path5.join(targetHome, ".claude");
26766
- return fileLayout(host, path5.join(root, "agents"), "massa-ai-*.md", path5.join(root, "massa-ai", "agent-profiles"));
27151
+ const marketplaceRoot = opts.marketplaceRoot?.claude;
27152
+ if (override === undefined && marketplaceRoot !== undefined) {
27153
+ return fileLayout(host, path6.join(marketplaceRoot, "agents"), "massa-ai-*.md", path6.join(marketplaceRoot, "agent-profiles"));
27154
+ }
27155
+ const root = override ?? path6.join(targetHome, ".claude");
27156
+ return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.md", path6.join(root, "massa-ai", "agent-profiles"));
26767
27157
  }
26768
27158
  case "codex": {
26769
- const root = override ?? path5.join(targetHome, ".codex");
26770
- return fileLayout(host, path5.join(root, "agents"), "massa-ai-*.toml", path5.join(root, "massa-ai", "agent-profiles"));
27159
+ const root = override ?? path6.join(targetHome, ".codex");
27160
+ return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.toml", path6.join(root, "massa-ai", "agent-profiles"));
26771
27161
  }
26772
27162
  case "opencode": {
26773
- const root = override ?? path5.join(targetHome, ".config", "opencode");
26774
- const pluginsDir = path5.join(root, "plugins", "massa-ai");
26775
- return fileLayout(host, path5.join(root, "agents"), "massa-ai-*.md", path5.join(pluginsDir, "agent-profiles"));
27163
+ const root = override ?? path6.join(targetHome, ".config", "opencode");
27164
+ const pluginsDir = path6.join(root, "plugins", "massa-ai");
27165
+ return fileLayout(host, path6.join(root, "agents"), "massa-ai-*.md", path6.join(pluginsDir, "agent-profiles"));
26776
27166
  }
26777
27167
  }
26778
27168
  }
26779
- function detectRoute(platform) {
27169
+ function detectRoute(platform, host) {
26780
27170
  const route = platform?.installRoute;
26781
27171
  if (route === "file")
26782
27172
  return { kind: "proceed" };
26783
27173
  if (route === "marketplace") {
27174
+ if (host === "claude")
27175
+ return { kind: "proceed" };
27176
+ if (host === "codex") {
27177
+ return {
27178
+ kind: "refuse",
27179
+ 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."
27180
+ };
27181
+ }
26784
27182
  return {
26785
27183
  kind: "refuse",
26786
27184
  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."
@@ -26798,7 +27196,7 @@ var init_hosts = __esm(() => {
26798
27196
 
26799
27197
  // ../../packages/shared/dist/profile-switch/state.js
26800
27198
  import fs3 from "fs";
26801
- import path6 from "path";
27199
+ import path7 from "path";
26802
27200
  function namedError(name, message) {
26803
27201
  const err = new InstallStateError(message);
26804
27202
  err.name = name;
@@ -26844,7 +27242,7 @@ function writeInstallState(filePath, state) {
26844
27242
  const text = `${JSON.stringify(validated, null, 2)}
26845
27243
  `;
26846
27244
  try {
26847
- fs3.mkdirSync(path6.dirname(filePath), { recursive: true });
27245
+ fs3.mkdirSync(path7.dirname(filePath), { recursive: true });
26848
27246
  fs3.writeFileSync(filePath, text);
26849
27247
  } catch (err) {
26850
27248
  throw UnwritableInstallStateError(filePath, err.message);
@@ -26873,7 +27271,7 @@ var init_state = __esm(() => {
26873
27271
 
26874
27272
  // ../../packages/shared/dist/profile-switch/lock.js
26875
27273
  import fs4 from "fs";
26876
- import path7 from "path";
27274
+ import path8 from "path";
26877
27275
  import os4 from "os";
26878
27276
  import crypto3 from "crypto";
26879
27277
  import { execFileSync } from "child_process";
@@ -26905,7 +27303,7 @@ function releaseIfOwned(lockDir, ownerPath, token) {
26905
27303
  }
26906
27304
  function acquireLock(stateFilePath, options = {}) {
26907
27305
  const lockDir = `${stateFilePath}.switch.lock`;
26908
- const ownerPath = path7.join(lockDir, "owner.json");
27306
+ const ownerPath = path8.join(lockDir, "owner.json");
26909
27307
  const clock = options.clock ?? DEFAULT_CLOCK;
26910
27308
  const identity = options.identity ?? DEFAULT_IDENTITY;
26911
27309
  const staleAfterMs = options.staleAfterMs ?? DEFAULT_STALE_AFTER_MS;
@@ -26925,7 +27323,7 @@ function acquireLock(stateFilePath, options = {}) {
26925
27323
  token,
26926
27324
  timestamp: clock.now()
26927
27325
  };
26928
- fs4.mkdirSync(path7.dirname(ownerPath), { recursive: true });
27326
+ fs4.mkdirSync(path8.dirname(ownerPath), { recursive: true });
26929
27327
  fs4.writeFileSync(ownerPath, JSON.stringify(record3));
26930
27328
  return { lockDir, release: () => releaseIfOwned(lockDir, ownerPath, token) };
26931
27329
  };
@@ -26978,10 +27376,59 @@ var init_lock = __esm(() => {
26978
27376
  };
26979
27377
  });
26980
27378
 
26981
- // ../../packages/shared/dist/profile-switch/engine.js
27379
+ // ../../packages/shared/dist/profile-switch/claude-marketplace.js
26982
27380
  import fs5 from "fs";
26983
- import path8 from "path";
26984
27381
  import os5 from "os";
27382
+ import path9 from "path";
27383
+ function selectRecord(records) {
27384
+ if (records.length === 0)
27385
+ return;
27386
+ const userScoped = records.filter((r) => r.scope === "user");
27387
+ const pool = userScoped.length > 0 ? userScoped : records;
27388
+ let best;
27389
+ let bestTime = -Infinity;
27390
+ for (const record3 of pool) {
27391
+ const parsed = record3.lastUpdated ? Date.parse(record3.lastUpdated) : NaN;
27392
+ if (Number.isFinite(parsed) && parsed >= bestTime) {
27393
+ best = record3;
27394
+ bestTime = parsed;
27395
+ }
27396
+ }
27397
+ return best ?? pool[pool.length - 1];
27398
+ }
27399
+ function resolveClaudeMarketplaceRoot(opts = {}) {
27400
+ const targetHome = opts.targetHome ?? os5.homedir();
27401
+ const pluginKey = opts.pluginKey ?? DEFAULT_PLUGIN_KEY;
27402
+ const registryPath = path9.join(targetHome, ".claude", "plugins", "installed_plugins.json");
27403
+ let records;
27404
+ try {
27405
+ const raw2 = fs5.readFileSync(registryPath, "utf8");
27406
+ const parsed = JSON.parse(raw2);
27407
+ records = parsed?.plugins?.[pluginKey];
27408
+ } catch {
27409
+ return null;
27410
+ }
27411
+ if (!Array.isArray(records) || records.length === 0)
27412
+ return null;
27413
+ const selected = selectRecord(records);
27414
+ const installPath = selected?.installPath;
27415
+ if (!installPath)
27416
+ return null;
27417
+ try {
27418
+ if (!fs5.existsSync(installPath))
27419
+ return null;
27420
+ } catch {
27421
+ return null;
27422
+ }
27423
+ return installPath;
27424
+ }
27425
+ var DEFAULT_PLUGIN_KEY = "massa-ai@massa-ai";
27426
+ var init_claude_marketplace = () => {};
27427
+
27428
+ // ../../packages/shared/dist/profile-switch/engine.js
27429
+ import fs6 from "fs";
27430
+ import path10 from "path";
27431
+ import os6 from "os";
26985
27432
  import crypto4 from "crypto";
26986
27433
  function namedError3(name, message) {
26987
27434
  const err = new SwitchEngineError(message);
@@ -26989,19 +27436,39 @@ function namedError3(name, message) {
26989
27436
  return err;
26990
27437
  }
26991
27438
  function defaultStatePath(targetHome) {
26992
- return path8.join(targetHome, ".config", "massa-ai", "install-state.json");
27439
+ return path10.join(targetHome, ".config", "massa-ai", "install-state.json");
26993
27440
  }
26994
27441
  function resolveCommon(opts) {
26995
- const targetHome = opts.targetHome ?? os5.homedir();
27442
+ const targetHome = opts.targetHome ?? os6.homedir();
26996
27443
  const stateFilePath = opts.stateFilePath ?? defaultStatePath(targetHome);
26997
27444
  return { targetHome, stateFilePath };
26998
27445
  }
27446
+ function marketplaceRoots(targetHome, state) {
27447
+ return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
27448
+ }
27449
+ function claudeMarketplaceUnresolvedReason(targetHome) {
27450
+ const registryPath = path10.join(targetHome, ".claude", "plugins", "installed_plugins.json");
27451
+ 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";
27452
+ }
26999
27453
  function listProfiles(opts = {}) {
27000
27454
  const { targetHome, stateFilePath } = resolveCommon(opts);
27001
27455
  const state = readInstallState(stateFilePath);
27456
+ const roots = marketplaceRoots(targetHome, state);
27002
27457
  const universe = opts.hosts ?? HOSTS;
27003
27458
  const hosts = universe.map((host) => {
27004
- const layout = resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot });
27459
+ if (host === "claude" && state.platforms.claude?.installRoute === "marketplace" && roots.claude === undefined) {
27460
+ const platform2 = state.platforms.claude;
27461
+ return {
27462
+ host,
27463
+ installed: false,
27464
+ skipped: false,
27465
+ skipReason: null,
27466
+ activeProfile: platform2.modelProfile?.profile ?? opts.hostDefaults?.[host] ?? "balanced",
27467
+ bundleVersion: platform2.plugin?.version ?? null,
27468
+ availableProfiles: []
27469
+ };
27470
+ }
27471
+ const layout = resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot, marketplaceRoot: roots });
27005
27472
  if (layout.route === "skip") {
27006
27473
  return {
27007
27474
  host,
@@ -27013,7 +27480,7 @@ function listProfiles(opts = {}) {
27013
27480
  availableProfiles: []
27014
27481
  };
27015
27482
  }
27016
- const installed = fs5.existsSync(layout.activeDir);
27483
+ const installed = fs6.existsSync(layout.activeDir);
27017
27484
  const availableProfiles = listVariantProfiles(layout);
27018
27485
  const platform = state.platforms[host];
27019
27486
  return {
@@ -27029,9 +27496,9 @@ function listProfiles(opts = {}) {
27029
27496
  return { hosts };
27030
27497
  }
27031
27498
  function listVariantProfiles(layout) {
27032
- if (!fs5.existsSync(layout.variantsRoot))
27499
+ if (!fs6.existsSync(layout.variantsRoot))
27033
27500
  return [];
27034
- return fs5.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
27501
+ return fs6.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
27035
27502
  }
27036
27503
  function matchesGlob(filename, glob) {
27037
27504
  const starIdx = glob.indexOf("*");
@@ -27042,50 +27509,50 @@ function matchesGlob(filename, glob) {
27042
27509
  return filename.length >= prefix.length + suffix.length && filename.startsWith(prefix) && filename.endsWith(suffix);
27043
27510
  }
27044
27511
  function assertStateWritable(stateFilePath) {
27045
- const dir = path8.dirname(stateFilePath);
27512
+ const dir = path10.dirname(stateFilePath);
27046
27513
  try {
27047
- fs5.mkdirSync(dir, { recursive: true });
27514
+ fs6.mkdirSync(dir, { recursive: true });
27048
27515
  } catch (err) {
27049
27516
  throw UnwritableInstallStateError(stateFilePath, err.message);
27050
27517
  }
27051
- const checkPath = fs5.existsSync(stateFilePath) ? stateFilePath : dir;
27518
+ const checkPath = fs6.existsSync(stateFilePath) ? stateFilePath : dir;
27052
27519
  try {
27053
- fs5.accessSync(checkPath, fs5.constants.W_OK);
27520
+ fs6.accessSync(checkPath, fs6.constants.W_OK);
27054
27521
  } catch (err) {
27055
27522
  throw UnwritableInstallStateError(stateFilePath, err.message);
27056
27523
  }
27057
27524
  }
27058
27525
  function copyFileRouteVariant(layout, variantDir) {
27059
- fs5.mkdirSync(layout.activeDir, { recursive: true });
27526
+ fs6.mkdirSync(layout.activeDir, { recursive: true });
27060
27527
  let changed = 0;
27061
- for (const entry of fs5.readdirSync(variantDir, { withFileTypes: true })) {
27528
+ for (const entry of fs6.readdirSync(variantDir, { withFileTypes: true })) {
27062
27529
  if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
27063
27530
  continue;
27064
- fs5.copyFileSync(path8.join(variantDir, entry.name), path8.join(layout.activeDir, entry.name));
27531
+ fs6.copyFileSync(path10.join(variantDir, entry.name), path10.join(layout.activeDir, entry.name));
27065
27532
  changed++;
27066
27533
  }
27067
27534
  return changed;
27068
27535
  }
27069
27536
  function repointOpencodeVariant(layout, variantDir) {
27070
- fs5.mkdirSync(layout.activeDir, { recursive: true });
27537
+ fs6.mkdirSync(layout.activeDir, { recursive: true });
27071
27538
  let changed = 0;
27072
- for (const entry of fs5.readdirSync(variantDir, { withFileTypes: true })) {
27539
+ for (const entry of fs6.readdirSync(variantDir, { withFileTypes: true })) {
27073
27540
  if (!entry.isFile() || !matchesGlob(entry.name, layout.activeGlob))
27074
27541
  continue;
27075
- const dest = path8.join(layout.activeDir, entry.name);
27076
- const target = path8.resolve(path8.join(variantDir, entry.name));
27542
+ const dest = path10.join(layout.activeDir, entry.name);
27543
+ const target = path10.resolve(path10.join(variantDir, entry.name));
27077
27544
  let destExists = true;
27078
27545
  let destIsSymlink = false;
27079
27546
  try {
27080
- destIsSymlink = fs5.lstatSync(dest).isSymbolicLink();
27547
+ destIsSymlink = fs6.lstatSync(dest).isSymbolicLink();
27081
27548
  } catch {
27082
27549
  destExists = false;
27083
27550
  }
27084
27551
  if (destExists && !destIsSymlink)
27085
27552
  continue;
27086
27553
  const tmp = `${dest}.massa-ai-switch.${crypto4.randomUUID()}`;
27087
- fs5.symlinkSync(target, tmp);
27088
- fs5.renameSync(tmp, dest);
27554
+ fs6.symlinkSync(target, tmp);
27555
+ fs6.renameSync(tmp, dest);
27089
27556
  changed++;
27090
27557
  }
27091
27558
  return changed;
@@ -27101,19 +27568,37 @@ function switchProfile(opts) {
27101
27568
  const state = readInstallState(stateFilePath);
27102
27569
  if (!dryRun)
27103
27570
  assertStateWritable(stateFilePath);
27104
- const layouts = universe.map((host) => ({ host, layout: resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot }) }));
27105
- const skipRows = layouts.filter((l) => l.layout.route === "skip").map((l) => ({ host: l.host, status: "skipped", reason: l.layout.reason }));
27571
+ const roots = marketplaceRoots(targetHome, state);
27572
+ const unresolvedRows = [];
27573
+ const resolvableUniverse = universe.filter((host) => {
27574
+ if (host !== "claude")
27575
+ return true;
27576
+ if (state.platforms.claude?.installRoute !== "marketplace")
27577
+ return true;
27578
+ if (roots.claude !== undefined)
27579
+ return true;
27580
+ unresolvedRows.push({ host, status: "failed", reason: claudeMarketplaceUnresolvedReason(targetHome) });
27581
+ return false;
27582
+ });
27583
+ const layouts = resolvableUniverse.map((host) => ({
27584
+ host,
27585
+ layout: resolveHostLayout(host, { targetHome, projectRoot: opts.projectRoot, marketplaceRoot: roots })
27586
+ }));
27587
+ const skipRows = [
27588
+ ...unresolvedRows,
27589
+ ...layouts.filter((l) => l.layout.route === "skip").map((l) => ({ host: l.host, status: "skipped", reason: l.layout.reason }))
27590
+ ];
27106
27591
  const fileHosts = layouts.filter((l) => l.layout.route === "files");
27107
27592
  if (fileHosts.length === 0) {
27108
27593
  return { profile: opts.profile, dryRun, hosts: orderRows(universe, skipRows), restartRequired: false };
27109
27594
  }
27110
- const installedFileHosts = fileHosts.filter((h) => fs5.existsSync(h.layout.activeDir));
27595
+ const installedFileHosts = fileHosts.filter((h) => fs6.existsSync(h.layout.activeDir));
27111
27596
  if (installedFileHosts.length === 0)
27112
27597
  throw NoHostsDetectedError();
27113
27598
  const withAvailability = fileHosts.map((h) => {
27114
- const variantsRootExists = fs5.existsSync(h.layout.variantsRoot);
27599
+ const variantsRootExists = fs6.existsSync(h.layout.variantsRoot);
27115
27600
  const variantDir = h.layout.variantDir(opts.profile);
27116
- const available = variantsRootExists && fs5.existsSync(variantDir) && fs5.statSync(variantDir).isDirectory();
27601
+ const available = variantsRootExists && fs6.existsSync(variantDir) && fs6.statSync(variantDir).isDirectory();
27117
27602
  return { ...h, variantsRootExists, variantDir, available };
27118
27603
  });
27119
27604
  if (!withAvailability.some((h) => h.available)) {
@@ -27143,7 +27628,7 @@ function switchProfile(opts) {
27143
27628
  });
27144
27629
  continue;
27145
27630
  }
27146
- const route = detectRoute(state.platforms[h.host]);
27631
+ const route = detectRoute(state.platforms[h.host], h.host);
27147
27632
  if (route.kind === "refuse") {
27148
27633
  rows.push({ host: h.host, status: "failed", reason: route.reason });
27149
27634
  continue;
@@ -27178,6 +27663,7 @@ var init_engine = __esm(() => {
27178
27663
  init_hosts();
27179
27664
  init_state();
27180
27665
  init_lock();
27666
+ init_claude_marketplace();
27181
27667
  SwitchEngineError = class SwitchEngineError extends Error {
27182
27668
  constructor(message) {
27183
27669
  super(message);
@@ -27192,18 +27678,25 @@ function reportSucceeded(report) {
27192
27678
  }
27193
27679
 
27194
27680
  // ../../packages/shared/dist/profile-switch/variant-sync.js
27195
- import fs6 from "fs";
27196
- import path9 from "path";
27681
+ import fs7 from "fs";
27682
+ import path11 from "path";
27683
+ import os7 from "os";
27197
27684
  import crypto5 from "crypto";
27685
+ function defaultStatePath2(targetHome) {
27686
+ return path11.join(targetHome, ".config", "massa-ai", "install-state.json");
27687
+ }
27688
+ function marketplaceRoots2(targetHome, state) {
27689
+ return state.platforms.claude?.installRoute === "marketplace" ? { claude: resolveClaudeMarketplaceRoot({ targetHome }) ?? undefined } : {};
27690
+ }
27198
27691
  function writeFileIntoDirAtomically(destDir, destName, content) {
27199
27692
  const unique = `${process.pid}.${++tempFileCounter2}.${crypto5.randomBytes(6).toString("hex")}`;
27200
- const tempFile = path9.join(destDir, `.${destName}.${unique}.tmp`);
27693
+ const tempFile = path11.join(destDir, `.${destName}.${unique}.tmp`);
27201
27694
  try {
27202
- fs6.writeFileSync(tempFile, content);
27203
- fs6.renameSync(tempFile, path9.join(destDir, destName));
27695
+ fs7.writeFileSync(tempFile, content);
27696
+ fs7.renameSync(tempFile, path11.join(destDir, destName));
27204
27697
  } catch (error51) {
27205
27698
  try {
27206
- fs6.unlinkSync(tempFile);
27699
+ fs7.unlinkSync(tempFile);
27207
27700
  } catch {}
27208
27701
  throw error51;
27209
27702
  }
@@ -27211,20 +27704,20 @@ function writeFileIntoDirAtomically(destDir, destName, content) {
27211
27704
  function isSafeDirName(name) {
27212
27705
  if (name === "." || name === "..")
27213
27706
  return false;
27214
- if (name.includes("/") || name.includes("\\") || name.includes(path9.sep))
27707
+ if (name.includes("/") || name.includes("\\") || name.includes(path11.sep))
27215
27708
  return false;
27216
- return path9.basename(name) === name;
27709
+ return path11.basename(name) === name;
27217
27710
  }
27218
- function syncHost(host, sourceRoot, targetHome) {
27219
- const layout = resolveHostLayout(host, { targetHome });
27711
+ function syncHost(host, sourceRoot, targetHome, marketplaceRoot) {
27712
+ const layout = resolveHostLayout(host, { targetHome, marketplaceRoot });
27220
27713
  if (layout.route === "skip") {
27221
27714
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: layout.reason };
27222
27715
  }
27223
- const srcDir = path9.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
27224
- if (!fs6.existsSync(srcDir) || !fs6.statSync(srcDir).isDirectory()) {
27716
+ const srcDir = path11.join(sourceRoot, "apps", `${host}-plugin`, "agent-profiles");
27717
+ if (!fs7.existsSync(srcDir) || !fs7.statSync(srcDir).isDirectory()) {
27225
27718
  return { host, status: "skipped", profiles: [], retained: [], files: 0, reason: "no generated variants for this host" };
27226
27719
  }
27227
- if (!fs6.existsSync(layout.variantsRoot)) {
27720
+ if (!fs7.existsSync(layout.variantsRoot)) {
27228
27721
  return {
27229
27722
  host,
27230
27723
  status: "skipped",
@@ -27236,24 +27729,24 @@ function syncHost(host, sourceRoot, targetHome) {
27236
27729
  }
27237
27730
  const profiles = [];
27238
27731
  let files = 0;
27239
- for (const entry of fs6.readdirSync(srcDir, { withFileTypes: true })) {
27732
+ for (const entry of fs7.readdirSync(srcDir, { withFileTypes: true })) {
27240
27733
  if (!entry.isDirectory())
27241
27734
  continue;
27242
27735
  if (!isSafeDirName(entry.name))
27243
27736
  continue;
27244
- const srcProfileDir = path9.join(srcDir, entry.name);
27245
- const destProfileDir = path9.join(layout.variantsRoot, entry.name);
27246
- fs6.mkdirSync(destProfileDir, { recursive: true });
27247
- for (const fileEntry of fs6.readdirSync(srcProfileDir, { withFileTypes: true })) {
27737
+ const srcProfileDir = path11.join(srcDir, entry.name);
27738
+ const destProfileDir = path11.join(layout.variantsRoot, entry.name);
27739
+ fs7.mkdirSync(destProfileDir, { recursive: true });
27740
+ for (const fileEntry of fs7.readdirSync(srcProfileDir, { withFileTypes: true })) {
27248
27741
  if (!fileEntry.isFile())
27249
27742
  continue;
27250
- const content = fs6.readFileSync(path9.join(srcProfileDir, fileEntry.name));
27743
+ const content = fs7.readFileSync(path11.join(srcProfileDir, fileEntry.name));
27251
27744
  writeFileIntoDirAtomically(destProfileDir, fileEntry.name, content);
27252
27745
  files++;
27253
27746
  }
27254
27747
  profiles.push(entry.name);
27255
27748
  }
27256
- const retained = fs6.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
27749
+ const retained = fs7.readdirSync(layout.variantsRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && !profiles.includes(e.name)).map((e) => e.name).sort();
27257
27750
  return { host, status: "synced", profiles: profiles.sort(), retained, files };
27258
27751
  }
27259
27752
  function syncGeneratedVariants(opts) {
@@ -27269,9 +27762,12 @@ function syncGeneratedVariants(opts) {
27269
27762
  }));
27270
27763
  }
27271
27764
  const sourceRoot = opts.sourceRoot;
27765
+ const targetHome = opts.targetHome ?? os7.homedir();
27766
+ const state = readInstallState(defaultStatePath2(targetHome));
27767
+ const roots = marketplaceRoots2(targetHome, state);
27272
27768
  return hosts.map((host) => {
27273
27769
  try {
27274
- return syncHost(host, sourceRoot, opts.targetHome);
27770
+ return syncHost(host, sourceRoot, opts.targetHome, roots);
27275
27771
  } catch (err) {
27276
27772
  return { host, status: "failed", profiles: [], retained: [], files: 0, error: err.message };
27277
27773
  }
@@ -27280,17 +27776,19 @@ function syncGeneratedVariants(opts) {
27280
27776
  var tempFileCounter2 = 0;
27281
27777
  var init_variant_sync = __esm(() => {
27282
27778
  init_hosts();
27779
+ init_state();
27780
+ init_claude_marketplace();
27283
27781
  });
27284
27782
 
27285
27783
  // ../../packages/shared/dist/profile-switch/repo-root.js
27286
- import fs7 from "fs";
27287
- import path10 from "path";
27784
+ import fs8 from "fs";
27785
+ import path12 from "path";
27288
27786
  function findRepoRootWithMarker(startDir, marker, maxLevels) {
27289
27787
  let dir = startDir;
27290
27788
  for (let i = 0;i <= maxLevels; i++) {
27291
- if (fs7.existsSync(path10.join(dir, marker)))
27789
+ if (fs8.existsSync(path12.join(dir, marker)))
27292
27790
  return dir;
27293
- const parent = path10.dirname(dir);
27791
+ const parent = path12.dirname(dir);
27294
27792
  if (parent === dir)
27295
27793
  break;
27296
27794
  dir = parent;
@@ -28830,7 +29328,7 @@ var import_brace_expansion, minimatch = (p, pattern, options = {}) => {
28830
29328
  }, qmarksTestNoExtDot = ([$0]) => {
28831
29329
  const len = $0.length;
28832
29330
  return (f) => f.length === len && f !== "." && f !== "..";
28833
- }, defaultPlatform, path11, sep, GLOBSTAR, qmark2 = "[^/]", star2, twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options), ext = (a, b = {}) => Object.assign({}, a, b), defaults = (def) => {
29331
+ }, defaultPlatform, path13, sep, GLOBSTAR, qmark2 = "[^/]", star2, twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options), ext = (a, b = {}) => Object.assign({}, a, b), defaults = (def) => {
28834
29332
  if (!def || typeof def !== "object" || !Object.keys(def).length) {
28835
29333
  return minimatch;
28836
29334
  }
@@ -28888,11 +29386,11 @@ var init_esm = __esm(() => {
28888
29386
  starRE = /^\*+$/;
28889
29387
  qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
28890
29388
  defaultPlatform = typeof process === "object" && process ? typeof process.env === "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix";
28891
- path11 = {
29389
+ path13 = {
28892
29390
  win32: { sep: "\\" },
28893
29391
  posix: { sep: "/" }
28894
29392
  };
28895
- sep = defaultPlatform === "win32" ? path11.win32.sep : path11.posix.sep;
29393
+ sep = defaultPlatform === "win32" ? path13.win32.sep : path13.posix.sep;
28896
29394
  minimatch.sep = sep;
28897
29395
  GLOBSTAR = Symbol("globstar **");
28898
29396
  minimatch.GLOBSTAR = GLOBSTAR;
@@ -30858,12 +31356,12 @@ var init_esm4 = __esm(() => {
30858
31356
  childrenCache() {
30859
31357
  return this.#children;
30860
31358
  }
30861
- resolve(path12) {
30862
- if (!path12) {
31359
+ resolve(path14) {
31360
+ if (!path14) {
30863
31361
  return this;
30864
31362
  }
30865
- const rootPath = this.getRootString(path12);
30866
- const dir = path12.substring(rootPath.length);
31363
+ const rootPath = this.getRootString(path14);
31364
+ const dir = path14.substring(rootPath.length);
30867
31365
  const dirParts = dir.split(this.splitSep);
30868
31366
  const result = rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
30869
31367
  return result;
@@ -31391,8 +31889,8 @@ var init_esm4 = __esm(() => {
31391
31889
  newChild(name, type = UNKNOWN, opts = {}) {
31392
31890
  return new PathWin32(name, type, this.root, this.roots, this.nocase, this.childrenCache(), opts);
31393
31891
  }
31394
- getRootString(path12) {
31395
- return win32.parse(path12).root;
31892
+ getRootString(path14) {
31893
+ return win32.parse(path14).root;
31396
31894
  }
31397
31895
  getRoot(rootPath) {
31398
31896
  rootPath = uncToDrive(rootPath.toUpperCase());
@@ -31417,8 +31915,8 @@ var init_esm4 = __esm(() => {
31417
31915
  constructor(name, type = UNKNOWN, root, roots, nocase, children, opts) {
31418
31916
  super(name, type, root, roots, nocase, children, opts);
31419
31917
  }
31420
- getRootString(path12) {
31421
- return path12.startsWith("/") ? "/" : "";
31918
+ getRootString(path14) {
31919
+ return path14.startsWith("/") ? "/" : "";
31422
31920
  }
31423
31921
  getRoot(_rootPath) {
31424
31922
  return this.root;
@@ -31437,8 +31935,8 @@ var init_esm4 = __esm(() => {
31437
31935
  #children;
31438
31936
  nocase;
31439
31937
  #fs;
31440
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs8 = defaultFS } = {}) {
31441
- this.#fs = fsFromOption(fs8);
31938
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs9 = defaultFS } = {}) {
31939
+ this.#fs = fsFromOption(fs9);
31442
31940
  if (cwd instanceof URL || cwd.startsWith("file://")) {
31443
31941
  cwd = fileURLToPath(cwd);
31444
31942
  }
@@ -31474,11 +31972,11 @@ var init_esm4 = __esm(() => {
31474
31972
  }
31475
31973
  this.cwd = prev;
31476
31974
  }
31477
- depth(path12 = this.cwd) {
31478
- if (typeof path12 === "string") {
31479
- path12 = this.cwd.resolve(path12);
31975
+ depth(path14 = this.cwd) {
31976
+ if (typeof path14 === "string") {
31977
+ path14 = this.cwd.resolve(path14);
31480
31978
  }
31481
- return path12.depth();
31979
+ return path14.depth();
31482
31980
  }
31483
31981
  childrenCache() {
31484
31982
  return this.#children;
@@ -31894,9 +32392,9 @@ var init_esm4 = __esm(() => {
31894
32392
  process4();
31895
32393
  return results;
31896
32394
  }
31897
- chdir(path12 = this.cwd) {
32395
+ chdir(path14 = this.cwd) {
31898
32396
  const oldCwd = this.cwd;
31899
- this.cwd = typeof path12 === "string" ? this.cwd.resolve(path12) : path12;
32397
+ this.cwd = typeof path14 === "string" ? this.cwd.resolve(path14) : path14;
31900
32398
  this.cwd[setAsCwd](oldCwd);
31901
32399
  }
31902
32400
  };
@@ -31913,8 +32411,8 @@ var init_esm4 = __esm(() => {
31913
32411
  parseRootPath(dir) {
31914
32412
  return win32.parse(dir).root.toUpperCase();
31915
32413
  }
31916
- newRoot(fs8) {
31917
- return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs8 });
32414
+ newRoot(fs9) {
32415
+ return new PathWin32(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs9 });
31918
32416
  }
31919
32417
  isAbsolute(p) {
31920
32418
  return p.startsWith("/") || p.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(p);
@@ -31930,8 +32428,8 @@ var init_esm4 = __esm(() => {
31930
32428
  parseRootPath(_dir) {
31931
32429
  return "/";
31932
32430
  }
31933
- newRoot(fs8) {
31934
- return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs8 });
32431
+ newRoot(fs9) {
32432
+ return new PathPosix(this.rootPath, IFDIR, undefined, this.roots, this.nocase, this.childrenCache(), { fs: fs9 });
31935
32433
  }
31936
32434
  isAbsolute(p) {
31937
32435
  return p.startsWith("/");
@@ -32188,8 +32686,8 @@ class MatchRecord {
32188
32686
  this.store.set(target, current === undefined ? n : n & current);
32189
32687
  }
32190
32688
  entries() {
32191
- return [...this.store.entries()].map(([path12, n]) => [
32192
- path12,
32689
+ return [...this.store.entries()].map(([path14, n]) => [
32690
+ path14,
32193
32691
  !!(n & 2),
32194
32692
  !!(n & 1)
32195
32693
  ]);
@@ -32393,9 +32891,9 @@ class GlobUtil {
32393
32891
  signal;
32394
32892
  maxDepth;
32395
32893
  includeChildMatches;
32396
- constructor(patterns, path12, opts) {
32894
+ constructor(patterns, path14, opts) {
32397
32895
  this.patterns = patterns;
32398
- this.path = path12;
32896
+ this.path = path14;
32399
32897
  this.opts = opts;
32400
32898
  this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/";
32401
32899
  this.includeChildMatches = opts.includeChildMatches !== false;
@@ -32414,11 +32912,11 @@ class GlobUtil {
32414
32912
  });
32415
32913
  }
32416
32914
  }
32417
- #ignored(path12) {
32418
- return this.seen.has(path12) || !!this.#ignore?.ignored?.(path12);
32915
+ #ignored(path14) {
32916
+ return this.seen.has(path14) || !!this.#ignore?.ignored?.(path14);
32419
32917
  }
32420
- #childrenIgnored(path12) {
32421
- return !!this.#ignore?.childrenIgnored?.(path12);
32918
+ #childrenIgnored(path14) {
32919
+ return !!this.#ignore?.childrenIgnored?.(path14);
32422
32920
  }
32423
32921
  pause() {
32424
32922
  this.paused = true;
@@ -32635,8 +33133,8 @@ var init_walker = __esm(() => {
32635
33133
  init_processor();
32636
33134
  GlobWalker = class GlobWalker extends GlobUtil {
32637
33135
  matches = new Set;
32638
- constructor(patterns, path12, opts) {
32639
- super(patterns, path12, opts);
33136
+ constructor(patterns, path14, opts) {
33137
+ super(patterns, path14, opts);
32640
33138
  }
32641
33139
  matchEmit(e) {
32642
33140
  this.matches.add(e);
@@ -32673,8 +33171,8 @@ var init_walker = __esm(() => {
32673
33171
  };
32674
33172
  GlobStream = class GlobStream extends GlobUtil {
32675
33173
  results;
32676
- constructor(patterns, path12, opts) {
32677
- super(patterns, path12, opts);
33174
+ constructor(patterns, path14, opts) {
33175
+ super(patterns, path14, opts);
32678
33176
  this.results = new Minipass({
32679
33177
  signal: this.signal,
32680
33178
  objectMode: true
@@ -33102,20 +33600,20 @@ var require_ignore = __commonJS((exports, module) => {
33102
33600
  var throwError = (message, Ctor) => {
33103
33601
  throw new Ctor(message);
33104
33602
  };
33105
- var checkPath = (path12, originalPath, doThrow) => {
33106
- if (!isString(path12)) {
33603
+ var checkPath = (path14, originalPath, doThrow) => {
33604
+ if (!isString(path14)) {
33107
33605
  return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
33108
33606
  }
33109
- if (!path12) {
33607
+ if (!path14) {
33110
33608
  return doThrow(`path must not be empty`, TypeError);
33111
33609
  }
33112
- if (checkPath.isNotRelative(path12)) {
33610
+ if (checkPath.isNotRelative(path14)) {
33113
33611
  const r = "`path.relative()`d";
33114
33612
  return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
33115
33613
  }
33116
33614
  return true;
33117
33615
  };
33118
- var isNotRelative = (path12) => REGEX_TEST_INVALID_PATH.test(path12);
33616
+ var isNotRelative = (path14) => REGEX_TEST_INVALID_PATH.test(path14);
33119
33617
  checkPath.isNotRelative = isNotRelative;
33120
33618
  checkPath.convert = (p) => p;
33121
33619
 
@@ -33158,7 +33656,7 @@ var require_ignore = __commonJS((exports, module) => {
33158
33656
  addPattern(pattern) {
33159
33657
  return this.add(pattern);
33160
33658
  }
33161
- _testOne(path12, checkUnignored) {
33659
+ _testOne(path14, checkUnignored) {
33162
33660
  let ignored = false;
33163
33661
  let unignored = false;
33164
33662
  this._rules.forEach((rule) => {
@@ -33166,7 +33664,7 @@ var require_ignore = __commonJS((exports, module) => {
33166
33664
  if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
33167
33665
  return;
33168
33666
  }
33169
- const matched = rule.regex.test(path12);
33667
+ const matched = rule.regex.test(path14);
33170
33668
  if (matched) {
33171
33669
  ignored = !negative;
33172
33670
  unignored = negative;
@@ -33178,39 +33676,39 @@ var require_ignore = __commonJS((exports, module) => {
33178
33676
  };
33179
33677
  }
33180
33678
  _test(originalPath, cache, checkUnignored, slices) {
33181
- const path12 = originalPath && checkPath.convert(originalPath);
33182
- checkPath(path12, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
33183
- return this._t(path12, cache, checkUnignored, slices);
33679
+ const path14 = originalPath && checkPath.convert(originalPath);
33680
+ checkPath(path14, originalPath, this._allowRelativePaths ? RETURN_FALSE : throwError);
33681
+ return this._t(path14, cache, checkUnignored, slices);
33184
33682
  }
33185
- _t(path12, cache, checkUnignored, slices) {
33186
- if (path12 in cache) {
33187
- return cache[path12];
33683
+ _t(path14, cache, checkUnignored, slices) {
33684
+ if (path14 in cache) {
33685
+ return cache[path14];
33188
33686
  }
33189
33687
  if (!slices) {
33190
- slices = path12.split(SLASH);
33688
+ slices = path14.split(SLASH);
33191
33689
  }
33192
33690
  slices.pop();
33193
33691
  if (!slices.length) {
33194
- return cache[path12] = this._testOne(path12, checkUnignored);
33692
+ return cache[path14] = this._testOne(path14, checkUnignored);
33195
33693
  }
33196
33694
  const parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
33197
- return cache[path12] = parent.ignored ? parent : this._testOne(path12, checkUnignored);
33695
+ return cache[path14] = parent.ignored ? parent : this._testOne(path14, checkUnignored);
33198
33696
  }
33199
- ignores(path12) {
33200
- return this._test(path12, this._ignoreCache, false).ignored;
33697
+ ignores(path14) {
33698
+ return this._test(path14, this._ignoreCache, false).ignored;
33201
33699
  }
33202
33700
  createFilter() {
33203
- return (path12) => !this.ignores(path12);
33701
+ return (path14) => !this.ignores(path14);
33204
33702
  }
33205
33703
  filter(paths) {
33206
33704
  return makeArray(paths).filter(this.createFilter());
33207
33705
  }
33208
- test(path12) {
33209
- return this._test(path12, this._testCache, true);
33706
+ test(path14) {
33707
+ return this._test(path14, this._testCache, true);
33210
33708
  }
33211
33709
  }
33212
33710
  var factory = (options) => new Ignore2(options);
33213
- var isPathValid = (path12) => checkPath(path12 && checkPath.convert(path12), path12, RETURN_FALSE);
33711
+ var isPathValid = (path14) => checkPath(path14 && checkPath.convert(path14), path14, RETURN_FALSE);
33214
33712
  factory.isPathValid = isPathValid;
33215
33713
  factory.default = factory;
33216
33714
  module.exports = factory;
@@ -33218,7 +33716,7 @@ var require_ignore = __commonJS((exports, module) => {
33218
33716
  const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
33219
33717
  checkPath.convert = makePosix;
33220
33718
  const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
33221
- checkPath.isNotRelative = (path12) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path12) || isNotRelative(path12);
33719
+ checkPath.isNotRelative = (path14) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path14) || isNotRelative(path14);
33222
33720
  }
33223
33721
  });
33224
33722
 
@@ -33270,7 +33768,7 @@ function validatePolicy(policy, opts = {}) {
33270
33768
  if (!Array.isArray(p.rules))
33271
33769
  throw new TypeError("policy.rules must be an array");
33272
33770
  const dropCount = p.rules.filter((r) => r?.disposition === "Drop").length;
33273
- const maxIgnore = typeof p.maxIgnorePatterns === "number" ? p.maxIgnorePatterns : MAX_IGNORE_PATTERNS2;
33771
+ const maxIgnore = typeof p.maxIgnorePatterns === "number" ? p.maxIgnorePatterns : MAX_IGNORE_PATTERNS;
33274
33772
  if (dropCount > maxIgnore) {
33275
33773
  throw new TypeError(`policy: ${dropCount} Drop rules exceed maxIgnorePatterns=${maxIgnore}`);
33276
33774
  }
@@ -33280,15 +33778,15 @@ function validatePolicy(policy, opts = {}) {
33280
33778
  }
33281
33779
  }
33282
33780
  }
33283
- function matchesGlob2(path12, pattern) {
33781
+ function matchesGlob2(path14, pattern) {
33284
33782
  let re = regexCache.get(pattern);
33285
33783
  if (!re) {
33286
33784
  re = globToRegex(pattern);
33287
33785
  regexCache.set(pattern, re);
33288
33786
  }
33289
- return re.test(path12);
33787
+ return re.test(path14);
33290
33788
  }
33291
- var MAX_MATCH_WORK = 1e5, MAX_IGNORE_PATTERNS2 = 1024, DEFAULT_POLICY, applyPolicy = (filePath, policy) => {
33789
+ var DEFAULT_POLICY, applyPolicy = (filePath, policy) => {
33292
33790
  const normalized = filePath.trim();
33293
33791
  for (const rule of policy.rules) {
33294
33792
  if (matchesGlob2(normalized, rule.pattern))
@@ -33297,48 +33795,14 @@ var MAX_MATCH_WORK = 1e5, MAX_IGNORE_PATTERNS2 = 1024, DEFAULT_POLICY, applyPoli
33297
33795
  return "Keep";
33298
33796
  }, regexCache;
33299
33797
  var init_capture_policy = __esm(() => {
33300
- DEFAULT_POLICY = {
33301
- rules: [
33302
- { pattern: "**/node_modules/**", disposition: "Drop" },
33303
- { pattern: "**/.git/**", disposition: "Drop" },
33304
- { pattern: "**/dist/**", disposition: "Drop" },
33305
- { pattern: "**/build/**", disposition: "Drop" },
33306
- { pattern: "**/coverage/**", disposition: "Drop" },
33307
- { pattern: ".env", disposition: "Drop" },
33308
- { pattern: ".env.*", disposition: "Drop" },
33309
- { pattern: "**/generated/**", disposition: "Drop" },
33310
- { pattern: "**/*.generated.*", disposition: "Drop" },
33311
- { pattern: "**/*.d.ts", disposition: "Drop" },
33312
- { pattern: "**/__tests__/**", disposition: "Drop" },
33313
- { pattern: "**/tests/**", disposition: "Drop" },
33314
- { pattern: "**/*.test.ts", disposition: "Drop" },
33315
- { pattern: "**/*.test.tsx", disposition: "Drop" },
33316
- { pattern: "**/*.test.js", disposition: "Drop" },
33317
- { pattern: "**/*.test.jsx", disposition: "Drop" },
33318
- { pattern: "**/*.spec.ts", disposition: "Drop" },
33319
- { pattern: "**/*.spec.tsx", disposition: "Drop" },
33320
- { pattern: "**/*.spec.js", disposition: "Drop" },
33321
- { pattern: "**/*.spec.jsx", disposition: "Drop" },
33322
- { pattern: "**/benchmarks/**", disposition: "Drop" },
33323
- { pattern: "**/fixtures/**", disposition: "Drop" },
33324
- { pattern: "**/*.wasm*", disposition: "Drop" },
33325
- { pattern: "**/*.min.*", disposition: "Drop" },
33326
- { pattern: "**/*.map", disposition: "Drop" },
33327
- { pattern: "**/lock.yaml", disposition: "Drop" },
33328
- { pattern: "**/pnpm-lock.yaml", disposition: "Drop" },
33329
- { pattern: "**/package-lock.json", disposition: "Drop" },
33330
- { pattern: "**/bun.lockb", disposition: "Drop" },
33331
- { pattern: "**/yarn.lock", disposition: "Drop" }
33332
- ],
33333
- maxMatchWork: MAX_MATCH_WORK,
33334
- maxIgnorePatterns: MAX_IGNORE_PATTERNS2
33335
- };
33798
+ init_dist();
33799
+ DEFAULT_POLICY = DEFAULT_CAPTURE_POLICY;
33336
33800
  regexCache = new Map;
33337
33801
  });
33338
33802
 
33339
33803
  // ../../packages/core/dist/services/search/ignore-patterns.js
33340
- import fs8 from "fs/promises";
33341
- import path12 from "path";
33804
+ import fs9 from "fs/promises";
33805
+ import path14 from "path";
33342
33806
  function buildExtensionGlob(extensions) {
33343
33807
  return extensions.map((ext2) => `**/*${ext2}`);
33344
33808
  }
@@ -33361,8 +33825,8 @@ async function loadProjectIgnore(projectPath) {
33361
33825
  const ig = ignore();
33362
33826
  ig.add(DEFAULT_IGNORES);
33363
33827
  try {
33364
- const gitignorePath = path12.join(projectPath, ".gitignore");
33365
- const gitignoreContent = await fs8.readFile(gitignorePath, "utf8");
33828
+ const gitignorePath = path14.join(projectPath, ".gitignore");
33829
+ const gitignoreContent = await fs9.readFile(gitignorePath, "utf8");
33366
33830
  const rules = gitignoreContent.split(`
33367
33831
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
33368
33832
  ig.add(rules);
@@ -34958,15 +35422,15 @@ var require_pg_connection_string = __commonJS((exports, module) => {
34958
35422
  if (config3.sslnegotiation === "direct" && config3.ssl === undefined) {
34959
35423
  config3.ssl = true;
34960
35424
  }
34961
- const fs9 = config3.sslcert || config3.sslkey || config3.sslrootcert ? __require("fs") : null;
35425
+ const fs10 = config3.sslcert || config3.sslkey || config3.sslrootcert ? __require("fs") : null;
34962
35426
  if (config3.sslcert) {
34963
- config3.ssl.cert = fs9.readFileSync(config3.sslcert).toString();
35427
+ config3.ssl.cert = fs10.readFileSync(config3.sslcert).toString();
34964
35428
  }
34965
35429
  if (config3.sslkey) {
34966
- config3.ssl.key = fs9.readFileSync(config3.sslkey).toString();
35430
+ config3.ssl.key = fs10.readFileSync(config3.sslkey).toString();
34967
35431
  }
34968
35432
  if (config3.sslrootcert) {
34969
- config3.ssl.ca = fs9.readFileSync(config3.sslrootcert).toString();
35433
+ config3.ssl.ca = fs10.readFileSync(config3.sslrootcert).toString();
34970
35434
  }
34971
35435
  if (options.useLibpqCompat && config3.uselibpqcompat) {
34972
35436
  throw new Error("Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.");
@@ -36680,7 +37144,7 @@ var require_split2 = __commonJS((exports, module) => {
36680
37144
 
36681
37145
  // ../../node_modules/pgpass/lib/helper.js
36682
37146
  var require_helper = __commonJS((exports, module) => {
36683
- var path13 = __require("path");
37147
+ var path15 = __require("path");
36684
37148
  var Stream2 = __require("stream").Stream;
36685
37149
  var split = require_split2();
36686
37150
  var util3 = __require("util");
@@ -36720,7 +37184,7 @@ var require_helper = __commonJS((exports, module) => {
36720
37184
  };
36721
37185
  exports.getFileName = function(rawEnv) {
36722
37186
  var env = rawEnv || process.env;
36723
- var file2 = env.PGPASSFILE || (isWin ? path13.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path13.join(env.HOME || "./", ".pgpass"));
37187
+ var file2 = env.PGPASSFILE || (isWin ? path15.join(env.APPDATA || "./", "postgresql", "pgpass.conf") : path15.join(env.HOME || "./", ".pgpass"));
36724
37188
  return file2;
36725
37189
  };
36726
37190
  exports.usePgPass = function(stats, fname) {
@@ -36844,16 +37308,16 @@ var require_helper = __commonJS((exports, module) => {
36844
37308
 
36845
37309
  // ../../node_modules/pgpass/lib/index.js
36846
37310
  var require_lib = __commonJS((exports, module) => {
36847
- var path13 = __require("path");
36848
- var fs9 = __require("fs");
37311
+ var path15 = __require("path");
37312
+ var fs10 = __require("fs");
36849
37313
  var helper = require_helper();
36850
37314
  module.exports = function(connInfo, cb) {
36851
37315
  var file2 = helper.getFileName();
36852
- fs9.stat(file2, function(err, stat) {
37316
+ fs10.stat(file2, function(err, stat) {
36853
37317
  if (err || !helper.usePgPass(stat, file2)) {
36854
37318
  return cb(undefined);
36855
37319
  }
36856
- var st = fs9.createReadStream(file2);
37320
+ var st = fs10.createReadStream(file2);
36857
37321
  helper.getPassword(connInfo, st, cb);
36858
37322
  });
36859
37323
  };
@@ -38552,8 +39016,8 @@ var init_alias_resolver = __esm(() => {
38552
39016
  });
38553
39017
 
38554
39018
  // ../../packages/core/dist/services/search/index-manager.js
38555
- import fs9 from "fs";
38556
- import path13 from "path";
39019
+ import fs10 from "fs";
39020
+ import path15 from "path";
38557
39021
 
38558
39022
  class IndexManager {
38559
39023
  metadataCache = new Map;
@@ -38646,9 +39110,9 @@ class IndexManager {
38646
39110
  const fileMetadata = {};
38647
39111
  let totalSize = 0;
38648
39112
  for (const filePath of indexedFiles) {
38649
- const fullPath = path13.join(projectPath, filePath);
39113
+ const fullPath = path15.join(projectPath, filePath);
38650
39114
  try {
38651
- const stat = await fs9.promises.stat(fullPath);
39115
+ const stat = await fs10.promises.stat(fullPath);
38652
39116
  fileMetadata[filePath] = {
38653
39117
  path: filePath,
38654
39118
  mtime: stat.mtimeMs,
@@ -38699,9 +39163,9 @@ class IndexManager {
38699
39163
  if (ig.ignores(match2)) {
38700
39164
  continue;
38701
39165
  }
38702
- const fullPath = path13.join(projectPath, match2);
39166
+ const fullPath = path15.join(projectPath, match2);
38703
39167
  try {
38704
- const stat = await fs9.promises.stat(fullPath);
39168
+ const stat = await fs10.promises.stat(fullPath);
38705
39169
  files.set(match2, {
38706
39170
  path: match2,
38707
39171
  mtime: stat.mtimeMs,
@@ -41886,19 +42350,19 @@ var require_token_io = __commonJS((exports, module) => {
41886
42350
  getUserDataDir: () => getUserDataDir
41887
42351
  });
41888
42352
  module.exports = __toCommonJS2(token_io_exports);
41889
- var import_path8 = __toESM2(__require("path"));
41890
- var import_fs5 = __toESM2(__require("fs"));
42353
+ var import_path9 = __toESM2(__require("path"));
42354
+ var import_fs6 = __toESM2(__require("fs"));
41891
42355
  var import_os3 = __toESM2(__require("os"));
41892
42356
  var import_token_error = require_token_error();
41893
42357
  function findRootDir() {
41894
42358
  try {
41895
42359
  let dir = process.cwd();
41896
- while (dir !== import_path8.default.dirname(dir)) {
41897
- const pkgPath = import_path8.default.join(dir, ".vercel");
41898
- if (import_fs5.default.existsSync(pkgPath)) {
42360
+ while (dir !== import_path9.default.dirname(dir)) {
42361
+ const pkgPath = import_path9.default.join(dir, ".vercel");
42362
+ if (import_fs6.default.existsSync(pkgPath)) {
41899
42363
  return dir;
41900
42364
  }
41901
- dir = import_path8.default.dirname(dir);
42365
+ dir = import_path9.default.dirname(dir);
41902
42366
  }
41903
42367
  } catch (e) {
41904
42368
  throw new import_token_error.VercelOidcTokenError("Token refresh only supported in node server environments");
@@ -41911,9 +42375,9 @@ var require_token_io = __commonJS((exports, module) => {
41911
42375
  }
41912
42376
  switch (import_os3.default.platform()) {
41913
42377
  case "darwin":
41914
- return import_path8.default.join(import_os3.default.homedir(), "Library/Application Support");
42378
+ return import_path9.default.join(import_os3.default.homedir(), "Library/Application Support");
41915
42379
  case "linux":
41916
- return import_path8.default.join(import_os3.default.homedir(), ".local/share");
42380
+ return import_path9.default.join(import_os3.default.homedir(), ".local/share");
41917
42381
  case "win32":
41918
42382
  if (process.env.LOCALAPPDATA) {
41919
42383
  return process.env.LOCALAPPDATA;
@@ -41954,23 +42418,23 @@ var require_auth_config = __commonJS((exports, module) => {
41954
42418
  writeAuthConfig: () => writeAuthConfig
41955
42419
  });
41956
42420
  module.exports = __toCommonJS2(auth_config_exports);
41957
- var fs10 = __toESM2(__require("fs"));
41958
- var path14 = __toESM2(__require("path"));
42421
+ var fs11 = __toESM2(__require("fs"));
42422
+ var path16 = __toESM2(__require("path"));
41959
42423
  var import_token_util = require_token_util();
41960
42424
  function getAuthConfigPath() {
41961
42425
  const dataDir = (0, import_token_util.getVercelDataDir)();
41962
42426
  if (!dataDir) {
41963
42427
  throw new Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);
41964
42428
  }
41965
- return path14.join(dataDir, "auth.json");
42429
+ return path16.join(dataDir, "auth.json");
41966
42430
  }
41967
42431
  function readAuthConfig() {
41968
42432
  try {
41969
42433
  const authPath = getAuthConfigPath();
41970
- if (!fs10.existsSync(authPath)) {
42434
+ if (!fs11.existsSync(authPath)) {
41971
42435
  return null;
41972
42436
  }
41973
- const content = fs10.readFileSync(authPath, "utf8");
42437
+ const content = fs11.readFileSync(authPath, "utf8");
41974
42438
  if (!content) {
41975
42439
  return null;
41976
42440
  }
@@ -41981,11 +42445,11 @@ var require_auth_config = __commonJS((exports, module) => {
41981
42445
  }
41982
42446
  function writeAuthConfig(config3) {
41983
42447
  const authPath = getAuthConfigPath();
41984
- const authDir = path14.dirname(authPath);
41985
- if (!fs10.existsSync(authDir)) {
41986
- fs10.mkdirSync(authDir, { mode: 504, recursive: true });
42448
+ const authDir = path16.dirname(authPath);
42449
+ if (!fs11.existsSync(authDir)) {
42450
+ fs11.mkdirSync(authDir, { mode: 504, recursive: true });
41987
42451
  }
41988
- fs10.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
42452
+ fs11.writeFileSync(authPath, JSON.stringify(config3, null, 2), { mode: 384 });
41989
42453
  }
41990
42454
  function isValidAccessToken(authConfig, expirationBufferMs = 0) {
41991
42455
  if (!authConfig.token)
@@ -42160,8 +42624,8 @@ var require_token_util = __commonJS((exports, module) => {
42160
42624
  saveToken: () => saveToken
42161
42625
  });
42162
42626
  module.exports = __toCommonJS2(token_util_exports);
42163
- var path14 = __toESM2(__require("path"));
42164
- var fs10 = __toESM2(__require("fs"));
42627
+ var path16 = __toESM2(__require("path"));
42628
+ var fs11 = __toESM2(__require("fs"));
42165
42629
  var import_token_error = require_token_error();
42166
42630
  var import_token_io = require_token_io();
42167
42631
  var import_auth_config = require_auth_config();
@@ -42173,7 +42637,7 @@ var require_token_util = __commonJS((exports, module) => {
42173
42637
  if (!dataDir) {
42174
42638
  return null;
42175
42639
  }
42176
- return path14.join(dataDir, vercelFolder);
42640
+ return path16.join(dataDir, vercelFolder);
42177
42641
  }
42178
42642
  async function getVercelToken2(options) {
42179
42643
  const authConfig = (0, import_auth_config.readAuthConfig)();
@@ -42241,11 +42705,11 @@ var require_token_util = __commonJS((exports, module) => {
42241
42705
  if (!dir) {
42242
42706
  throw new import_token_error.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");
42243
42707
  }
42244
- const prjPath = path14.join(dir, ".vercel", "project.json");
42245
- if (!fs10.existsSync(prjPath)) {
42708
+ const prjPath = path16.join(dir, ".vercel", "project.json");
42709
+ if (!fs11.existsSync(prjPath)) {
42246
42710
  throw new import_token_error.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");
42247
42711
  }
42248
- const prj = JSON.parse(fs10.readFileSync(prjPath, "utf8"));
42712
+ const prj = JSON.parse(fs11.readFileSync(prjPath, "utf8"));
42249
42713
  if (typeof prj.projectId !== "string" && typeof prj.orgId !== "string") {
42250
42714
  throw new TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");
42251
42715
  }
@@ -42256,11 +42720,11 @@ var require_token_util = __commonJS((exports, module) => {
42256
42720
  if (!dir) {
42257
42721
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
42258
42722
  }
42259
- const tokenPath = path14.join(dir, "com.vercel.token", `${projectId}.json`);
42723
+ const tokenPath = path16.join(dir, "com.vercel.token", `${projectId}.json`);
42260
42724
  const tokenJson = JSON.stringify(token);
42261
- fs10.mkdirSync(path14.dirname(tokenPath), { mode: 504, recursive: true });
42262
- fs10.writeFileSync(tokenPath, tokenJson);
42263
- fs10.chmodSync(tokenPath, 432);
42725
+ fs11.mkdirSync(path16.dirname(tokenPath), { mode: 504, recursive: true });
42726
+ fs11.writeFileSync(tokenPath, tokenJson);
42727
+ fs11.chmodSync(tokenPath, 432);
42264
42728
  return;
42265
42729
  }
42266
42730
  function loadToken(projectId) {
@@ -42268,11 +42732,11 @@ var require_token_util = __commonJS((exports, module) => {
42268
42732
  if (!dir) {
42269
42733
  throw new import_token_error.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");
42270
42734
  }
42271
- const tokenPath = path14.join(dir, "com.vercel.token", `${projectId}.json`);
42272
- if (!fs10.existsSync(tokenPath)) {
42735
+ const tokenPath = path16.join(dir, "com.vercel.token", `${projectId}.json`);
42736
+ if (!fs11.existsSync(tokenPath)) {
42273
42737
  return null;
42274
42738
  }
42275
- const token = JSON.parse(fs10.readFileSync(tokenPath, "utf8"));
42739
+ const token = JSON.parse(fs11.readFileSync(tokenPath, "utf8"));
42276
42740
  assertVercelOidcTokenResponse(token);
42277
42741
  return token;
42278
42742
  }
@@ -53114,37 +53578,37 @@ function createOpenAI(options = {}) {
53114
53578
  }, `ai-sdk/openai/${VERSION4}`);
53115
53579
  const createChatModel = (modelId) => new OpenAIChatLanguageModel(modelId, {
53116
53580
  provider: `${providerName}.chat`,
53117
- url: ({ path: path14 }) => `${baseURL}${path14}`,
53581
+ url: ({ path: path16 }) => `${baseURL}${path16}`,
53118
53582
  headers: getHeaders,
53119
53583
  fetch: options.fetch
53120
53584
  });
53121
53585
  const createCompletionModel = (modelId) => new OpenAICompletionLanguageModel(modelId, {
53122
53586
  provider: `${providerName}.completion`,
53123
- url: ({ path: path14 }) => `${baseURL}${path14}`,
53587
+ url: ({ path: path16 }) => `${baseURL}${path16}`,
53124
53588
  headers: getHeaders,
53125
53589
  fetch: options.fetch
53126
53590
  });
53127
53591
  const createEmbeddingModel = (modelId) => new OpenAIEmbeddingModel(modelId, {
53128
53592
  provider: `${providerName}.embedding`,
53129
- url: ({ path: path14 }) => `${baseURL}${path14}`,
53593
+ url: ({ path: path16 }) => `${baseURL}${path16}`,
53130
53594
  headers: getHeaders,
53131
53595
  fetch: options.fetch
53132
53596
  });
53133
53597
  const createImageModel = (modelId) => new OpenAIImageModel(modelId, {
53134
53598
  provider: `${providerName}.image`,
53135
- url: ({ path: path14 }) => `${baseURL}${path14}`,
53599
+ url: ({ path: path16 }) => `${baseURL}${path16}`,
53136
53600
  headers: getHeaders,
53137
53601
  fetch: options.fetch
53138
53602
  });
53139
53603
  const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, {
53140
53604
  provider: `${providerName}.transcription`,
53141
- url: ({ path: path14 }) => `${baseURL}${path14}`,
53605
+ url: ({ path: path16 }) => `${baseURL}${path16}`,
53142
53606
  headers: getHeaders,
53143
53607
  fetch: options.fetch
53144
53608
  });
53145
53609
  const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
53146
53610
  provider: `${providerName}.speech`,
53147
- url: ({ path: path14 }) => `${baseURL}${path14}`,
53611
+ url: ({ path: path16 }) => `${baseURL}${path16}`,
53148
53612
  headers: getHeaders,
53149
53613
  fetch: options.fetch
53150
53614
  });
@@ -53157,7 +53621,7 @@ function createOpenAI(options = {}) {
53157
53621
  const createResponsesModel = (modelId) => {
53158
53622
  return new OpenAIResponsesLanguageModel(modelId, {
53159
53623
  provider: `${providerName}.responses`,
53160
- url: ({ path: path14 }) => `${baseURL}${path14}`,
53624
+ url: ({ path: path16 }) => `${baseURL}${path16}`,
53161
53625
  headers: getHeaders,
53162
53626
  fetch: options.fetch,
53163
53627
  fileIdPrefixes: ["file-"]
@@ -69702,26 +70166,26 @@ var require_process = __commonJS((exports, module) => {
69702
70166
 
69703
70167
  // ../../node_modules/detect-libc/lib/filesystem.js
69704
70168
  var require_filesystem = __commonJS((exports, module) => {
69705
- var fs10 = __require("fs");
70169
+ var fs11 = __require("fs");
69706
70170
  var LDD_PATH = "/usr/bin/ldd";
69707
70171
  var SELF_PATH = "/proc/self/exe";
69708
70172
  var MAX_LENGTH = 2048;
69709
- var readFileSync2 = (path14) => {
69710
- const fd = fs10.openSync(path14, "r");
70173
+ var readFileSync2 = (path16) => {
70174
+ const fd = fs11.openSync(path16, "r");
69711
70175
  const buffer = Buffer.alloc(MAX_LENGTH);
69712
- const bytesRead = fs10.readSync(fd, buffer, 0, MAX_LENGTH, 0);
69713
- fs10.close(fd, () => {});
70176
+ const bytesRead = fs11.readSync(fd, buffer, 0, MAX_LENGTH, 0);
70177
+ fs11.close(fd, () => {});
69714
70178
  return buffer.subarray(0, bytesRead);
69715
70179
  };
69716
- var readFile = (path14) => new Promise((resolve4, reject) => {
69717
- fs10.open(path14, "r", (err, fd) => {
70180
+ var readFile = (path16) => new Promise((resolve4, reject) => {
70181
+ fs11.open(path16, "r", (err, fd) => {
69718
70182
  if (err) {
69719
70183
  reject(err);
69720
70184
  } else {
69721
70185
  const buffer = Buffer.alloc(MAX_LENGTH);
69722
- fs10.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
70186
+ fs11.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => {
69723
70187
  resolve4(buffer.subarray(0, bytesRead));
69724
- fs10.close(fd, () => {});
70188
+ fs11.close(fd, () => {});
69725
70189
  });
69726
70190
  }
69727
70191
  });
@@ -69826,11 +70290,11 @@ var require_detect_libc = __commonJS((exports, module) => {
69826
70290
  }
69827
70291
  return null;
69828
70292
  };
69829
- var familyFromInterpreterPath = (path14) => {
69830
- if (path14) {
69831
- if (path14.includes("/ld-musl-")) {
70293
+ var familyFromInterpreterPath = (path16) => {
70294
+ if (path16) {
70295
+ if (path16.includes("/ld-musl-")) {
69832
70296
  return MUSL;
69833
- } else if (path14.includes("/ld-linux-")) {
70297
+ } else if (path16.includes("/ld-linux-")) {
69834
70298
  return GLIBC;
69835
70299
  }
69836
70300
  }
@@ -69875,8 +70339,8 @@ var require_detect_libc = __commonJS((exports, module) => {
69875
70339
  cachedFamilyInterpreter = null;
69876
70340
  try {
69877
70341
  const selfContent = await readFile(SELF_PATH);
69878
- const path14 = interpreterPath(selfContent);
69879
- cachedFamilyInterpreter = familyFromInterpreterPath(path14);
70342
+ const path16 = interpreterPath(selfContent);
70343
+ cachedFamilyInterpreter = familyFromInterpreterPath(path16);
69880
70344
  } catch (e) {}
69881
70345
  return cachedFamilyInterpreter;
69882
70346
  };
@@ -69887,8 +70351,8 @@ var require_detect_libc = __commonJS((exports, module) => {
69887
70351
  cachedFamilyInterpreter = null;
69888
70352
  try {
69889
70353
  const selfContent = readFileSync2(SELF_PATH);
69890
- const path14 = interpreterPath(selfContent);
69891
- cachedFamilyInterpreter = familyFromInterpreterPath(path14);
70354
+ const path16 = interpreterPath(selfContent);
70355
+ cachedFamilyInterpreter = familyFromInterpreterPath(path16);
69892
70356
  } catch (e) {}
69893
70357
  return cachedFamilyInterpreter;
69894
70358
  };
@@ -71550,18 +72014,18 @@ var require_sharp = __commonJS((exports, module) => {
71550
72014
  `@img/sharp-${runtimePlatform}/sharp.node`,
71551
72015
  "@img/sharp-wasm32/sharp.node"
71552
72016
  ];
71553
- var path14;
72017
+ var path16;
71554
72018
  var sharp;
71555
72019
  var errors4 = [];
71556
- for (path14 of paths) {
72020
+ for (path16 of paths) {
71557
72021
  try {
71558
- sharp = __require(path14);
72022
+ sharp = __require(path16);
71559
72023
  break;
71560
72024
  } catch (err) {
71561
72025
  errors4.push(err);
71562
72026
  }
71563
72027
  }
71564
- if (sharp && path14.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
72028
+ if (sharp && path16.startsWith("@img/sharp-linux-x64") && !sharp._isUsingX64V2()) {
71565
72029
  const err = new Error("Prebuilt binaries for linux-x64 require v2 microarchitecture");
71566
72030
  err.code = "Unsupported CPU";
71567
72031
  errors4.push(err);
@@ -71570,7 +72034,7 @@ var require_sharp = __commonJS((exports, module) => {
71570
72034
  if (sharp) {
71571
72035
  module.exports = sharp;
71572
72036
  } else {
71573
- const [isLinux, isMacOs, isWindows] = ["linux", "darwin", "win32"].map((os6) => runtimePlatform.startsWith(os6));
72037
+ const [isLinux, isMacOs, isWindows] = ["linux", "darwin", "win32"].map((os8) => runtimePlatform.startsWith(os8));
71574
72038
  const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`];
71575
72039
  errors4.forEach((err) => {
71576
72040
  if (err.code !== "MODULE_NOT_FOUND") {
@@ -71583,9 +72047,9 @@ var require_sharp = __commonJS((exports, module) => {
71583
72047
  const { found, expected } = isUnsupportedNodeRuntime();
71584
72048
  help.push("- Please upgrade Node.js:", ` Found ${found}`, ` Requires ${expected}`);
71585
72049
  } else if (prebuiltPlatforms.includes(runtimePlatform)) {
71586
- const [os6, cpu] = runtimePlatform.split("-");
71587
- const libc = os6.endsWith("musl") ? " --libc=musl" : "";
71588
- 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`);
72050
+ const [os8, cpu] = runtimePlatform.split("-");
72051
+ const libc = os8.endsWith("musl") ? " --libc=musl" : "";
72052
+ 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`);
71589
72053
  } else {
71590
72054
  help.push(`- Manually install libvips >= ${minimumLibvipsVersion}`, "- Add experimental WebAssembly-based dependencies:", " npm install --cpu=wasm32 sharp", " npm install @img/sharp-wasm32");
71591
72055
  }
@@ -72845,7 +73309,7 @@ var require_operation = __commonJS((exports, module) => {
72845
73309
  float: "float",
72846
73310
  approximate: "approximate"
72847
73311
  };
72848
- function rotate(angle, options) {
73312
+ function rotate2(angle, options) {
72849
73313
  if (!is.defined(angle)) {
72850
73314
  return this.autoOrient();
72851
73315
  }
@@ -73272,7 +73736,7 @@ var require_operation = __commonJS((exports, module) => {
73272
73736
  module.exports = (Sharp) => {
73273
73737
  Object.assign(Sharp.prototype, {
73274
73738
  autoOrient,
73275
- rotate,
73739
+ rotate: rotate2,
73276
73740
  flip,
73277
73741
  flop,
73278
73742
  affine,
@@ -74423,15 +74887,15 @@ var require_color = __commonJS((exports, module) => {
74423
74887
  };
74424
74888
  }
74425
74889
  function wrapConversion(toModel, graph) {
74426
- const path14 = [graph[toModel].parent, toModel];
74890
+ const path16 = [graph[toModel].parent, toModel];
74427
74891
  let fn = conversions_default[graph[toModel].parent][toModel];
74428
74892
  let cur = graph[toModel].parent;
74429
74893
  while (graph[cur].parent) {
74430
- path14.unshift(graph[cur].parent);
74894
+ path16.unshift(graph[cur].parent);
74431
74895
  fn = link(conversions_default[graph[cur].parent][cur], fn);
74432
74896
  cur = graph[cur].parent;
74433
74897
  }
74434
- fn.conversion = path14;
74898
+ fn.conversion = path16;
74435
74899
  return fn;
74436
74900
  }
74437
74901
  function route(fromModel) {
@@ -75036,7 +75500,7 @@ var require_output = __commonJS((exports, module) => {
75036
75500
  Copyright 2013 Lovell Fuller and others.
75037
75501
  SPDX-License-Identifier: Apache-2.0
75038
75502
  */
75039
- var path14 = __require("path");
75503
+ var path16 = __require("path");
75040
75504
  var is = require_is();
75041
75505
  var sharp = require_sharp();
75042
75506
  var formats = new Map([
@@ -75067,9 +75531,9 @@ var require_output = __commonJS((exports, module) => {
75067
75531
  let err;
75068
75532
  if (!is.string(fileOut)) {
75069
75533
  err = new Error("Missing output file path");
75070
- } else if (is.string(this.options.input.file) && path14.resolve(this.options.input.file) === path14.resolve(fileOut)) {
75534
+ } else if (is.string(this.options.input.file) && path16.resolve(this.options.input.file) === path16.resolve(fileOut)) {
75071
75535
  err = new Error("Cannot use same file for input and output");
75072
- } else if (jp2Regex.test(path14.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
75536
+ } else if (jp2Regex.test(path16.extname(fileOut)) && !this.constructor.format.jp2k.output.file) {
75073
75537
  err = errJp2Save();
75074
75538
  }
75075
75539
  if (err) {
@@ -82316,11 +82780,11 @@ var init_transformers_node = __esm(() => {
82316
82780
  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}).`);
82317
82781
  }
82318
82782
  for (let i = 0;i < num_chunks; ++i) {
82319
- const path14 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
82320
- const fullPath = `${options.subfolder ?? ""}/${path14}`;
82783
+ const path16 = `${baseName}_data${i === 0 ? "" : "_" + i}`;
82784
+ const fullPath = `${options.subfolder ?? ""}/${path16}`;
82321
82785
  externalDataPromises.push(new Promise(async (resolve4, reject) => {
82322
82786
  const data = await (0, _utils_hub_js__WEBPACK_IMPORTED_MODULE_5__.getModelFile)(pretrained_model_name_or_path, fullPath, true, options, return_path);
82323
- resolve4(data instanceof Uint8Array ? { path: path14, data } : path14);
82787
+ resolve4(data instanceof Uint8Array ? { path: path16, data } : path16);
82324
82788
  }));
82325
82789
  }
82326
82790
  } else if (session_options.externalData !== undefined) {
@@ -95384,7 +95848,7 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
95384
95848
  const blob = new Blob([wav], { type: "audio/wav" });
95385
95849
  return blob;
95386
95850
  }
95387
- async save(path14) {
95851
+ async save(path16) {
95388
95852
  let fn;
95389
95853
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_BROWSER_ENV) {
95390
95854
  if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_WEBWORKER_ENV) {
@@ -95392,14 +95856,14 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
95392
95856
  }
95393
95857
  fn = _core_js__WEBPACK_IMPORTED_MODULE_2__.saveBlob;
95394
95858
  } else if (_env_js__WEBPACK_IMPORTED_MODULE_3__.apis.IS_FS_AVAILABLE) {
95395
- fn = async (path15, blob) => {
95859
+ fn = async (path17, blob) => {
95396
95860
  let buffer = await blob.arrayBuffer();
95397
- node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path15, Buffer.from(buffer));
95861
+ node_fs__WEBPACK_IMPORTED_MODULE_5__["default"].writeFileSync(path17, Buffer.from(buffer));
95398
95862
  };
95399
95863
  } else {
95400
95864
  throw new Error("Unable to save because filesystem is disabled in this environment.");
95401
95865
  }
95402
- await fn(path14, this.toBlob());
95866
+ await fn(path16, this.toBlob());
95403
95867
  }
95404
95868
  }
95405
95869
  },
@@ -95495,11 +95959,11 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
95495
95959
  function calculateReflectOffset(i, w) {
95496
95960
  return Math.abs((i + w) % (2 * w) - w);
95497
95961
  }
95498
- function saveBlob(path14, blob) {
95962
+ function saveBlob(path16, blob) {
95499
95963
  const dataURL = URL.createObjectURL(blob);
95500
95964
  const downloadLink = document.createElement("a");
95501
95965
  downloadLink.href = dataURL;
95502
- downloadLink.download = path14;
95966
+ downloadLink.download = path16;
95503
95967
  downloadLink.click();
95504
95968
  downloadLink.remove();
95505
95969
  URL.revokeObjectURL(dataURL);
@@ -96100,8 +96564,8 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
96100
96564
  }
96101
96565
 
96102
96566
  class FileCache {
96103
- constructor(path14) {
96104
- this.path = path14;
96567
+ constructor(path16) {
96568
+ this.path = path16;
96105
96569
  }
96106
96570
  async match(request) {
96107
96571
  let filePath = node_path__WEBPACK_IMPORTED_MODULE_1__["default"].join(this.path, request);
@@ -96857,20 +97321,20 @@ ${fake_token_around_image}` + `${global_img_token}` + image_token.repeat(image_s
96857
97321
  }
96858
97322
  return this;
96859
97323
  }
96860
- async save(path14) {
97324
+ async save(path16) {
96861
97325
  if (IS_BROWSER_OR_WEBWORKER) {
96862
97326
  if (_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_WEBWORKER_ENV) {
96863
97327
  throw new Error("Unable to save an image from a Web Worker.");
96864
97328
  }
96865
- const extension = path14.split(".").pop().toLowerCase();
97329
+ const extension = path16.split(".").pop().toLowerCase();
96866
97330
  const mime = CONTENT_TYPE_MAP.get(extension) ?? "image/png";
96867
97331
  const blob = await this.toBlob(mime);
96868
- (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path14, blob);
97332
+ (0, _core_js__WEBPACK_IMPORTED_MODULE_0__.saveBlob)(path16, blob);
96869
97333
  } else if (!_env_js__WEBPACK_IMPORTED_MODULE_2__.apis.IS_FS_AVAILABLE) {
96870
97334
  throw new Error("Unable to save the image because filesystem is disabled in this environment.");
96871
97335
  } else {
96872
97336
  const img = this.toSharp();
96873
- return await img.toFile(path14);
97337
+ return await img.toFile(path16);
96874
97338
  }
96875
97339
  }
96876
97340
  toSharp() {
@@ -100397,20 +100861,20 @@ function getRetryDelay(attempt, config3) {
100397
100861
  return Math.min(delay2, config3.maxDelay);
100398
100862
  }
100399
100863
  async function withRetry(fn, config3, context2) {
100400
- let lastError;
100864
+ let lastError2;
100401
100865
  for (let attempt = 0;attempt <= config3.maxRetries; attempt++) {
100402
100866
  try {
100403
100867
  return await fn();
100404
100868
  } catch (error51) {
100405
- lastError = error51;
100869
+ lastError2 = error51;
100406
100870
  if (attempt < config3.maxRetries) {
100407
100871
  const delay2 = getRetryDelay(attempt, config3);
100408
- logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError.message });
100872
+ logger.warn(`[EmbeddingProvider] ${context2} failed (attempt ${attempt + 1}/${config3.maxRetries + 1}), retrying in ${delay2}ms`, { error: lastError2.message });
100409
100873
  await sleep(delay2);
100410
100874
  }
100411
100875
  }
100412
100876
  }
100413
- throw new Error(`${context2} failed after ${config3.maxRetries + 1} attempts: ${lastError?.message}`);
100877
+ throw new Error(`${context2} failed after ${config3.maxRetries + 1} attempts: ${lastError2?.message}`);
100414
100878
  }
100415
100879
  async function withTimeout(fn, timeoutMs, context2) {
100416
100880
  let timeoutId;
@@ -106096,7 +106560,7 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a;
106096
106560
  function ns(e = Yo, t = Yo) {
106097
106561
  return (r) => e(t(r));
106098
106562
  }
106099
- function os6({ dataPath: e, modelName: t, args: r, runtimeDataModel: n }) {
106563
+ function os8({ dataPath: e, modelName: t, args: r, runtimeDataModel: n }) {
106100
106564
  let i = { modelName: t, args: r ?? {} }, o = dp(e);
106101
106565
  if (!o || o.length === 0)
106102
106566
  return i;
@@ -106401,10 +106865,10 @@ Note that ${s.bold("include")} statements only accept relation fields.`, a;
106401
106865
  super(t, "P2023", r);
106402
106866
  }
106403
106867
  };
106404
- var fs10 = new WeakMap;
106868
+ var fs11 = new WeakMap;
106405
106869
  function Ep(e) {
106406
- let t = fs10.get(e);
106407
- return t || (t = Object.entries(e), fs10.set(e, t)), t;
106870
+ let t = fs11.get(e);
106871
+ return t || (t = Object.entries(e), fs11.set(e, t)), t;
106408
106872
  }
106409
106873
  function hs(e, t, r) {
106410
106874
  switch (t.type) {
@@ -109969,7 +110433,7 @@ new PrismaClient({
109969
110433
  let m = await es(this, d);
109970
110434
  if (!d.model)
109971
110435
  return m;
109972
- let g = os6({ dataPath: d.dataPath, modelName: d.model, args: d.args, runtimeDataModel: this._runtimeDataModel });
110436
+ let g = os8({ dataPath: d.dataPath, modelName: d.model, args: d.args, runtimeDataModel: this._runtimeDataModel });
109973
110437
  return Wo({ result: m, modelName: g.modelName, args: g.args, extensions: this._extensions, runtimeDataModel: this._runtimeDataModel, globalOmit: this._globalOmit });
109974
110438
  };
109975
110439
  return this._tracingHelper.runInChildSpan(s.operation, () => new zl.AsyncResource("prisma-client-request").runInAsyncScope(() => a(o)));
@@ -110372,7 +110836,7 @@ var require_prisma = __commonJS((exports) => {
110372
110836
  Prisma.JsonNull = JsonNull2;
110373
110837
  Prisma.AnyNull = AnyNull2;
110374
110838
  Prisma.NullTypes = NullTypes2;
110375
- var path14 = __require("path");
110839
+ var path16 = __require("path");
110376
110840
  exports.Prisma.TransactionIsolationLevel = makeStrictEnum2({
110377
110841
  ReadUncommitted: "ReadUncommitted",
110378
110842
  ReadCommitted: "ReadCommitted",
@@ -113340,11 +113804,17 @@ var init_config2 = __esm(() => {
113340
113804
  ollama: (() => {
113341
113805
  const file2 = fileFor("ollama");
113342
113806
  const model = process.env.OLLAMA_EMBEDDING_MODEL || file2?.model || "qwen3-embedding:4b";
113807
+ const rawEnvDimensions = Number(process.env.OLLAMA_EMBEDDING_DIMENSIONS);
113808
+ const envDimensions = Number.isInteger(rawEnvDimensions) && rawEnvDimensions > 0 ? rawEnvDimensions : undefined;
113809
+ const resolvedDimensions = resolveEmbeddingDimensions(model, file2?.dimensions, envDimensions);
113810
+ if (resolvedDimensions.correctedFrom !== undefined) {
113811
+ logger.warn(`[ollama] config.json records embedding.dimensions ${resolvedDimensions.correctedFrom} for model ` + `"${model}", which emits ${resolvedDimensions.dimensions}. Using ${resolvedDimensions.dimensions}. ` + "Update embedding.dimensions in config.json (or set OLLAMA_EMBEDDING_DIMENSIONS) to silence this.");
113812
+ }
113343
113813
  return {
113344
113814
  provider: "ollama",
113345
113815
  model,
113346
113816
  baseURL: process.env.OLLAMA_BASE_URL || file2?.baseURL || "http://localhost:11434",
113347
- dimensions: process.env.OLLAMA_EMBEDDING_DIMENSIONS ? Number(process.env.OLLAMA_EMBEDDING_DIMENSIONS) : file2?.dimensions ?? 2560,
113817
+ dimensions: resolvedDimensions.dimensions,
113348
113818
  priority: selectedProvider === "ollama" ? 1 : 50,
113349
113819
  timeout: 300000,
113350
113820
  maxRetries: 2,
@@ -117885,7 +118355,7 @@ async function upsertWorkspace(ws) {
117885
118355
  }, { timeout: 60000, maxWait: 1e4 });
117886
118356
  }
117887
118357
  async function updateWorkspaceStatus(projectId, status, opts) {
117888
- const lastError = typeof opts === "string" ? opts : opts?.lastError ?? null;
118358
+ const lastError2 = typeof opts === "string" ? opts : opts?.lastError ?? null;
117889
118359
  const filesCount = typeof opts === "object" ? opts?.filesCount : undefined;
117890
118360
  const chunksCount = typeof opts === "object" ? opts?.chunksCount : undefined;
117891
118361
  const symbolsCount = typeof opts === "object" ? opts?.symbolsCount : undefined;
@@ -117895,7 +118365,7 @@ async function updateWorkspaceStatus(projectId, status, opts) {
117895
118365
  await tx.$executeRaw`
117896
118366
  UPDATE workspaces SET
117897
118367
  status = ${status},
117898
- last_error = ${lastError},
118368
+ last_error = ${lastError2},
117899
118369
  last_indexed_at = ${lastIndexedAt ?? null},
117900
118370
  files_count = COALESCE(${filesCount ?? null}, files_count),
117901
118371
  chunks_count = COALESCE(${chunksCount ?? null}, chunks_count),
@@ -123239,10 +123709,10 @@ var init_chunker_code = __esm(() => {
123239
123709
  });
123240
123710
 
123241
123711
  // ../../packages/core/dist/services/search/smart-chunker.js
123242
- import path14 from "path";
123712
+ import path16 from "path";
123243
123713
  function smartChunk(content, filePath, config3 = {}) {
123244
123714
  const cfg = { ...DEFAULT_CONFIG, ...config3 };
123245
- const ext2 = path14.extname(filePath).toLowerCase();
123715
+ const ext2 = path16.extname(filePath).toLowerCase();
123246
123716
  const relativePath = filePath;
123247
123717
  const fileImports = isCodeFile(ext2) ? extractFileImports(content, ext2) : undefined;
123248
123718
  let chunks;
@@ -123549,8 +124019,8 @@ var init_managed_run_repository_pg = __esm(() => {
123549
124019
  });
123550
124020
 
123551
124021
  // ../../packages/core/dist/services/search/project-indexer.js
123552
- import fs10 from "fs/promises";
123553
- import path15 from "path";
124022
+ import fs11 from "fs/promises";
124023
+ import path17 from "path";
123554
124024
  import { randomUUID as randomUUID3 } from "crypto";
123555
124025
  async function runWithIndexLock(lockMap, projectId, work) {
123556
124026
  const prevLock = lockMap.get(projectId);
@@ -123593,7 +124063,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
123593
124063
  dot: false
123594
124064
  });
123595
124065
  const filteredFiles = files.filter((file2) => {
123596
- const relativePath = path15.relative(projectPath, file2);
124066
+ const relativePath = path17.relative(projectPath, file2);
123597
124067
  const shouldIgnore = ig.ignores(relativePath);
123598
124068
  if (shouldIgnore) {
123599
124069
  logger.debug("Ignoring file per .gitignore during indexing", {
@@ -123633,7 +124103,7 @@ async function indexProjectInternal(deps, projectPath, projectId, options = {})
123633
124103
  });
123634
124104
  }
123635
124105
  }
123636
- const indexedFilesList = filteredFiles.map((f) => path15.relative(projectPath, f));
124106
+ const indexedFilesList = filteredFiles.map((f) => path17.relative(projectPath, f));
123637
124107
  await deps.indexManager.updateIndexMetadata(projectId, projectPath, indexedFilesList);
123638
124108
  logger.info("Project indexing completed", {
123639
124109
  projectId,
@@ -123758,7 +124228,7 @@ async function ensureFreshIndex(deps, projectId, projectPath, options = {}) {
123758
124228
  let errors4 = 0;
123759
124229
  for (const relativeFilePath of filesToReindex) {
123760
124230
  try {
123761
- const fullPath = path15.join(projectPath, relativeFilePath);
124231
+ const fullPath = path17.join(projectPath, relativeFilePath);
123762
124232
  const result = await deps.indexFile(fullPath, projectId, projectPath, centralityMap);
123763
124233
  filesIndexed++;
123764
124234
  chunksIndexed += result.chunks;
@@ -123809,8 +124279,8 @@ async function checkSearchAdmission(deps, projectId, projectPath) {
123809
124279
  }
123810
124280
  async function indexFile(deps, filePath, projectId, projectRoot, centralityMap) {
123811
124281
  projectId = await getProjectIdentityAliasResolver().resolve(projectId);
123812
- const content = await fs10.readFile(filePath, "utf-8");
123813
- const relativePath = path15.relative(projectRoot, filePath);
124282
+ const content = await fs11.readFile(filePath, "utf-8");
124283
+ const relativePath = path17.relative(projectRoot, filePath);
123814
124284
  const maxFileSize = config2.get("security").maxFileSize || 1024 * 1024;
123815
124285
  if (content.length > maxFileSize) {
123816
124286
  logger.warn("File too large, skipping", {
@@ -123830,7 +124300,7 @@ async function indexFile(deps, filePath, projectId, projectRoot, centralityMap)
123830
124300
  chunkIndex: i,
123831
124301
  totalChunks: chunks.length,
123832
124302
  type: chunk.type,
123833
- language: path15.extname(filePath).slice(1),
124303
+ language: path17.extname(filePath).slice(1),
123834
124304
  lineStart: chunk.lineStart,
123835
124305
  lineEnd: chunk.lineEnd,
123836
124306
  label: chunk.label,
@@ -124675,8 +125145,8 @@ function stripNul(content) {
124675
125145
  }
124676
125146
 
124677
125147
  // ../../packages/core/dist/services/etl/stages/discover.js
124678
- import fs11 from "fs/promises";
124679
- import path16 from "path";
125148
+ import fs12 from "fs/promises";
125149
+ import path18 from "path";
124680
125150
  import { createHash as createHash5 } from "crypto";
124681
125151
 
124682
125152
  class DiscoverStage {
@@ -124702,7 +125172,7 @@ class DiscoverStage {
124702
125172
  dot: false,
124703
125173
  absolute: false
124704
125174
  });
124705
- relPaths = found.map((p) => path16.isAbsolute(p) ? path16.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
125175
+ relPaths = found.map((p) => path18.isAbsolute(p) ? path18.relative(ctx.projectPath, p) : p).filter((p) => !ig.ignores(p) && applyPolicy(p, policy) !== "Drop");
124706
125176
  }
124707
125177
  if (ctx.resumeCursor?.path) {
124708
125178
  const cursorPath = ctx.resumeCursor.path;
@@ -124761,10 +125231,10 @@ class DiscoverStage {
124761
125231
  return discovered;
124762
125232
  }
124763
125233
  async processFile(ctx, relativePath, forceReindex) {
124764
- const absolutePath = path16.join(ctx.projectPath, relativePath);
125234
+ const absolutePath = path18.join(ctx.projectPath, relativePath);
124765
125235
  try {
124766
- const stat = await fs11.stat(absolutePath);
124767
- const content = stripNul(await fs11.readFile(absolutePath, "utf-8"));
125236
+ const stat = await fs12.stat(absolutePath);
125237
+ const content = stripNul(await fs12.readFile(absolutePath, "utf-8"));
124768
125238
  const contentHash = createHash5("sha256").update(content).digest("hex");
124769
125239
  let needsReparse = forceReindex;
124770
125240
  if (!forceReindex) {
@@ -124807,8 +125277,8 @@ class DiscoverStage {
124807
125277
  ig.add(pattern);
124808
125278
  }
124809
125279
  try {
124810
- const gitignorePath = path16.join(projectPath, ".gitignore");
124811
- const gitignoreContent = await fs11.readFile(gitignorePath, "utf8");
125280
+ const gitignorePath = path18.join(projectPath, ".gitignore");
125281
+ const gitignoreContent = await fs12.readFile(gitignorePath, "utf8");
124812
125282
  const rules = gitignoreContent.split(`
124813
125283
  `).map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
124814
125284
  ig.add(rules);
@@ -126163,8 +126633,8 @@ function rustUseLeaves(node, source, prefix = []) {
126163
126633
  }
126164
126634
  if (node.type === "use_wildcard")
126165
126635
  return [{ path: [...prefix, "*"], glob: true }];
126166
- const path17 = rustPathSegments(node, source);
126167
- return path17.length ? [{ path: [...prefix, ...path17] }] : [];
126636
+ const path19 = rustPathSegments(node, source);
126637
+ return path19.length ? [{ path: [...prefix, ...path19] }] : [];
126168
126638
  }
126169
126639
  function functionalCaptures(captures, source, family) {
126170
126640
  if (family !== "clojure")
@@ -127136,8 +127606,8 @@ var init_structural_runtime = __esm(() => {
127136
127606
  });
127137
127607
 
127138
127608
  // ../../packages/core/dist/services/etl/stages/parse.js
127139
- import path17 from "path";
127140
- import fs12 from "fs/promises";
127609
+ import path19 from "path";
127610
+ import fs13 from "fs/promises";
127141
127611
  function resolveChunkerMaxChars() {
127142
127612
  const global2 = Number(process.env.EMBEDDING_MAX_CHARS);
127143
127613
  if (Number.isFinite(global2) && global2 > 0)
@@ -127165,8 +127635,8 @@ class ParseStage {
127165
127635
  const results = new Map;
127166
127636
  let processed = 0;
127167
127637
  const phases = [
127168
- files.filter((file2) => path17.extname(file2.relativePath).toLowerCase() !== ".h"),
127169
- files.filter((file2) => path17.extname(file2.relativePath).toLowerCase() === ".h")
127638
+ files.filter((file2) => path19.extname(file2.relativePath).toLowerCase() !== ".h"),
127639
+ files.filter((file2) => path19.extname(file2.relativePath).toLowerCase() === ".h")
127170
127640
  ];
127171
127641
  const batches = phases.flatMap((phase) => Array.from({ length: Math.ceil(phase.length / BATCH_SIZE) }, (_, index) => phase.slice(index * BATCH_SIZE, (index + 1) * BATCH_SIZE)));
127172
127642
  for (const batch of batches) {
@@ -127204,19 +127674,19 @@ class ParseStage {
127204
127674
  return files.map((file2) => results.get(file2.relativePath));
127205
127675
  }
127206
127676
  recordHeaderImporterEvidence(ctx, files, parsedFiles) {
127207
- const knownHeaders = new Set(files.filter((file2) => path17.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path17.posix.normalize(file2.relativePath)));
127677
+ const knownHeaders = new Set(files.filter((file2) => path19.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path19.posix.normalize(file2.relativePath)));
127208
127678
  const mutable = {
127209
127679
  ...ctx.structuralHeaderEvidenceByFile
127210
127680
  };
127211
127681
  for (const parsed of parsedFiles) {
127212
- const extension = path17.extname(parsed.file.relativePath).toLowerCase();
127682
+ const extension = path19.extname(parsed.file.relativePath).toLowerCase();
127213
127683
  const key = extension === ".c" ? "cImporters" : [".cpp", ".hpp"].includes(extension) ? "cppImporters" : undefined;
127214
127684
  if (!key)
127215
127685
  continue;
127216
127686
  for (const imported of parsed.rawImports) {
127217
127687
  if (!["c_include", "cpp_include"].includes(imported.form) || imported.specifier.startsWith("<"))
127218
127688
  continue;
127219
- const header = path17.posix.normalize(path17.posix.join(path17.posix.dirname(parsed.file.relativePath), imported.specifier));
127689
+ const header = path19.posix.normalize(path19.posix.join(path19.posix.dirname(parsed.file.relativePath), imported.specifier));
127220
127690
  if (!knownHeaders.has(header))
127221
127691
  continue;
127222
127692
  const existing = mutable[header] ?? {};
@@ -127227,9 +127697,9 @@ class ParseStage {
127227
127697
  }
127228
127698
  async parseFile(ctx, file2) {
127229
127699
  if (!file2.needsReparse) {
127230
- const extension = path17.extname(file2.relativePath).toLowerCase();
127700
+ const extension = path19.extname(file2.relativePath).toLowerCase();
127231
127701
  if ([".c", ".cpp", ".hpp"].includes(extension)) {
127232
- const content = file2.snapshotContent ?? await fs12.readFile(file2.absolutePath, "utf8");
127702
+ const content = file2.snapshotContent ?? await fs13.readFile(file2.absolutePath, "utf8");
127233
127703
  const outcome = await this.runtime.parse({ extension, source: Buffer.from(content) });
127234
127704
  if (outcome.status === "failed")
127235
127705
  throw new StructuralEtlParseError(file2.relativePath, outcome.failureKind, `Structural evidence parse failed (${outcome.failureKind})`, outcome.diagnosticCount, outcome.diagnostics.slice(0, 10));
@@ -127241,8 +127711,8 @@ class ParseStage {
127241
127711
  return { file: file2, chunks: [], symbols: [], rawImports: [], rawEdges: [] };
127242
127712
  }
127243
127713
  try {
127244
- const content = file2.snapshotContent ?? await fs12.readFile(file2.absolutePath, "utf-8");
127245
- const ext2 = path17.extname(file2.relativePath).toLowerCase();
127714
+ const content = file2.snapshotContent ?? await fs13.readFile(file2.absolutePath, "utf-8");
127715
+ const ext2 = path19.extname(file2.relativePath).toLowerCase();
127246
127716
  const chunkerMaxChars = resolveChunkerMaxChars();
127247
127717
  const chunks = smartChunk(content, file2.relativePath, chunkerMaxChars ? { maxChunkChars: chunkerMaxChars } : {});
127248
127718
  let symbols;
@@ -127796,7 +128266,7 @@ var init_resolver = __esm(() => {
127796
128266
  });
127797
128267
 
127798
128268
  // ../../packages/core/dist/services/structural/resolvers/typescript.js
127799
- import path18 from "path";
128269
+ import path20 from "path";
127800
128270
  function candidates(identities) {
127801
128271
  return Object.freeze(identities.map((identity) => Object.freeze({
127802
128272
  fqn: identity.fqn,
@@ -127891,7 +128361,7 @@ function probe(base, known, dialect = "typescript") {
127891
128361
  const bases = /\.[cm]?jsx?$/u.test(base) ? [base.replace(/\.[cm]?jsx?$/u, ".ts"), base.replace(/\.[cm]?jsx?$/u, ".tsx"), base] : [base];
127892
128362
  for (const candidateBase of bases)
127893
128363
  for (const suffix of DIALECT_PROBES[dialect] ?? [""]) {
127894
- const value = path18.posix.normalize(`${candidateBase}${suffix}`);
128364
+ const value = path20.posix.normalize(`${candidateBase}${suffix}`);
127895
128365
  if (!value.startsWith("../") && value !== ".." && known.has(value))
127896
128366
  return value;
127897
128367
  }
@@ -127900,7 +128370,7 @@ function probe(base, known, dialect = "typescript") {
127900
128370
  function resolveStructuralSpecifier(specifier, fromFile, build, dialect = "typescript") {
127901
128371
  const known = new Set(build.knownFiles.map(normalizeStructuralFile));
127902
128372
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
127903
- return probe(path18.posix.join(path18.posix.dirname(fromFile), specifier), known, dialect);
128373
+ return probe(path20.posix.join(path20.posix.dirname(fromFile), specifier), known, dialect);
127904
128374
  }
127905
128375
  const aliases = build.pathAliasesByFile?.[normalizeStructuralFile(fromFile)] ?? build.pathAliases ?? [];
127906
128376
  for (const alias of aliases) {
@@ -128164,7 +128634,7 @@ var init_scripting2 = __esm(() => {
128164
128634
  });
128165
128635
 
128166
128636
  // ../../packages/core/dist/services/structural/resolvers/systems.js
128167
- import path19 from "path";
128637
+ import path21 from "path";
128168
128638
  var DIALECTS, SYSTEMS_LANGUAGE_RESOLVER;
128169
128639
  var init_systems2 = __esm(() => {
128170
128640
  init_typescript2();
@@ -128183,7 +128653,7 @@ var init_systems2 = __esm(() => {
128183
128653
  const bindings = item.bindings.map((binding) => binding.imported === "*" && binding.local === "*" && unresolvedTarget && !unresolvedTarget.qualifier ? { ...binding, imported: unresolvedTarget.name, local: unresolvedTarget.name } : binding);
128184
128654
  if (item.specifier === "crate" || item.specifier.startsWith("crate/")) {
128185
128655
  const crateRoot = file2.file.startsWith("src/") ? "src" : "";
128186
- return { ...item, bindings, specifier: `./${path19.posix.relative(path19.posix.dirname(file2.file), path19.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
128656
+ return { ...item, bindings, specifier: `./${path21.posix.relative(path21.posix.dirname(file2.file), path21.posix.join(crateRoot, item.specifier.replace(/^crate\/?/u, "")))}` };
128187
128657
  }
128188
128658
  if (item.specifier === "self" || item.specifier.startsWith("self/"))
128189
128659
  return { ...item, bindings, specifier: `./${item.specifier.replace(/^self\/?/u, "")}` };
@@ -128281,8 +128751,8 @@ var init_data_document2 = __esm(() => {
128281
128751
  });
128282
128752
 
128283
128753
  // ../../packages/core/dist/services/etl/stages/resolve.js
128284
- import path20 from "path";
128285
- import fs13 from "fs";
128754
+ import path22 from "path";
128755
+ import fs14 from "fs";
128286
128756
 
128287
128757
  class ResolveStage {
128288
128758
  symbolRepository;
@@ -128306,7 +128776,7 @@ class ResolveStage {
128306
128776
  const structuralDocuments = files.flatMap((file2) => {
128307
128777
  if (!file2.structure)
128308
128778
  return [];
128309
- const language = resolveStructuralLanguage(path20.extname(file2.file.relativePath));
128779
+ const language = resolveStructuralLanguage(path22.extname(file2.file.relativePath));
128310
128780
  if (language.status !== "supported")
128311
128781
  throw new Error(`structural_manifest_missing:${file2.file.relativePath}`);
128312
128782
  return [{
@@ -128318,13 +128788,13 @@ class ResolveStage {
128318
128788
  }];
128319
128789
  });
128320
128790
  const currentStructuralFiles = new Set(structuralDocuments.map((document2) => document2.file));
128321
- const skippedStructuralFiles = new Set(files.filter((item) => !item.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path20.extname(item.file.relativePath).toLowerCase())).map((item) => item.file.relativePath));
128791
+ 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));
128322
128792
  const pathAliasesByFile = Object.fromEntries([...knownRelPaths].map((file2) => [
128323
128793
  file2,
128324
128794
  this.structuralAliasesFor(file2, rootAliases, monorepoPackages)
128325
128795
  ]));
128326
128796
  const buildMetadata = { knownFiles: [...knownRelPaths], pathAliasesByFile };
128327
- const seedRows = repositoryDefinitions.filter((definition) => STRUCTURAL_SEED_EXTENSIONS.has(path20.extname(definition.file_path).toLowerCase())).filter((definition) => knownRelPaths.has(definition.file_path) && skippedStructuralFiles.has(definition.file_path)).filter((definition) => !currentStructuralFiles.has(definition.file_path));
128797
+ 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));
128328
128798
  const seedIds = new Set;
128329
128799
  for (const definition of seedRows) {
128330
128800
  if (seedIds.has(definition.id))
@@ -128417,7 +128887,7 @@ class ResolveStage {
128417
128887
  if (parsed.file !== definition.file_path) {
128418
128888
  throw new Error(`structural_repository_seed_file_mismatch:${definition.id}`);
128419
128889
  }
128420
- const language = resolveStructuralLanguage(path20.extname(definition.file_path));
128890
+ const language = resolveStructuralLanguage(path22.extname(definition.file_path));
128421
128891
  if (language.status !== "supported")
128422
128892
  throw new Error(`structural_repository_seed_language:${definition.id}`);
128423
128893
  let identity;
@@ -128469,7 +128939,7 @@ class ResolveStage {
128469
128939
  });
128470
128940
  }
128471
128941
  resolveFile(parsed, projectPath, knownRelPaths, rootAliases, monorepoPackages, symbolIndex, knownFqns) {
128472
- const fromDir = path20.dirname(path20.join(projectPath, parsed.file.relativePath));
128942
+ const fromDir = path22.dirname(path22.join(projectPath, parsed.file.relativePath));
128473
128943
  const packageAliases = this.getPackageAliases(parsed.file.relativePath, monorepoPackages);
128474
128944
  const allAliases = [...packageAliases, ...rootAliases];
128475
128945
  const resolvedImports = parsed.rawImports.map((raw2) => {
@@ -128540,7 +129010,7 @@ class ResolveStage {
128540
129010
  index.set(def.name, `${def.file_path}#${def.name}`);
128541
129011
  }
128542
129012
  } catch (err) {
128543
- const skippedStructural = files.some((file2) => !file2.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path20.extname(file2.file.relativePath).toLowerCase()));
129013
+ const skippedStructural = files.some((file2) => !file2.file.needsReparse && STRUCTURAL_SEED_EXTENSIONS.has(path22.extname(file2.file.relativePath).toLowerCase()));
128544
129014
  if (skippedStructural)
128545
129015
  throw new Error("structural_repository_seed_failed", { cause: err });
128546
129016
  logger.warn("buildSymbolIndex: repo seed failed, in-batch only", {
@@ -128564,7 +129034,7 @@ class ResolveStage {
128564
129034
  }
128565
129035
  resolveSpecifier(specifier, fromDir, projectPath, knownRelPaths, aliases) {
128566
129036
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
128567
- const resolved = this.probeExtensions(path20.resolve(fromDir, specifier), projectPath, knownRelPaths);
129037
+ const resolved = this.probeExtensions(path22.resolve(fromDir, specifier), projectPath, knownRelPaths);
128568
129038
  return { resolvedPath: resolved, external: false };
128569
129039
  }
128570
129040
  for (const alias of aliases) {
@@ -128572,8 +129042,8 @@ class ResolveStage {
128572
129042
  const suffix = specifier.slice(alias.prefix.length);
128573
129043
  for (const target of alias.targets) {
128574
129044
  const cleanTarget = target.replace(/\/\*$/, "");
128575
- const basePath = alias.packagePath ? path20.join(projectPath, alias.packagePath) : projectPath;
128576
- const absPath = path20.join(basePath, cleanTarget + suffix);
129045
+ const basePath = alias.packagePath ? path22.join(projectPath, alias.packagePath) : projectPath;
129046
+ const absPath = path22.join(basePath, cleanTarget + suffix);
128577
129047
  const resolved = this.probeExtensions(absPath, projectPath, knownRelPaths);
128578
129048
  if (resolved)
128579
129049
  return { resolvedPath: resolved, external: false };
@@ -128589,7 +129059,7 @@ class ResolveStage {
128589
129059
  ...TS_EXTENSIONS.map((ext2) => absPath.replace(/\.[^.]+$/, ext2))
128590
129060
  ];
128591
129061
  for (const candidate2 of candidates2) {
128592
- const rel = path20.relative(projectPath, candidate2).replace(/\\/g, "/");
129062
+ const rel = path22.relative(projectPath, candidate2).replace(/\\/g, "/");
128593
129063
  if (knownRelPaths.has(rel))
128594
129064
  return rel;
128595
129065
  }
@@ -128597,9 +129067,9 @@ class ResolveStage {
128597
129067
  }
128598
129068
  loadTsConfigPaths(projectPath, packageBase) {
128599
129069
  const aliases = [];
128600
- const tsconfigPath = path20.join(projectPath, "tsconfig.json");
129070
+ const tsconfigPath = path22.join(projectPath, "tsconfig.json");
128601
129071
  try {
128602
- const raw2 = fs13.readFileSync(tsconfigPath, "utf-8");
129072
+ const raw2 = fs14.readFileSync(tsconfigPath, "utf-8");
128603
129073
  const stripped = raw2.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
128604
129074
  const tsconfig = JSON.parse(stripped);
128605
129075
  const paths = tsconfig?.compilerOptions?.paths ?? {};
@@ -128628,7 +129098,7 @@ class ResolveStage {
128628
129098
  }
128629
129099
  }
128630
129100
  for (const packageRelPath of packagePaths) {
128631
- const absPackagePath = path20.join(projectPath, packageRelPath);
129101
+ const absPackagePath = path22.join(projectPath, packageRelPath);
128632
129102
  const aliases = this.loadTsConfigPaths(absPackagePath, packageRelPath);
128633
129103
  if (aliases.length > 0) {
128634
129104
  packages.push({
@@ -128658,7 +129128,7 @@ class ResolveStage {
128658
129128
  structuralAliasesFor(filePath, rootAliases, packages) {
128659
129129
  return [...this.getPackageAliases(filePath, packages), ...rootAliases].map((alias) => ({
128660
129130
  pattern: alias.prefix + (alias.targets.some((target) => target.includes("*")) ? "/*" : ""),
128661
- targets: alias.targets.map((target) => alias.packagePath ? path20.posix.join(alias.packagePath, target) : target)
129131
+ targets: alias.targets.map((target) => alias.packagePath ? path22.posix.join(alias.packagePath, target) : target)
128662
129132
  }));
128663
129133
  }
128664
129134
  }
@@ -128722,7 +129192,7 @@ var init_with_deadlock_retry = __esm(() => {
128722
129192
  });
128723
129193
 
128724
129194
  // ../../packages/core/dist/services/etl/stages/load.js
128725
- import path21 from "path";
129195
+ import path23 from "path";
128726
129196
  function formatDuration(ms) {
128727
129197
  const totalSec = Math.max(0, Math.round(ms / 1000));
128728
129198
  if (totalSec < 60)
@@ -128999,7 +129469,7 @@ class LoadStage {
128999
129469
  const filePath = file2.file.relativePath;
129000
129470
  const batch = buildSymbolPersistenceBatch(ctx.projectId, file2);
129001
129471
  if (ctx.graphGenerationLease) {
129002
- const manifest = getLanguageManifestEntry(path21.extname(filePath));
129472
+ const manifest = getLanguageManifestEntry(path23.extname(filePath));
129003
129473
  const diagnostics2 = (file2.structuralDiagnostics ?? []).slice(0, 10).map((diagnostic2) => ({
129004
129474
  code: diagnostic2.code,
129005
129475
  severity: diagnostic2.severity,
@@ -129456,9 +129926,9 @@ var init_graph_generation_coordinator = __esm(() => {
129456
129926
  // ../../packages/core/dist/services/etl/pipeline.js
129457
129927
  import { createHash as createHash7 } from "crypto";
129458
129928
  import { setTimeout as delay2 } from "timers/promises";
129459
- import path22 from "path";
129929
+ import path24 from "path";
129460
129930
  function buildHeaderLanguageEvidence(files) {
129461
- const headers = new Set(files.filter((file2) => path22.posix.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path22.posix.normalize(file2.relativePath)));
129931
+ const headers = new Set(files.filter((file2) => path24.posix.extname(file2.relativePath).toLowerCase() === ".h").map((file2) => path24.posix.normalize(file2.relativePath)));
129462
129932
  const mutable = new Map;
129463
129933
  const entry2 = (header) => {
129464
129934
  let value = mutable.get(header);
@@ -129469,7 +129939,7 @@ function buildHeaderLanguageEvidence(files) {
129469
129939
  return value;
129470
129940
  };
129471
129941
  for (const file2 of files) {
129472
- if (path22.posix.basename(file2.relativePath) !== "compile_commands.json" || file2.snapshotContent === undefined)
129942
+ if (path24.posix.basename(file2.relativePath) !== "compile_commands.json" || file2.snapshotContent === undefined)
129473
129943
  continue;
129474
129944
  let commands;
129475
129945
  try {
@@ -129485,11 +129955,11 @@ function buildHeaderLanguageEvidence(files) {
129485
129955
  const record3 = command;
129486
129956
  if (typeof record3.file !== "string")
129487
129957
  continue;
129488
- const projectRoot = path22.resolve(file2.absolutePath, ...file2.relativePath.split("/").map(() => ".."));
129489
- const commandDirectory = typeof record3.directory === "string" ? path22.resolve(projectRoot, record3.directory) : projectRoot;
129490
- const absoluteInput = path22.resolve(commandDirectory, record3.file);
129491
- const relative2 = path22.relative(projectRoot, absoluteInput);
129492
- const header = path22.posix.normalize(relative2.replaceAll(path22.sep, "/"));
129958
+ const projectRoot = path24.resolve(file2.absolutePath, ...file2.relativePath.split("/").map(() => ".."));
129959
+ const commandDirectory = typeof record3.directory === "string" ? path24.resolve(projectRoot, record3.directory) : projectRoot;
129960
+ const absoluteInput = path24.resolve(commandDirectory, record3.file);
129961
+ const relative2 = path24.relative(projectRoot, absoluteInput);
129962
+ const header = path24.posix.normalize(relative2.replaceAll(path24.sep, "/"));
129493
129963
  if (!headers.has(header))
129494
129964
  continue;
129495
129965
  const invocation = typeof record3.command === "string" ? record3.command : Array.isArray(record3.arguments) ? record3.arguments.join(" ") : "";
@@ -130020,9 +130490,9 @@ var init_acquire_indexing_lease = __esm(() => {
130020
130490
 
130021
130491
  // ../../packages/core/dist/services/project-identity/project-root-identity.js
130022
130492
  import { realpath as realpath2 } from "fs/promises";
130023
- import path23 from "path";
130493
+ import path25 from "path";
130024
130494
  async function canonicalizeProjectRoot(projectPath, canonicalize = realpath2) {
130025
- return canonicalize(path23.resolve(projectPath));
130495
+ return canonicalize(path25.resolve(projectPath));
130026
130496
  }
130027
130497
  async function assertProjectRootReuse(options) {
130028
130498
  if (!options.storedProjectPath || options.forceReindex)
@@ -130030,9 +130500,9 @@ async function assertProjectRootReuse(options) {
130030
130500
  const canonicalize = options.canonicalize ?? realpath2;
130031
130501
  let storedCanonical;
130032
130502
  try {
130033
- storedCanonical = await canonicalize(path23.resolve(options.storedProjectPath));
130503
+ storedCanonical = await canonicalize(path25.resolve(options.storedProjectPath));
130034
130504
  } catch {
130035
- storedCanonical = path23.resolve(options.storedProjectPath);
130505
+ storedCanonical = path25.resolve(options.storedProjectPath);
130036
130506
  }
130037
130507
  if (storedCanonical !== options.canonicalProjectPath) {
130038
130508
  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");
@@ -130775,16 +131245,16 @@ function detectRoutes(httpEdges, defs, opts = {}) {
130775
131245
  const seen = new Set;
130776
131246
  const out = [];
130777
131247
  for (const e of httpEdges) {
130778
- const path24 = e.route;
130779
- if (!path24)
131248
+ const path26 = e.route;
131249
+ if (!path26)
130780
131250
  continue;
130781
131251
  const method = (e.method ?? "ANY").toUpperCase();
130782
- const key = method + " " + path24;
131252
+ const key = method + " " + path26;
130783
131253
  if (seen.has(key))
130784
131254
  continue;
130785
131255
  seen.add(key);
130786
131256
  out.push({
130787
- path: path24,
131257
+ path: path26,
130788
131258
  method: e.method,
130789
131259
  file: e.fromFile,
130790
131260
  handler: e.targetFqn ?? e.symbolName
@@ -130795,12 +131265,12 @@ function detectRoutes(httpEdges, defs, opts = {}) {
130795
131265
  continue;
130796
131266
  const parsed = parseRouteName(d.name);
130797
131267
  const method = parsed?.method ?? "ANY";
130798
- const path24 = parsed?.path ?? d.name;
130799
- const key = method + " " + path24;
131268
+ const path26 = parsed?.path ?? d.name;
131269
+ const key = method + " " + path26;
130800
131270
  if (seen.has(key))
130801
131271
  continue;
130802
131272
  seen.add(key);
130803
- out.push({ path: path24, method: parsed?.method, file: d.filePath, handler: d.name });
131273
+ out.push({ path: path26, method: parsed?.method, file: d.filePath, handler: d.name });
130804
131274
  }
130805
131275
  for (const d of defs) {
130806
131276
  const parsed = parseRouteName(d.name);
@@ -131021,8 +131491,8 @@ __export(exports_symbol_graph_service, {
131021
131491
  symbolGraphService: () => symbolGraphService,
131022
131492
  SymbolGraphService: () => SymbolGraphService
131023
131493
  });
131024
- import path24 from "path";
131025
- import fs14 from "fs/promises";
131494
+ import path26 from "path";
131495
+ import fs15 from "fs/promises";
131026
131496
 
131027
131497
  class SymbolGraphService {
131028
131498
  identityLookup;
@@ -131350,7 +131820,7 @@ class SymbolGraphService {
131350
131820
  async readSnippet(relativePath, lineStart, lineEnd, projectId) {
131351
131821
  try {
131352
131822
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
131353
- const content = await fs14.readFile(absolutePath, "utf-8");
131823
+ const content = await fs15.readFile(absolutePath, "utf-8");
131354
131824
  const lines = content.split(`
131355
131825
  `);
131356
131826
  return lines.slice(Math.max(0, lineStart - 1), Math.min(lines.length, lineEnd)).join(`
@@ -131362,7 +131832,7 @@ class SymbolGraphService {
131362
131832
  async readContext(relativePath, lineNumber, contextLines, projectId) {
131363
131833
  try {
131364
131834
  const absolutePath = await this.resolveToAbsolute(relativePath, projectId);
131365
- const content = await fs14.readFile(absolutePath, "utf-8");
131835
+ const content = await fs15.readFile(absolutePath, "utf-8");
131366
131836
  const lines = content.split(`
131367
131837
  `);
131368
131838
  const start = Math.max(0, lineNumber - contextLines - 1);
@@ -131375,7 +131845,7 @@ class SymbolGraphService {
131375
131845
  }
131376
131846
  async resolveToAbsolute(relativePath, projectId) {
131377
131847
  const root = await this.getProjectRoot(projectId);
131378
- return root ? path24.resolve(root, relativePath) : relativePath;
131848
+ return root ? path26.resolve(root, relativePath) : relativePath;
131379
131849
  }
131380
131850
  async getProjectRoot(projectId) {
131381
131851
  const cached2 = this.projectRootCache.get(projectId);
@@ -131518,7 +131988,7 @@ var init_workspace_manager = __esm(() => {
131518
131988
  });
131519
131989
 
131520
131990
  // ../../packages/core/dist/tools/index_project.js
131521
- import path25 from "path";
131991
+ import path27 from "path";
131522
131992
 
131523
131993
  class IndexProjectTool {
131524
131994
  name = "index_project";
@@ -131566,7 +132036,7 @@ class IndexProjectTool {
131566
132036
  try {
131567
132037
  await assertParserReadyForIndexing();
131568
132038
  const canonicalProjectPath = await canonicalizeProjectRoot(projectPath);
131569
- const finalProjectId = projectId || path25.basename(canonicalProjectPath) || "default";
132039
+ const finalProjectId = projectId || path27.basename(canonicalProjectPath) || "default";
131570
132040
  const existing = await workspaceManager.getWorkspace(finalProjectId);
131571
132041
  await assertProjectRootReuse({
131572
132042
  projectId: finalProjectId,
@@ -132119,17 +132589,17 @@ function applyReplacer(root, replacer) {
132119
132589
  return transformChildren(root, replacer, []);
132120
132590
  return transformChildren(normalizeValue(replacedRoot), replacer, []);
132121
132591
  }
132122
- function transformChildren(value, replacer, path26) {
132592
+ function transformChildren(value, replacer, path28) {
132123
132593
  if (isJsonObject(value))
132124
- return transformObject(value, replacer, path26);
132594
+ return transformObject(value, replacer, path28);
132125
132595
  if (isJsonArray(value))
132126
- return transformArray(value, replacer, path26);
132596
+ return transformArray(value, replacer, path28);
132127
132597
  return value;
132128
132598
  }
132129
- function transformObject(obj, replacer, path26) {
132599
+ function transformObject(obj, replacer, path28) {
132130
132600
  const result = {};
132131
132601
  for (const [key, value] of Object.entries(obj)) {
132132
- const childPath = [...path26, key];
132602
+ const childPath = [...path28, key];
132133
132603
  const replacedValue = replacer(key, value, childPath);
132134
132604
  if (replacedValue === undefined)
132135
132605
  continue;
@@ -132137,11 +132607,11 @@ function transformObject(obj, replacer, path26) {
132137
132607
  }
132138
132608
  return result;
132139
132609
  }
132140
- function transformArray(arr, replacer, path26) {
132610
+ function transformArray(arr, replacer, path28) {
132141
132611
  const result = [];
132142
132612
  for (let i = 0;i < arr.length; i++) {
132143
132613
  const value = arr[i];
132144
- const childPath = [...path26, i];
132614
+ const childPath = [...path28, i];
132145
132615
  const replacedValue = replacer(String(i), value, childPath);
132146
132616
  if (replacedValue === undefined)
132147
132617
  continue;
@@ -137211,9 +137681,9 @@ var init_session_pin_store = __esm(() => {
137211
137681
  });
137212
137682
 
137213
137683
  // ../../packages/core/dist/services/hooks/attribution-resolver.js
137214
- import fs15 from "fs";
137215
- import os6 from "os";
137216
- import path26 from "path";
137684
+ import fs16 from "fs";
137685
+ import os8 from "os";
137686
+ import path28 from "path";
137217
137687
 
137218
137688
  class PgWorkspaceRootProvider {
137219
137689
  cache = null;
@@ -137262,8 +137732,8 @@ class AttributionResolver {
137262
137732
  this.aliasResolver = options.aliasResolver ?? getProjectIdentityAliasResolver();
137263
137733
  this.pins = options.pins ?? new SessionPinStore;
137264
137734
  this.canonicalize = options.canonicalize ?? defaultCanonicalize;
137265
- this.homedir = options.homedir ?? os6.homedir;
137266
- this.fsRoot = options.fsRoot ?? (() => path26.parse(path26.sep).root);
137735
+ this.homedir = options.homedir ?? os8.homedir;
137736
+ this.fsRoot = options.fsRoot ?? (() => path28.parse(path28.sep).root);
137267
137737
  }
137268
137738
  async resolve(input) {
137269
137739
  const caller = input.callerProjectId;
@@ -137314,7 +137784,7 @@ class AttributionResolver {
137314
137784
  }
137315
137785
  let bestPath = null;
137316
137786
  for (const candidate2 of byPath.keys()) {
137317
- if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path26.sep) ? candidate2 : candidate2 + path26.sep)) {
137787
+ if (canonicalCwd === candidate2 || canonicalCwd.startsWith(candidate2.endsWith(path28.sep) ? candidate2 : candidate2 + path28.sep)) {
137318
137788
  if (bestPath === null || candidate2.length > bestPath.length) {
137319
137789
  bestPath = candidate2;
137320
137790
  }
@@ -137337,7 +137807,7 @@ class AttributionResolver {
137337
137807
  return projectPath2;
137338
137808
  const fsRoot = this.fsRoot();
137339
137809
  let normalized = projectPath2;
137340
- while (normalized.length > fsRoot.length && normalized.endsWith(path26.sep)) {
137810
+ while (normalized.length > fsRoot.length && normalized.endsWith(path28.sep)) {
137341
137811
  normalized = normalized.slice(0, -1);
137342
137812
  }
137343
137813
  return normalized;
@@ -137345,10 +137815,10 @@ class AttributionResolver {
137345
137815
  }
137346
137816
  function defaultCanonicalize(cwd) {
137347
137817
  try {
137348
- return fs15.realpathSync(cwd);
137818
+ return fs16.realpathSync(cwd);
137349
137819
  } catch {
137350
137820
  try {
137351
- return path26.resolve(cwd);
137821
+ return path28.resolve(cwd);
137352
137822
  } catch {
137353
137823
  return;
137354
137824
  }
@@ -138096,31 +138566,31 @@ class TracePathService {
138096
138566
  const chains = [];
138097
138567
  const seen = new Set;
138098
138568
  let walks = 0;
138099
- const walk = (fqn, path27) => {
138569
+ const walk = (fqn, path29) => {
138100
138570
  if (chains.length >= CHAIN_CAP)
138101
138571
  return;
138102
138572
  if (walks >= MAX_WALKS)
138103
138573
  return;
138104
138574
  walks++;
138105
- const key = path27.join("\u2192");
138575
+ const key = path29.join("\u2192");
138106
138576
  if (seen.has(key))
138107
138577
  return;
138108
138578
  seen.add(key);
138109
138579
  const next = adj.get(fqn);
138110
138580
  if (!next || next.length === 0 || !whoHasChild.has(fqn)) {
138111
- if (path27.length > 1)
138112
- chains.push(path27.map((n) => this.fqnToName(n)).join(" \u2192 "));
138581
+ if (path29.length > 1)
138582
+ chains.push(path29.map((n) => this.fqnToName(n)).join(" \u2192 "));
138113
138583
  return;
138114
138584
  }
138115
138585
  for (const child of next) {
138116
138586
  if (chains.length >= CHAIN_CAP || walks >= MAX_WALKS)
138117
138587
  return;
138118
- if (path27.includes(child)) {
138119
- const cycled = [...path27, `${this.fqnToName(child)}\u21BA`];
138588
+ if (path29.includes(child)) {
138589
+ const cycled = [...path29, `${this.fqnToName(child)}\u21BA`];
138120
138590
  chains.push(cycled.map((n) => n).join(" \u2192 "));
138121
138591
  continue;
138122
138592
  }
138123
- walk(child, [...path27, child]);
138593
+ walk(child, [...path29, child]);
138124
138594
  }
138125
138595
  };
138126
138596
  for (const seed of seeds) {
@@ -138953,7 +139423,7 @@ var init_get_architecture = __esm(() => {
138953
139423
  });
138954
139424
 
138955
139425
  // ../../packages/core/dist/services/file-read/file-content-cache.js
138956
- import fs16 from "fs/promises";
139426
+ import fs17 from "fs/promises";
138957
139427
 
138958
139428
  class FileContentCache {
138959
139429
  extractMetadata;
@@ -138986,7 +139456,7 @@ class FileContentCache {
138986
139456
  metadata: cached2.metadata
138987
139457
  };
138988
139458
  }
138989
- const content = await fs16.readFile(filePath, "utf-8");
139459
+ const content = await fs17.readFile(filePath, "utf-8");
138990
139460
  const metadata = await this.extractMetadata(content, filePath, options);
138991
139461
  evictOldest(this.fileCache, this.FILE_CACHE_MAX_ENTRIES - 1);
138992
139462
  this.fileCache.set(cacheKey, {
@@ -139003,7 +139473,7 @@ var init_file_content_cache = __esm(() => {
139003
139473
  });
139004
139474
 
139005
139475
  // ../../packages/core/dist/services/file-read/file-metadata.js
139006
- import path27 from "path";
139476
+ import path29 from "path";
139007
139477
 
139008
139478
  class FileMetadataExtractor {
139009
139479
  symbolGraph;
@@ -139039,7 +139509,7 @@ class FileMetadataExtractor {
139039
139509
  return metadata;
139040
139510
  }
139041
139511
  detectLanguage(filePath) {
139042
- const ext2 = path27.extname(filePath).toLowerCase();
139512
+ const ext2 = path29.extname(filePath).toLowerCase();
139043
139513
  const languageMap2 = {
139044
139514
  ".ts": "TypeScript",
139045
139515
  ".tsx": "TypeScript",
@@ -139161,7 +139631,7 @@ var init_line_range = __esm(() => {
139161
139631
  });
139162
139632
 
139163
139633
  // ../../packages/core/dist/services/file-read/path-containment.js
139164
- import path28 from "path";
139634
+ import path30 from "path";
139165
139635
 
139166
139636
  class PathContainment {
139167
139637
  projectRoots;
@@ -139169,14 +139639,14 @@ class PathContainment {
139169
139639
  this.projectRoots = projectRoots;
139170
139640
  }
139171
139641
  async resolveFilePath(filePath, projectId) {
139172
- if (path28.isAbsolute(filePath)) {
139173
- return path28.resolve(filePath);
139642
+ if (path30.isAbsolute(filePath)) {
139643
+ return path30.resolve(filePath);
139174
139644
  }
139175
139645
  if (projectId) {
139176
139646
  const root = await this.projectRoots.getProjectRoot(projectId);
139177
139647
  if (root) {
139178
139648
  const cleaned = sanitizeFilePath(filePath);
139179
- return path28.resolve(root, cleaned);
139649
+ return path30.resolve(root, cleaned);
139180
139650
  }
139181
139651
  return null;
139182
139652
  }
@@ -139187,17 +139657,17 @@ class PathContainment {
139187
139657
  if (projectId) {
139188
139658
  const root = await this.projectRoots.getProjectRoot(projectId);
139189
139659
  if (root)
139190
- roots.push(path28.resolve(root));
139660
+ roots.push(path30.resolve(root));
139191
139661
  }
139192
- roots.push(path28.resolve(process.cwd()));
139662
+ roots.push(path30.resolve(process.cwd()));
139193
139663
  const envRoots = (process.env.MASSA_AI_READ_FILE_ROOTS ?? "").split(":").map((s) => s.trim()).filter((s) => s.length > 0);
139194
139664
  for (const extra of envRoots) {
139195
- roots.push(path28.resolve(extra));
139665
+ roots.push(path30.resolve(extra));
139196
139666
  }
139197
- const target = path28.resolve(absoluteFilePath);
139667
+ const target = path30.resolve(absoluteFilePath);
139198
139668
  for (const root of roots) {
139199
- const rel = path28.relative(root, target);
139200
- if (rel !== "" && !rel.startsWith("..") && !path28.isAbsolute(rel)) {
139669
+ const rel = path30.relative(root, target);
139670
+ if (rel !== "" && !rel.startsWith("..") && !path30.isAbsolute(rel)) {
139201
139671
  return { allowed: true };
139202
139672
  }
139203
139673
  if (rel === "")
@@ -142411,9 +142881,9 @@ var init_l1_memory_cache = __esm(() => {
142411
142881
  });
142412
142882
 
142413
142883
  // ../../packages/core/dist/services/health/local-health-checker.js
142414
- import fs17 from "fs/promises";
142884
+ import fs18 from "fs/promises";
142415
142885
  import { existsSync as existsSync3 } from "fs";
142416
- import path29 from "path";
142886
+ import path31 from "path";
142417
142887
 
142418
142888
  class LocalHealthChecker {
142419
142889
  ollamaBaseUrl = process.env.OLLAMA_BASE_URL || "http://localhost:11434";
@@ -142447,10 +142917,10 @@ class LocalHealthChecker {
142447
142917
  const start = Date.now();
142448
142918
  try {
142449
142919
  if (!existsSync3(this.dataDir))
142450
- await fs17.mkdir(this.dataDir, { recursive: true });
142451
- const probe2 = path29.join(this.dataDir, ".health-check-test");
142452
- await fs17.writeFile(probe2, "ok");
142453
- await fs17.unlink(probe2);
142920
+ await fs18.mkdir(this.dataDir, { recursive: true });
142921
+ const probe2 = path31.join(this.dataDir, ".health-check-test");
142922
+ await fs18.writeFile(probe2, "ok");
142923
+ await fs18.unlink(probe2);
142454
142924
  return { available: true, latency: Date.now() - start, details: { path: this.dataDir, writable: true } };
142455
142925
  } catch (error51) {
142456
142926
  return { available: false, latency: Date.now() - start, error: `Data directory error: ${error51.message}` };
@@ -142846,10 +143316,18 @@ var init_scheduler_store_factory = __esm(() => {
142846
143316
  });
142847
143317
 
142848
143318
  // ../../packages/core/dist/services/scheduler/scheduler.js
142849
- function readEnabled() {
143319
+ function readEnabledEnv() {
142850
143320
  const raw2 = process.env.MASSA_AI_SCHEDULER_ENABLED;
143321
+ if (raw2 === undefined)
143322
+ return;
142851
143323
  return raw2 === "true" || raw2 === "1";
142852
143324
  }
143325
+ function envPositiveInt(raw2) {
143326
+ if (raw2 === undefined || raw2 === "")
143327
+ return;
143328
+ const parsed = parsePositiveIntEnv(raw2, NaN);
143329
+ return Number.isNaN(parsed) ? undefined : parsed;
143330
+ }
142853
143331
 
142854
143332
  class Scheduler {
142855
143333
  store;
@@ -142863,9 +143341,10 @@ class Scheduler {
142863
143341
  started = false;
142864
143342
  constructor(opts = {}) {
142865
143343
  this.store = opts.store ?? getScheduledJobStore();
142866
- this.tickIntervalMs = opts.tickIntervalMs ?? parsePositiveIntEnv(process.env.MASSA_AI_SCHEDULER_TICK_MS, DEFAULTS.tickMs);
142867
- this.maxConcurrent = opts.maxConcurrent ?? parsePositiveIntEnv(process.env.MASSA_AI_SCHEDULER_MAX_CONCURRENT, DEFAULTS.maxConcurrent);
142868
- this.enabled = opts.enabled ?? readEnabled();
143344
+ const schedulerConfig = config2.get("scheduler");
143345
+ this.tickIntervalMs = opts.tickIntervalMs ?? envPositiveInt(process.env.MASSA_AI_SCHEDULER_TICK_MS) ?? schedulerConfig?.tickMs ?? DEFAULTS.tickMs;
143346
+ this.maxConcurrent = opts.maxConcurrent ?? envPositiveInt(process.env.MASSA_AI_SCHEDULER_MAX_CONCURRENT) ?? schedulerConfig?.maxConcurrent ?? DEFAULTS.maxConcurrent;
143347
+ this.enabled = opts.enabled ?? readEnabledEnv() ?? schedulerConfig?.enabled ?? false;
142869
143348
  }
142870
143349
  registerHandler(jobKind, handler) {
142871
143350
  this.handlers.set(jobKind, handler);
@@ -144258,21 +144737,31 @@ var init_observation_consolidation_job = __esm(() => {
144258
144737
  });
144259
144738
 
144260
144739
  // ../../packages/core/dist/services/scheduler/scheduler-defaults.js
144261
- function envBool2(key, fallback) {
144740
+ function envBool2(key, fileValue, fallback) {
144262
144741
  const raw2 = process.env[key];
144263
144742
  if (raw2 === undefined)
144264
- return fallback;
144743
+ return fileValue ?? fallback;
144265
144744
  return raw2 === "true" || raw2 === "1";
144266
144745
  }
144267
- function envNum2(key, fallback) {
144746
+ function envNum2(key, fileValue, fallback) {
144268
144747
  const raw2 = process.env[key];
144269
- if (raw2 === undefined || raw2 === "")
144270
- return fallback;
144271
- const n = Number(raw2);
144272
- return Number.isFinite(n) && n > 0 ? n : fallback;
144748
+ if (raw2 !== undefined && raw2 !== "") {
144749
+ const n = Number(raw2);
144750
+ if (Number.isFinite(n) && n > 0)
144751
+ return n;
144752
+ }
144753
+ return fileValue ?? fallback;
144754
+ }
144755
+ function readFileSchedulerJobs() {
144756
+ try {
144757
+ const raw2 = loadRawUserConfig().scheduler?.jobs;
144758
+ return raw2;
144759
+ } catch {
144760
+ return;
144761
+ }
144273
144762
  }
144274
144763
  function applySafeDefaults(job) {
144275
- if (!envBool2("MASSA_AI_SCHEDULER_SAFE_DEFAULTS", false)) {
144764
+ if (!envBool2("MASSA_AI_SCHEDULER_SAFE_DEFAULTS", undefined, false)) {
144276
144765
  return job;
144277
144766
  }
144278
144767
  if (job.jobKind === "memory-consolidation") {
@@ -144319,10 +144808,12 @@ function registerDefaultJobs(scheduler) {
144319
144808
  const count = CheckpointManager2.getInstance().purgeExpired();
144320
144809
  logger.info("Scheduled checkpoint purge completed", { count });
144321
144810
  });
144811
+ const fileJobs = readFileSchedulerJobs();
144322
144812
  for (const rawDef of DEFAULT_SCHEDULED_JOBS) {
144323
144813
  const def = applySafeDefaults(rawDef);
144324
- const enabled2 = envBool2(def.enableEnvVar, def.defaultEnabled);
144325
- const intervalMs = envNum2(def.intervalEnvVar, def.schedule.intervalMs ?? THIRTY_MIN);
144814
+ const fileJob = fileJobs?.[def.jobKind];
144815
+ const enabled2 = envBool2(def.enableEnvVar, fileJob?.enabled, def.defaultEnabled);
144816
+ const intervalMs = envNum2(def.intervalEnvVar, fileJob?.intervalMs, def.schedule.intervalMs ?? THIRTY_MIN);
144326
144817
  const schedule = { type: "interval", intervalMs };
144327
144818
  scheduler.registerOrResumeJob({
144328
144819
  id: def.id,
@@ -144403,9 +144894,9 @@ var init_scheduler2 = __esm(() => {
144403
144894
  });
144404
144895
 
144405
144896
  // ../../packages/core/dist/services/pricing/models-dev-client.js
144406
- import fs18 from "fs/promises";
144897
+ import fs19 from "fs/promises";
144407
144898
  import { existsSync as existsSync4 } from "fs";
144408
- import path30 from "path";
144899
+ import path32 from "path";
144409
144900
  function getModelsDevClient() {
144410
144901
  if (!clientInstance) {
144411
144902
  clientInstance = new ModelsDevClient;
@@ -144425,7 +144916,7 @@ var init_models_dev_client = __esm(() => {
144425
144916
  memoryCacheTimestamp = 0;
144426
144917
  getLocalCachePath() {
144427
144918
  const dataDir = config2.get("dataDir");
144428
- return path30.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
144919
+ return path32.join(dataDir, ModelsDevClient.LOCAL_CACHE_FILE);
144429
144920
  }
144430
144921
  async loadLocalCache() {
144431
144922
  const cachePath = this.getLocalCachePath();
@@ -144433,7 +144924,7 @@ var init_models_dev_client = __esm(() => {
144433
144924
  if (!existsSync4(cachePath)) {
144434
144925
  return null;
144435
144926
  }
144436
- const content = await fs18.readFile(cachePath, "utf-8");
144927
+ const content = await fs19.readFile(cachePath, "utf-8");
144437
144928
  const data = JSON.parse(content);
144438
144929
  const age = Date.now() - data.timestamp;
144439
144930
  if (age > ModelsDevClient.LOCAL_CACHE_TTL) {
@@ -144460,14 +144951,14 @@ var init_models_dev_client = __esm(() => {
144460
144951
  async saveLocalCache(models) {
144461
144952
  const cachePath = this.getLocalCachePath();
144462
144953
  try {
144463
- const dir = path30.dirname(cachePath);
144464
- await fs18.mkdir(dir, { recursive: true });
144954
+ const dir = path32.dirname(cachePath);
144955
+ await fs19.mkdir(dir, { recursive: true });
144465
144956
  const data = {
144466
144957
  timestamp: Date.now(),
144467
144958
  version: "1.0.0",
144468
144959
  models: Object.fromEntries(models)
144469
144960
  };
144470
- await fs18.writeFile(cachePath, JSON.stringify(data), "utf-8");
144961
+ await fs19.writeFile(cachePath, JSON.stringify(data), "utf-8");
144471
144962
  logger.debug("Saved pricing to local cache", {
144472
144963
  models: models.size,
144473
144964
  path: cachePath
@@ -144796,7 +145287,7 @@ var init_models_dev_client = __esm(() => {
144796
145287
  const cachePath = this.getLocalCachePath();
144797
145288
  try {
144798
145289
  if (existsSync4(cachePath)) {
144799
- await fs18.unlink(cachePath);
145290
+ await fs19.unlink(cachePath);
144800
145291
  logger.debug("Local pricing cache file deleted");
144801
145292
  }
144802
145293
  } catch (error51) {
@@ -150351,33 +150842,33 @@ var require_URL = __commonJS((exports, module) => {
150351
150842
  else
150352
150843
  return basepath.substring(0, lastslash + 1) + refpath;
150353
150844
  }
150354
- function remove_dot_segments(path31) {
150355
- if (!path31)
150356
- return path31;
150845
+ function remove_dot_segments(path33) {
150846
+ if (!path33)
150847
+ return path33;
150357
150848
  var output = "";
150358
- while (path31.length > 0) {
150359
- if (path31 === "." || path31 === "..") {
150360
- path31 = "";
150849
+ while (path33.length > 0) {
150850
+ if (path33 === "." || path33 === "..") {
150851
+ path33 = "";
150361
150852
  break;
150362
150853
  }
150363
- var twochars = path31.substring(0, 2);
150364
- var threechars = path31.substring(0, 3);
150365
- var fourchars = path31.substring(0, 4);
150854
+ var twochars = path33.substring(0, 2);
150855
+ var threechars = path33.substring(0, 3);
150856
+ var fourchars = path33.substring(0, 4);
150366
150857
  if (threechars === "../") {
150367
- path31 = path31.substring(3);
150858
+ path33 = path33.substring(3);
150368
150859
  } else if (twochars === "./") {
150369
- path31 = path31.substring(2);
150860
+ path33 = path33.substring(2);
150370
150861
  } else if (threechars === "/./") {
150371
- path31 = "/" + path31.substring(3);
150372
- } else if (twochars === "/." && path31.length === 2) {
150373
- path31 = "/";
150374
- } else if (fourchars === "/../" || threechars === "/.." && path31.length === 3) {
150375
- path31 = "/" + path31.substring(4);
150862
+ path33 = "/" + path33.substring(3);
150863
+ } else if (twochars === "/." && path33.length === 2) {
150864
+ path33 = "/";
150865
+ } else if (fourchars === "/../" || threechars === "/.." && path33.length === 3) {
150866
+ path33 = "/" + path33.substring(4);
150376
150867
  output = output.replace(/\/?[^\/]*$/, "");
150377
150868
  } else {
150378
- var segment = path31.match(/(\/?([^\/]*))/)[0];
150869
+ var segment = path33.match(/(\/?([^\/]*))/)[0];
150379
150870
  output += segment;
150380
- path31 = path31.substring(segment.length);
150871
+ path33 = path33.substring(segment.length);
150381
150872
  }
150382
150873
  }
150383
150874
  return output;
@@ -162447,21 +162938,21 @@ function jsonToKeyPathChunks(value, label = "$") {
162447
162938
  walk(value, label, out);
162448
162939
  return out;
162449
162940
  }
162450
- function walk(val, path31, out) {
162941
+ function walk(val, path33, out) {
162451
162942
  if (val === null || val === undefined)
162452
162943
  return;
162453
162944
  if (Array.isArray(val)) {
162454
162945
  if (val.length === 0) {
162455
- out.push({ path: path31, content: `**${path31}** = _[]_` });
162946
+ out.push({ path: path33, content: `**${path33}** = _[]_` });
162456
162947
  return;
162457
162948
  }
162458
162949
  if (val.every((v) => v !== null && typeof v === "object")) {
162459
- val.forEach((v, i) => walk(v, `${path31}[${i}]`, out));
162950
+ val.forEach((v, i) => walk(v, `${path33}[${i}]`, out));
162460
162951
  return;
162461
162952
  }
162462
162953
  const items = val.map((v) => `- \`${String(v)}\``).join(`
162463
162954
  `);
162464
- out.push({ path: path31, content: `**${path31}**
162955
+ out.push({ path: path33, content: `**${path33}**
162465
162956
 
162466
162957
  ${items}` });
162467
162958
  return;
@@ -162469,16 +162960,16 @@ ${items}` });
162469
162960
  if (typeof val === "object") {
162470
162961
  const entries = Object.entries(val);
162471
162962
  if (entries.length === 0) {
162472
- out.push({ path: path31, content: `**${path31}** = _{}_` });
162963
+ out.push({ path: path33, content: `**${path33}** = _{}_` });
162473
162964
  return;
162474
162965
  }
162475
162966
  for (const [k, v] of entries) {
162476
162967
  const safeKey = /^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k);
162477
- walk(v, `${path31}.${safeKey}`, out);
162968
+ walk(v, `${path33}.${safeKey}`, out);
162478
162969
  }
162479
162970
  return;
162480
162971
  }
162481
- out.push({ path: path31, content: `**${path31}** = \`${String(val)}\`` });
162972
+ out.push({ path: path33, content: `**${path33}** = \`${String(val)}\`` });
162482
162973
  }
162483
162974
  var gfm, STRIP_SELECTORS, tdCache = null;
162484
162975
  var init_html_to_md = __esm(() => {
@@ -163241,8 +163732,8 @@ var init_hook_service = __esm(() => {
163241
163732
 
163242
163733
  // ../../packages/core/dist/services/bootstrap/bootstrap-service.js
163243
163734
  import { randomUUID as randomUUID9 } from "crypto";
163244
- import fs19 from "fs";
163245
- import path31 from "path";
163735
+ import fs20 from "fs";
163736
+ import path33 from "path";
163246
163737
  import { spawn as spawn2 } from "child_process";
163247
163738
  function readBootstrapConfig() {
163248
163739
  try {
@@ -163402,9 +163893,9 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
163402
163893
  }
163403
163894
  try {
163404
163895
  for (const name26 of README_CANDIDATES) {
163405
- const p = path31.join(projectRoot, name26);
163406
- if (fs19.existsSync(p) && fs19.statSync(p).isFile()) {
163407
- const buf = fs19.readFileSync(p);
163896
+ const p = path33.join(projectRoot, name26);
163897
+ if (fs20.existsSync(p) && fs20.statSync(p).isFile()) {
163898
+ const buf = fs20.readFileSync(p);
163408
163899
  signals.readme = buf.slice(0, MAX_README_BYTES).toString("utf8");
163409
163900
  break;
163410
163901
  }
@@ -163413,14 +163904,14 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
163413
163904
  logger.debug("bootstrap scan: README read failed", { error: e.message });
163414
163905
  }
163415
163906
  try {
163416
- const docsDir = path31.join(projectRoot, "docs");
163417
- if (fs19.existsSync(docsDir) && fs19.statSync(docsDir).isDirectory()) {
163907
+ const docsDir = path33.join(projectRoot, "docs");
163908
+ if (fs20.existsSync(docsDir) && fs20.statSync(docsDir).isDirectory()) {
163418
163909
  const entries = walkMarkdown(docsDir).slice(0, MAX_DOCS);
163419
163910
  for (const rel of entries) {
163420
163911
  try {
163421
- const buf = fs19.readFileSync(rel);
163912
+ const buf = fs20.readFileSync(rel);
163422
163913
  signals.docs.push({
163423
- path: path31.relative(projectRoot, rel),
163914
+ path: path33.relative(projectRoot, rel),
163424
163915
  snippet: buf.slice(0, MAX_DOC_BYTES).toString("utf8")
163425
163916
  });
163426
163917
  } catch {}
@@ -163431,10 +163922,10 @@ async function scanSignals(_projectId, projectRoot, caps, symbolGraph, gitRunner
163431
163922
  }
163432
163923
  try {
163433
163924
  for (const name26 of MANIFEST_FILES) {
163434
- const p = path31.join(projectRoot, name26);
163435
- if (!fs19.existsSync(p) || !fs19.statSync(p).isFile())
163925
+ const p = path33.join(projectRoot, name26);
163926
+ if (!fs20.existsSync(p) || !fs20.statSync(p).isFile())
163436
163927
  continue;
163437
- const raw2 = fs19.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
163928
+ const raw2 = fs20.readFileSync(p).slice(0, MAX_MANIFEST_BYTES).toString("utf8");
163438
163929
  const kind = name26;
163439
163930
  if (name26 === "package.json") {
163440
163931
  try {
@@ -163474,12 +163965,12 @@ function walkMarkdown(dir) {
163474
163965
  const cur = stack.pop();
163475
163966
  let entries;
163476
163967
  try {
163477
- entries = fs19.readdirSync(cur, { withFileTypes: true });
163968
+ entries = fs20.readdirSync(cur, { withFileTypes: true });
163478
163969
  } catch {
163479
163970
  continue;
163480
163971
  }
163481
163972
  for (const e of entries) {
163482
- const full = path31.join(cur, e.name);
163973
+ const full = path33.join(cur, e.name);
163483
163974
  if (e.isDirectory()) {
163484
163975
  if (e.name === "node_modules" || e.name.startsWith("."))
163485
163976
  continue;
@@ -166891,7 +167382,7 @@ class StdioServerTransport {
166891
167382
  }
166892
167383
 
166893
167384
  // src/index.ts
166894
- import fs22 from "fs/promises";
167385
+ import fs23 from "fs/promises";
166895
167386
 
166896
167387
  // src/api-client.ts
166897
167388
  init_config();
@@ -167001,8 +167492,8 @@ init_dist();
167001
167492
  init_dist();
167002
167493
  init_dist15();
167003
167494
  init_dist();
167004
- import fs20 from "fs/promises";
167005
- import path32 from "path";
167495
+ import fs21 from "fs/promises";
167496
+ import path34 from "path";
167006
167497
  var _indexProjectTool = null;
167007
167498
  function indexProjectTool() {
167008
167499
  if (!_indexProjectTool)
@@ -167285,8 +167776,8 @@ class EmbeddedApiClient {
167285
167776
  } else {
167286
167777
  end = start + 20;
167287
167778
  }
167288
- const absolutePath = path32.join(workspace.project_path, file2);
167289
- const content = await fs20.readFile(absolutePath, "utf-8");
167779
+ const absolutePath = path34.join(workspace.project_path, file2);
167780
+ const content = await fs21.readFile(absolutePath, "utf-8");
167290
167781
  const lines = content.split(/\r?\n/);
167291
167782
  const slice = lines.slice(start - 1, Math.min(lines.length, end));
167292
167783
  const formatted = slice.map((text3, idx) => ({ lineNumber: start + idx, content: text3 }));
@@ -167523,22 +168014,22 @@ class EmbeddedApiClient {
167523
168014
  async uploadAndIndex(params) {
167524
168015
  const rawBase = params.projectId || params.projectPath.replace(/\\/g, "/").split("/").filter(Boolean).pop() || "default";
167525
168016
  const finalProjectId = rawBase.replace(/[^a-zA-Z0-9_.-]/g, "_").slice(0, 128);
167526
- const uploadRoot = process.env.MASSA_AI_UPLOAD_DIR || path32.join(getGlobalDataDir(), "uploads");
167527
- const stagingDir = path32.resolve(uploadRoot, finalProjectId);
167528
- await fs20.rm(stagingDir, { recursive: true, force: true });
167529
- await fs20.mkdir(stagingDir, { recursive: true });
168017
+ const uploadRoot = process.env.MASSA_AI_UPLOAD_DIR || path34.join(getGlobalDataDir(), "uploads");
168018
+ const stagingDir = path34.resolve(uploadRoot, finalProjectId);
168019
+ await fs21.rm(stagingDir, { recursive: true, force: true });
168020
+ await fs21.mkdir(stagingDir, { recursive: true });
167530
168021
  const WRITE_BATCH = 20;
167531
168022
  for (let i = 0;i < params.files.length; i += WRITE_BATCH) {
167532
168023
  await Promise.all(params.files.slice(i, i + WRITE_BATCH).map(async (file2) => {
167533
- if (path32.isAbsolute(file2.relativePath) || file2.relativePath.includes("..")) {
168024
+ if (path34.isAbsolute(file2.relativePath) || file2.relativePath.includes("..")) {
167534
168025
  throw new Error(`Invalid file path: ${file2.relativePath}`);
167535
168026
  }
167536
- const dest = path32.resolve(stagingDir, file2.relativePath.replace(/\//g, path32.sep));
167537
- if (!dest.startsWith(stagingDir + path32.sep)) {
168027
+ const dest = path34.resolve(stagingDir, file2.relativePath.replace(/\//g, path34.sep));
168028
+ if (!dest.startsWith(stagingDir + path34.sep)) {
167538
168029
  throw new Error(`Path escapes staging directory: ${file2.relativePath}`);
167539
168030
  }
167540
- await fs20.mkdir(path32.dirname(dest), { recursive: true });
167541
- await fs20.writeFile(dest, file2.content, "utf-8");
168031
+ await fs21.mkdir(path34.dirname(dest), { recursive: true });
168032
+ await fs21.writeFile(dest, file2.content, "utf-8");
167542
168033
  }));
167543
168034
  }
167544
168035
  return await indexProjectTool().handle({
@@ -167882,8 +168373,8 @@ class EmbeddedApiClient {
167882
168373
 
167883
168374
  // src/file-collector.ts
167884
168375
  init_config();
167885
- import fs21 from "fs/promises";
167886
- import path33 from "path";
168376
+ import fs22 from "fs/promises";
168377
+ import path35 from "path";
167887
168378
  var SKIP_DIRS = new Set([
167888
168379
  "node_modules",
167889
168380
  ".git",
@@ -167924,7 +168415,7 @@ async function walk2(root2, dir, files, state, allowed) {
167924
168415
  return;
167925
168416
  let entries;
167926
168417
  try {
167927
- entries = await fs21.readdir(dir, { withFileTypes: true });
168418
+ entries = await fs22.readdir(dir, { withFileTypes: true });
167928
168419
  } catch {
167929
168420
  return;
167930
168421
  }
@@ -167933,22 +168424,22 @@ async function walk2(root2, dir, files, state, allowed) {
167933
168424
  break;
167934
168425
  if (entry2.isDirectory()) {
167935
168426
  if (!SKIP_DIRS.has(entry2.name) && !entry2.name.startsWith(".")) {
167936
- await walk2(root2, path33.join(dir, entry2.name), files, state, allowed);
168427
+ await walk2(root2, path35.join(dir, entry2.name), files, state, allowed);
167937
168428
  }
167938
168429
  } else if (entry2.isFile()) {
167939
- const ext2 = path33.extname(entry2.name).toLowerCase();
168430
+ const ext2 = path35.extname(entry2.name).toLowerCase();
167940
168431
  if (!allowed.has(ext2))
167941
168432
  continue;
167942
- const fullPath = path33.join(dir, entry2.name);
168433
+ const fullPath = path35.join(dir, entry2.name);
167943
168434
  try {
167944
- const stat = await fs21.stat(fullPath);
168435
+ const stat = await fs22.stat(fullPath);
167945
168436
  if (stat.size > MAX_FILE_BYTES)
167946
168437
  continue;
167947
168438
  if (state.totalBytes + stat.size > MAX_TOTAL_BYTES)
167948
168439
  continue;
167949
- const content = await fs21.readFile(fullPath, "utf-8");
168440
+ const content = await fs22.readFile(fullPath, "utf-8");
167950
168441
  state.totalBytes += stat.size;
167951
- const relativePath = path33.relative(root2, fullPath).split(path33.sep).join("/");
168442
+ const relativePath = path35.relative(root2, fullPath).split(path35.sep).join("/");
167952
168443
  files.push({ relativePath, content });
167953
168444
  } catch {}
167954
168445
  }
@@ -169849,7 +170340,7 @@ class McpProxyServer {
169849
170340
  return textContent(JSON.stringify({ success: false, error: "projectPath is required" }));
169850
170341
  }
169851
170342
  try {
169852
- if (!(await fs22.stat(projectPath2)).isDirectory()) {
170343
+ if (!(await fs23.stat(projectPath2)).isDirectory()) {
169853
170344
  return textContent(JSON.stringify({ success: false, error: `${projectPath2} is not a directory` }));
169854
170345
  }
169855
170346
  } catch {