@massa-ai/mcp-client 1.66.0 → 1.66.2

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.
@@ -2182,6 +2182,15 @@ function estimateTokens(text, type = "code") {
2182
2182
  const charsPerToken = type === "code" ? 4 : 5;
2183
2183
  return Math.ceil(text.length / charsPerToken);
2184
2184
  }
2185
+ function truncateToTokenLimit(text, limit, type = "code") {
2186
+ const charsPerToken = type === "code" ? 4 : 5;
2187
+ const maxChars = limit * charsPerToken;
2188
+ if (text.length <= maxChars) {
2189
+ return text;
2190
+ }
2191
+ return text.slice(0, maxChars) + `
2192
+ ... (truncated)`;
2193
+ }
2185
2194
  // ../../packages/shared/dist/utils/metrics.js
2186
2195
  var FALLBACK_PRICING, MetricsCollector;
2187
2196
  var init_metrics = __esm(() => {
@@ -53035,12 +53044,55 @@ function _isAbortOrTimeoutError(err) {
53035
53044
  }
53036
53045
  return false;
53037
53046
  }
53047
+ function _isConnectionError(err) {
53048
+ let cur = err;
53049
+ for (let hops = 0;cur && hops < 5; hops++, cur = cur.lastError ?? cur.cause) {
53050
+ const code = typeof cur.code === "string" ? cur.code : "";
53051
+ if (/^(ECONNREFUSED|ECONNRESET|ENOTFOUND|EHOSTUNREACH|ConnectionRefused|ConnectionClosed|FailedToOpenSocket)$/.test(code)) {
53052
+ return true;
53053
+ }
53054
+ const message = typeof cur.message === "string" ? cur.message : "";
53055
+ if (message.startsWith("Cannot connect to API"))
53056
+ return true;
53057
+ }
53058
+ return false;
53059
+ }
53038
53060
  function summarizeZodIssues(error51, maxIssues = 5) {
53039
53061
  return error51.issues.slice(0, maxIssues).map((issue2) => `${issue2.path.join(".") || "(root)"}: ${issue2.message}`).join("; ");
53040
53062
  }
53063
+ function isEndpointCircuitOpen(baseUrl) {
53064
+ const circuit = endpointCircuits.get(baseUrl);
53065
+ if (!circuit || circuit.failures < ENDPOINT_FAILURE_THRESHOLD)
53066
+ return false;
53067
+ const now2 = Date.now();
53068
+ if (now2 < circuit.openUntil)
53069
+ return true;
53070
+ circuit.openUntil = now2 + ENDPOINT_COOLDOWN_MS;
53071
+ return false;
53072
+ }
53073
+ function recordEndpointOutcome(baseUrl, err) {
53074
+ if (!err || !_isConnectionError(err)) {
53075
+ endpointCircuits.delete(baseUrl);
53076
+ return;
53077
+ }
53078
+ const circuit = endpointCircuits.get(baseUrl) ?? { failures: 0, openUntil: 0 };
53079
+ circuit.failures++;
53080
+ if (circuit.failures >= ENDPOINT_FAILURE_THRESHOLD) {
53081
+ circuit.openUntil = Date.now() + ENDPOINT_COOLDOWN_MS;
53082
+ }
53083
+ if (circuit.failures === ENDPOINT_FAILURE_THRESHOLD) {
53084
+ logger.warn("LLM endpoint unreachable \u2014 pausing LLM calls", {
53085
+ provider: resolveProviderIdForLogging(baseUrl),
53086
+ consecutiveConnectionFailures: circuit.failures,
53087
+ cooldownMs: ENDPOINT_COOLDOWN_MS
53088
+ });
53089
+ }
53090
+ endpointCircuits.set(baseUrl, circuit);
53091
+ }
53041
53092
  function recordLlmFailure(label, role, model, baseUrl, timeoutMs, elapsedMs, err) {
53042
53093
  const consecutiveFailures = (llmFailureStreaks.get(label) ?? 0) + 1;
53043
53094
  llmFailureStreaks.set(label, consecutiveFailures);
53095
+ recordEndpointOutcome(baseUrl, err);
53044
53096
  logger.warn("LLM call failed \u2014 using non-LLM fallback", {
53045
53097
  label,
53046
53098
  role,
@@ -53054,7 +53106,8 @@ function recordLlmFailure(label, role, model, baseUrl, timeoutMs, elapsedMs, err
53054
53106
  });
53055
53107
  return consecutiveFailures;
53056
53108
  }
53057
- function recordLlmSuccess(label, model) {
53109
+ function recordLlmSuccess(label, model, baseUrl) {
53110
+ recordEndpointOutcome(baseUrl, null);
53058
53111
  const priorFailures = llmFailureStreaks.get(label) ?? 0;
53059
53112
  if (priorFailures > 0) {
53060
53113
  logger.info("LLM call recovered", { label, model, afterFailures: priorFailures });
@@ -53066,6 +53119,9 @@ async function llmComplete(prompt, opts) {
53066
53119
  return { ok: false, error: "llm disabled" };
53067
53120
  }
53068
53121
  const llm = getLlmConfig({ modelRole: opts.modelRole });
53122
+ if (isEndpointCircuitOpen(llm.baseUrl)) {
53123
+ return { ok: false, error: "llm endpoint unreachable (circuit open)" };
53124
+ }
53069
53125
  const role = opts.modelRole ?? "instruct";
53070
53126
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
53071
53127
  const startedAt = Date.now();
@@ -53080,7 +53136,7 @@ async function llmComplete(prompt, opts) {
53080
53136
  });
53081
53137
  const text2 = result.text ?? "";
53082
53138
  if (text2.length > 0) {
53083
- recordLlmSuccess(opts.label, llm.model);
53139
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
53084
53140
  return { ok: true, value: text2 };
53085
53141
  }
53086
53142
  if (llm.disableThink) {
@@ -53089,7 +53145,7 @@ async function llmComplete(prompt, opts) {
53089
53145
  logger.warn("llmComplete: empty content \u2014 recovered from reasoning channel", {
53090
53146
  reasoningLen: reasoning.length
53091
53147
  });
53092
- recordLlmSuccess(opts.label, llm.model);
53148
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
53093
53149
  return { ok: true, value: reasoning };
53094
53150
  }
53095
53151
  logger.warn("llm reasoning-recovery empty", {
@@ -53110,6 +53166,9 @@ async function llmObject(prompt, schema, opts) {
53110
53166
  return { ok: false, error: "llm disabled" };
53111
53167
  }
53112
53168
  const llm = getLlmConfig({ modelRole: opts.modelRole });
53169
+ if (isEndpointCircuitOpen(llm.baseUrl)) {
53170
+ return { ok: false, error: "llm endpoint unreachable (circuit open)" };
53171
+ }
53113
53172
  const role = opts.modelRole ?? "instruct";
53114
53173
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
53115
53174
  const startedAt = Date.now();
@@ -53128,7 +53187,7 @@ async function llmObject(prompt, schema, opts) {
53128
53187
  abortSignal: timeoutSignal(timeoutMs)
53129
53188
  });
53130
53189
  logger.debug("json_schema: constrained decoding used", { label: opts.label, model: llm.model });
53131
- recordLlmSuccess(opts.label, llm.model);
53190
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
53132
53191
  return { ok: true, value: result.object };
53133
53192
  }
53134
53193
  result = await generateObject({
@@ -53143,7 +53202,7 @@ async function llmObject(prompt, schema, opts) {
53143
53202
  const validated = schema.safeParse(result.object);
53144
53203
  if (validated.success) {
53145
53204
  logger.debug("json_schema: fallback to json_object \u2014 validated", { label: opts.label, model: llm.model });
53146
- recordLlmSuccess(opts.label, llm.model);
53205
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
53147
53206
  return { ok: true, value: validated.data };
53148
53207
  }
53149
53208
  if (llm.disableThink) {
@@ -53156,7 +53215,7 @@ async function llmObject(prompt, schema, opts) {
53156
53215
  logger.warn("llmObject: recovered object from reasoning channel (fallback path)", {
53157
53216
  reasoningLen: reasoning.length
53158
53217
  });
53159
- recordLlmSuccess(opts.label, llm.model);
53218
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
53160
53219
  return { ok: true, value: recovered.data };
53161
53220
  }
53162
53221
  }
@@ -53168,7 +53227,7 @@ async function llmObject(prompt, schema, opts) {
53168
53227
  recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, validationErr);
53169
53228
  return { ok: false, error: validationErr.message };
53170
53229
  } catch (e) {
53171
- if (llm.disableThink && !_isAbortOrTimeoutError(e)) {
53230
+ if (llm.disableThink && !_isAbortOrTimeoutError(e) && !_isConnectionError(e)) {
53172
53231
  const reasoning = _reasoningToText(result).length > 0 ? _reasoningToText(result) : _reasoningToText(e);
53173
53232
  if (reasoning.length > 0) {
53174
53233
  const parsed = _extractJsonObject(reasoning);
@@ -53178,7 +53237,7 @@ async function llmObject(prompt, schema, opts) {
53178
53237
  logger.warn("llmObject: recovered object from reasoning channel", {
53179
53238
  reasoningLen: reasoning.length
53180
53239
  });
53181
- recordLlmSuccess(opts.label, llm.model);
53240
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
53182
53241
  return { ok: true, value: validated.data };
53183
53242
  }
53184
53243
  }
@@ -53192,7 +53251,7 @@ async function llmObject(prompt, schema, opts) {
53192
53251
  return { ok: false, error: e.message };
53193
53252
  }
53194
53253
  }
53195
- var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llmFailureStreaks, llm;
53254
+ var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llmFailureStreaks, ENDPOINT_FAILURE_THRESHOLD = 3, ENDPOINT_COOLDOWN_MS = 60000, endpointCircuits, llm;
53196
53255
  var init_llm_client = __esm(() => {
53197
53256
  init_dist6();
53198
53257
  init_dist7();
@@ -53200,6 +53259,7 @@ var init_llm_client = __esm(() => {
53200
53259
  init_config();
53201
53260
  init_inference_providers();
53202
53261
  llmFailureStreaks = new Map;
53262
+ endpointCircuits = new Map;
53203
53263
  llm = {
53204
53264
  complete: llmComplete,
53205
53265
  object: llmObject,
@@ -129938,6 +129998,7 @@ var init_auto_improve_job = __esm(() => {
129938
129998
  var exports_observation_consolidation_job = {};
129939
129999
  __export(exports_observation_consolidation_job, {
129940
130000
  observationConsolidationJob: () => observationConsolidationJob,
130001
+ buildObservationPrompt: () => buildObservationPrompt,
129941
130002
  ObservationConsolidationJob: () => ObservationConsolidationJob
129942
130003
  });
129943
130004
  import { randomUUID as randomUUID8 } from "crypto";
@@ -129965,6 +130026,7 @@ class ObservationConsolidationJob {
129965
130026
  maxWindow;
129966
130027
  lastRunAt = 0;
129967
130028
  newSinceRun = 0;
130029
+ running = false;
129968
130030
  runCalls = 0;
129969
130031
  get store() {
129970
130032
  return this.injectedStore ?? getObservationStore();
@@ -130008,6 +130070,18 @@ class ObservationConsolidationJob {
130008
130070
  }
130009
130071
  async runOnce(projectId) {
130010
130072
  this.runCalls++;
130073
+ if (this.running) {
130074
+ logger.debug("observation consolidation: skipped, a run is in flight", { projectId });
130075
+ return { consolidated: false, batchesCreated: 0 };
130076
+ }
130077
+ this.running = true;
130078
+ try {
130079
+ return await this.consolidateWindow(projectId);
130080
+ } finally {
130081
+ this.running = false;
130082
+ }
130083
+ }
130084
+ async consolidateWindow(projectId) {
130011
130085
  const noop2 = {
130012
130086
  consolidated: false,
130013
130087
  batchesCreated: 0
@@ -130097,8 +130171,9 @@ class ObservationConsolidationJob {
130097
130171
  }
130098
130172
  }
130099
130173
  function buildObservationPrompt(window2) {
130174
+ const observationTokens = Math.min(MAX_OBSERVATION_TOKENS, Math.floor(MAX_WINDOW_TOKENS / Math.max(window2.length, 1)));
130100
130175
  const items = window2.map((o, i) => `[${i}] id=${o.id} source=${o.source} importance=${o.importance.toFixed(2)}
130101
- ${o.payloadJson}`).join(`
130176
+ ${digestPayload(o.payloadJson, observationTokens)}`).join(`
130102
130177
  `);
130103
130178
  return [
130104
130179
  "You are consolidating a window of passive lifecycle observations (agent telemetry)",
@@ -130113,7 +130188,20 @@ ${o.payloadJson}`).join(`
130113
130188
  ].join(`
130114
130189
  `);
130115
130190
  }
130116
- var FALLBACK_BRIDGE, observationConsolidationJob;
130191
+ function digestPayload(payloadJson, maxTokens) {
130192
+ let payload;
130193
+ try {
130194
+ payload = JSON.parse(payloadJson);
130195
+ } catch {
130196
+ return truncateToTokenLimit(payloadJson, maxTokens);
130197
+ }
130198
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
130199
+ payload = Object.fromEntries(Object.entries(payload).filter(([key]) => !PROMPT_BOOKKEEPING_KEYS.has(key)));
130200
+ }
130201
+ const compact = JSON.stringify(payload, (_key, value) => typeof value === "string" && value.length > MAX_PROMPT_FIELD_CHARS ? `${value.slice(0, MAX_PROMPT_FIELD_CHARS)}\u2026` : value);
130202
+ return truncateToTokenLimit(compact ?? "", maxTokens);
130203
+ }
130204
+ var FALLBACK_BRIDGE, observationConsolidationJob, PROMPT_BOOKKEEPING_KEYS, MAX_PROMPT_FIELD_CHARS = 400, MAX_OBSERVATION_TOKENS = 300, MAX_WINDOW_TOKENS = 2400;
130117
130205
  var init_observation_consolidation_job = __esm(() => {
130118
130206
  init_dist();
130119
130207
  init_dist();
@@ -130129,6 +130217,18 @@ var init_observation_consolidation_job = __esm(() => {
130129
130217
  maxWindow: 8
130130
130218
  };
130131
130219
  observationConsolidationJob = new ObservationConsolidationJob;
130220
+ PROMPT_BOOKKEEPING_KEYS = new Set([
130221
+ "session_id",
130222
+ "transcript_path",
130223
+ "cwd",
130224
+ "prompt_id",
130225
+ "tool_use_id",
130226
+ "agent_id",
130227
+ "hook_event_name",
130228
+ "permission_mode",
130229
+ "effort",
130230
+ "duration_ms"
130231
+ ]);
130132
130232
  });
130133
130233
 
130134
130234
  // ../../packages/core/dist/services/checkpoint/checkpoint-store-pg.js
@@ -134878,14 +134978,80 @@ function indexDefinitions(definitions) {
134878
134978
  });
134879
134979
  return { registry: registry3, definitions: Object.freeze(indexed) };
134880
134980
  }
134881
- function candidateKind(reference, definition) {
134882
- if (reference.kind === "type_ref" || reference.kind === "extend" || reference.kind === "implement") {
134883
- return ["class", "interface", "trait", "enum", "type", "type_parameter"].includes(definition.identity.kind);
134884
- }
134885
- if (reference.kind === "call" || reference.kind === "data_flow" || reference.kind === "http_call") {
134886
- return ["function", "method", "constructor", "class", "field", "variable", "constant", "export"].includes(definition.identity.kind);
134887
- }
134888
- return false;
134981
+ function buildPartition(list) {
134982
+ const byFqn = new Map;
134983
+ const byFile = new Map;
134984
+ const byFileQualifiedName = new Map;
134985
+ const byQualifiedName = new Map;
134986
+ for (const definition of list) {
134987
+ const identity = definition.identity;
134988
+ if (!byFqn.has(identity.fqn))
134989
+ byFqn.set(identity.fqn, definition);
134990
+ const fileBucket = byFile.get(identity.file);
134991
+ if (fileBucket)
134992
+ fileBucket.push(definition);
134993
+ else
134994
+ byFile.set(identity.file, [definition]);
134995
+ const fileQualifiedNameKey = `${identity.file}\x00${identity.qualifiedName}`;
134996
+ const fileQualifiedNameBucket = byFileQualifiedName.get(fileQualifiedNameKey);
134997
+ if (fileQualifiedNameBucket)
134998
+ fileQualifiedNameBucket.push(definition);
134999
+ else
135000
+ byFileQualifiedName.set(fileQualifiedNameKey, [definition]);
135001
+ const qualifiedNameBucket = byQualifiedName.get(identity.qualifiedName);
135002
+ if (qualifiedNameBucket)
135003
+ qualifiedNameBucket.push(definition);
135004
+ else
135005
+ byQualifiedName.set(identity.qualifiedName, [definition]);
135006
+ }
135007
+ return { list, byFqn, byFile, byFileQualifiedName, byQualifiedName };
135008
+ }
135009
+ function buildScopedIndex(rawDefinitions, familyOnly) {
135010
+ const scoped = familyOnly ? rawDefinitions.filter((definition) => FAMILY_DIALECTS.has(definition.identity.dialect)) : rawDefinitions;
135011
+ const { registry: registry3, definitions: all } = indexDefinitions(scoped);
135012
+ const typeRefs = [];
135013
+ const calls = [];
135014
+ for (const definition of all) {
135015
+ if (TYPE_REF_KINDS.has(definition.identity.kind))
135016
+ typeRefs.push(definition);
135017
+ if (CALL_KINDS.has(definition.identity.kind))
135018
+ calls.push(definition);
135019
+ }
135020
+ return { registry: registry3, typeRefs: buildPartition(typeRefs), calls: buildPartition(calls), all: buildPartition(all) };
135021
+ }
135022
+ function definitionIndex(rawDefinitions, familyOnly) {
135023
+ let byScope = RESOLVE_INDEX_CACHE.get(rawDefinitions);
135024
+ if (!byScope) {
135025
+ byScope = new Map;
135026
+ RESOLVE_INDEX_CACHE.set(rawDefinitions, byScope);
135027
+ }
135028
+ const existing = byScope.get(familyOnly);
135029
+ if (existing)
135030
+ return existing;
135031
+ const built = buildScopedIndex(rawDefinitions, familyOnly);
135032
+ byScope.set(familyOnly, built);
135033
+ return built;
135034
+ }
135035
+ function cachedDialectScope(definitions, dialectKey, predicate) {
135036
+ let byKey = DIALECT_SCOPE_CACHE.get(definitions);
135037
+ if (!byKey) {
135038
+ byKey = new Map;
135039
+ DIALECT_SCOPE_CACHE.set(definitions, byKey);
135040
+ }
135041
+ const existing = byKey.get(dialectKey);
135042
+ if (existing)
135043
+ return existing;
135044
+ const scoped = definitions.filter((definition) => predicate(definition));
135045
+ byKey.set(dialectKey, scoped);
135046
+ return scoped;
135047
+ }
135048
+ function normalizedKnownFiles(knownFiles) {
135049
+ const existing = KNOWN_FILES_CACHE.get(knownFiles);
135050
+ if (existing)
135051
+ return existing;
135052
+ const built = new Set(knownFiles.map(normalizeStructuralFile));
135053
+ KNOWN_FILES_CACHE.set(knownFiles, built);
135054
+ return built;
134889
135055
  }
134890
135056
  function probe(base, known, dialect = "typescript") {
134891
135057
  const bases = /\.[cm]?jsx?$/u.test(base) ? [base.replace(/\.[cm]?jsx?$/u, ".ts"), base.replace(/\.[cm]?jsx?$/u, ".tsx"), base] : [base];
@@ -134898,7 +135064,7 @@ function probe(base, known, dialect = "typescript") {
134898
135064
  return;
134899
135065
  }
134900
135066
  function resolveStructuralSpecifier(specifier, fromFile, build, dialect = "typescript") {
134901
- const known = new Set(build.knownFiles.map(normalizeStructuralFile));
135067
+ const known = normalizedKnownFiles(build.knownFiles);
134902
135068
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
134903
135069
  return probe(path28.posix.join(path28.posix.dirname(fromFile), specifier), known, dialect);
134904
135070
  }
@@ -134935,12 +135101,12 @@ function matchesStructuralPathAlias(specifier, aliases) {
134935
135101
  return specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length;
134936
135102
  });
134937
135103
  }
134938
- function exportedMatches(file2, sought, defaultOnly, definitions, build, visited = new Set) {
135104
+ function exportedMatches(file2, sought, defaultOnly, partition, build, visited = new Set) {
134939
135105
  const key = `${file2}\x00${sought}\x00${defaultOnly}`;
134940
135106
  if (visited.has(key))
134941
135107
  return [];
134942
135108
  visited.add(key);
134943
- const direct = definitions.filter((definition) => definition.identity.file === file2 && definition.exported && (defaultOnly ? definition.defaultExport : definition.identity.qualifiedName === sought));
135109
+ const direct = (partition.byFile.get(file2) ?? []).filter((definition) => definition.exported && (defaultOnly ? definition.defaultExport : definition.identity.qualifiedName === sought));
134944
135110
  const concrete = direct.filter((definition) => definition.identity.kind !== "export");
134945
135111
  if (concrete.length > 0) {
134946
135112
  if (!defaultOnly)
@@ -134958,7 +135124,7 @@ function exportedMatches(file2, sought, defaultOnly, definitions, build, visited
134958
135124
  for (const binding of reexport.bindings) {
134959
135125
  if (binding.local !== sought && binding.imported !== "*")
134960
135126
  continue;
134961
- forwarded.push(...exportedMatches(targetFile, binding.imported === "*" ? sought : binding.imported, defaultOnly || binding.imported === "default", definitions, build, visited));
135127
+ forwarded.push(...exportedMatches(targetFile, binding.imported === "*" ? sought : binding.imported, defaultOnly || binding.imported === "default", partition, build, visited));
134962
135128
  }
134963
135129
  }
134964
135130
  if (forwarded.length > 0)
@@ -134968,7 +135134,7 @@ function exportedMatches(file2, sought, defaultOnly, definitions, build, visited
134968
135134
  const namedDefault = direct.filter((definition) => definition.identity.name !== "default");
134969
135135
  return namedDefault.length > 0 ? namedDefault : direct;
134970
135136
  }
134971
- function importedMatches(file2, reference, definitions, build) {
135137
+ function importedMatches(file2, reference, partition, build) {
134972
135138
  const matches = [];
134973
135139
  let claimed = false;
134974
135140
  for (const imported of file2.imports) {
@@ -135010,31 +135176,30 @@ function importedMatches(file2, reference, definitions, build) {
135010
135176
  }
135011
135177
  if ((imported.typeOnly || binding.typeOnly) && !typeEdge)
135012
135178
  continue;
135013
- const importedFile = resolveStructuralSpecifier(imported.specifier, file2.file, build, file2.dialect) ?? (["python_import", "ruby_require", "php_use", "lua_require", "c_include", "cpp_include", "go_import", "rust_use", "zig_import", "java_import", "java_static_import", "kotlin_import", "scala_import", "dart_import", "elixir_alias", "elixir_import", "elixir_require", "elixir_use", "erlang_import", "clojure_require", "clojure_import", "ocaml_open", "ocaml_include", "ocaml_module_alias", "haskell_import"].includes(imported.form) ? probe(imported.specifier.replace(/^\.\//u, ""), new Set(build.knownFiles.map(normalizeStructuralFile)), file2.dialect) : undefined);
135179
+ const importedFile = resolveStructuralSpecifier(imported.specifier, file2.file, build, file2.dialect) ?? (["python_import", "ruby_require", "php_use", "lua_require", "c_include", "cpp_include", "go_import", "rust_use", "zig_import", "java_import", "java_static_import", "kotlin_import", "scala_import", "dart_import", "elixir_alias", "elixir_import", "elixir_require", "elixir_use", "erlang_import", "clojure_require", "clojure_import", "ocaml_open", "ocaml_include", "ocaml_module_alias", "haskell_import"].includes(imported.form) ? probe(imported.specifier.replace(/^\.\//u, ""), normalizedKnownFiles(build.knownFiles), file2.dialect) : undefined);
135014
135180
  if (!importedFile)
135015
135181
  continue;
135016
135182
  const esmDefaultMember = imported.form === "esm_import" && binding.imported === "default" && qualifier[0] === binding.local;
135017
135183
  if (esmDefaultMember && sought !== undefined) {
135018
- const owners = exportedMatches(importedFile, "default", true, definitions, build);
135184
+ const owners = exportedMatches(importedFile, "default", true, partition, build);
135019
135185
  for (const owner of owners) {
135020
135186
  const ownerMember = `${owner.identity.qualifiedName}.${sought}`;
135021
- matches.push(...definitions.filter((definition) => definition.identity.file === owner.identity.file && definition.exported && definition.identity.qualifiedName === ownerMember));
135187
+ matches.push(...(partition.byFileQualifiedName.get(`${owner.identity.file}\x00${ownerMember}`) ?? []).filter((definition) => definition.exported));
135022
135188
  }
135023
135189
  continue;
135024
135190
  }
135025
135191
  if (defaultOnly)
135026
- matches.push(...exportedMatches(importedFile, "default", true, definitions, build));
135192
+ matches.push(...exportedMatches(importedFile, "default", true, partition, build));
135027
135193
  else if (sought !== undefined)
135028
- matches.push(...exportedMatches(importedFile, sought, false, definitions, build).filter((definition) => binding.arity === undefined || definition.arity === binding.arity));
135194
+ matches.push(...exportedMatches(importedFile, sought, false, partition, build).filter((definition) => binding.arity === undefined || definition.arity === binding.arity));
135029
135195
  }
135030
135196
  }
135031
135197
  return { matches, claimed };
135032
135198
  }
135033
- function sameFileMatches(file2, reference, definitions) {
135034
- const local = definitions.filter((definition) => definition.identity.file === file2);
135199
+ function sameFileMatches(file2, reference, partition) {
135035
135200
  if (reference.qualifier && reference.qualifier !== "this") {
135036
135201
  const exact = `${reference.qualifier}.${reference.name}`;
135037
- return local.filter((definition) => definition.identity.qualifiedName === exact);
135202
+ return partition.byFileQualifiedName.get(`${file2}\x00${exact}`) ?? [];
135038
135203
  }
135039
135204
  const lexical = reference.lexicalScope?.split(".").filter(Boolean) ?? [];
135040
135205
  if (lexical.length > 0)
@@ -135042,7 +135207,7 @@ function sameFileMatches(file2, reference, definitions) {
135042
135207
  for (let length = lexical.length;length >= 0; length -= 1) {
135043
135208
  const prefix = lexical.slice(0, length).join(".");
135044
135209
  const exact = prefix ? `${prefix}.${reference.name}` : reference.name;
135045
- const matches = local.filter((definition) => definition.identity.qualifiedName === exact);
135210
+ const matches = partition.byFileQualifiedName.get(`${file2}\x00${exact}`) ?? [];
135046
135211
  if (matches.length > 0)
135047
135212
  return matches;
135048
135213
  if (reference.qualifier === "this")
@@ -135050,7 +135215,7 @@ function sameFileMatches(file2, reference, definitions) {
135050
135215
  }
135051
135216
  return [];
135052
135217
  }
135053
- var TYPESCRIPT_RESOLVER_VERSION = "1.0.0", DIALECT_PROBES, REQUIRE_IMPORT_FORMS, TYPESCRIPT_LANGUAGE_RESOLVER;
135218
+ var TYPESCRIPT_RESOLVER_VERSION = "1.0.0", DIALECT_PROBES, TYPE_REF_KINDS, CALL_KINDS, FAMILY_DIALECTS, REFERENCE_PARTITION, EMPTY_PARTITION, RESOLVE_INDEX_CACHE, DIALECT_SCOPE_CACHE, KNOWN_FILES_CACHE, REQUIRE_IMPORT_FORMS, TYPESCRIPT_LANGUAGE_RESOLVER;
135054
135219
  var init_typescript2 = __esm(() => {
135055
135220
  init_fqn_codec();
135056
135221
  DIALECT_PROBES = Object.freeze({
@@ -135085,6 +135250,27 @@ var init_typescript2 = __esm(() => {
135085
135250
  ocaml: ["", ".ml"],
135086
135251
  haskell: ["", ".hs"]
135087
135252
  });
135253
+ TYPE_REF_KINDS = new Set(["class", "interface", "trait", "enum", "type", "type_parameter"]);
135254
+ CALL_KINDS = new Set(["function", "method", "constructor", "class", "field", "variable", "constant", "export"]);
135255
+ FAMILY_DIALECTS = new Set(["typescript", "tsx", "javascript", "jsx", "sfc"]);
135256
+ REFERENCE_PARTITION = Object.freeze({
135257
+ type_ref: "typeRefs",
135258
+ extend: "typeRefs",
135259
+ implement: "typeRefs",
135260
+ call: "calls",
135261
+ data_flow: "calls",
135262
+ http_call: "calls"
135263
+ });
135264
+ EMPTY_PARTITION = Object.freeze({
135265
+ list: Object.freeze([]),
135266
+ byFqn: new Map,
135267
+ byFile: new Map,
135268
+ byFileQualifiedName: new Map,
135269
+ byQualifiedName: new Map
135270
+ });
135271
+ RESOLVE_INDEX_CACHE = new WeakMap;
135272
+ DIALECT_SCOPE_CACHE = new WeakMap;
135273
+ KNOWN_FILES_CACHE = new WeakMap;
135088
135274
  REQUIRE_IMPORT_FORMS = new Set(["commonjs_require", "dynamic_import", "ruby_require", "lua_require"]);
135089
135275
  TYPESCRIPT_LANGUAGE_RESOLVER = Object.freeze({
135090
135276
  version: TYPESCRIPT_RESOLVER_VERSION,
@@ -135092,21 +135278,19 @@ var init_typescript2 = __esm(() => {
135092
135278
  resolve(file2, rawReference, rawDefinitions, build) {
135093
135279
  const normalizedFile = normalizeStructuralFile(file2.file);
135094
135280
  const reference = normalizedReference(rawReference);
135095
- const familyDialects = ["typescript", "tsx", "javascript", "jsx", "sfc"];
135096
- const scopedDefinitions = familyDialects.includes(file2.dialect) ? rawDefinitions.filter((definition) => familyDialects.includes(definition.identity.dialect)) : rawDefinitions;
135097
- const { registry: registry3, definitions: allDefinitions } = indexDefinitions(scopedDefinitions);
135098
- const definitions = allDefinitions.filter((definition) => candidateKind(reference, definition));
135281
+ const index = definitionIndex(rawDefinitions, FAMILY_DIALECTS.has(file2.dialect));
135282
+ const partition = reference.kind && REFERENCE_PARTITION[reference.kind] ? index[REFERENCE_PARTITION[reference.kind]] : EMPTY_PARTITION;
135099
135283
  if (reference.existingFqn) {
135100
- const prepared = definitions.find((definition) => definition.identity.fqn === reference.existingFqn)?.identity;
135101
- const exact = prepared ? { found: true, identity: prepared } : registry3.resolveModern(reference.existingFqn);
135284
+ const prepared = partition.byFqn.get(reference.existingFqn)?.identity;
135285
+ const exact = prepared ? { found: true, identity: prepared } : index.registry.resolveModern(reference.existingFqn);
135102
135286
  return exact.found ? Object.freeze({ status: "resolved", fqn: exact.identity.fqn, identity: exact.identity, source: "exact" }) : Object.freeze({ status: "unresolved", name: reference.existingFqn });
135103
135287
  }
135104
135288
  const soughtQualified = reference.qualifier ? `${reference.qualifier}.${reference.name}` : reference.name;
135105
- const local = sameFileMatches(normalizedFile, reference, definitions);
135289
+ const local = sameFileMatches(normalizedFile, reference, partition);
135106
135290
  const localOutcome = outcome(reference, local, "same_file");
135107
135291
  if (localOutcome)
135108
135292
  return localOutcome;
135109
- const imported = importedMatches({ ...file2, file: normalizedFile }, reference, definitions, build);
135293
+ const imported = importedMatches({ ...file2, file: normalizedFile }, reference, partition, build);
135110
135294
  const importOutcome = outcome(reference, imported.matches, "import");
135111
135295
  if (importOutcome)
135112
135296
  return importOutcome;
@@ -135116,16 +135300,16 @@ var init_typescript2 = __esm(() => {
135116
135300
  name: reference.name,
135117
135301
  ...reference.qualifier ? { qualifier: reference.qualifier } : {}
135118
135302
  });
135119
- const global2 = definitions.filter((definition) => definition.exported && (reference.qualifier ? definition.identity.qualifiedName === soughtQualified : definition.identity.name === reference.name && definition.identity.qualifiedName === definition.identity.name));
135120
- return outcome(reference, global2, "global") ?? Object.freeze({
135303
+ const globalBucket = reference.qualifier ? (partition.byQualifiedName.get(soughtQualified) ?? []).filter((definition) => definition.exported) : (partition.byQualifiedName.get(reference.name) ?? []).filter((definition) => definition.exported && definition.identity.qualifiedName === definition.identity.name);
135304
+ return outcome(reference, globalBucket, "global") ?? Object.freeze({
135121
135305
  status: "unresolved",
135122
135306
  name: reference.name,
135123
135307
  ...reference.qualifier ? { qualifier: reference.qualifier } : {}
135124
135308
  });
135125
135309
  },
135126
135310
  resolveLegacy(legacyFqn, rawDefinitions) {
135127
- const { registry: registry3, definitions } = indexDefinitions(rawDefinitions);
135128
- const materialized = definitions.filter((definition) => definition.identity.legacyFqn === legacyFqn);
135311
+ const { registry: registry3, all } = definitionIndex(rawDefinitions, false);
135312
+ const materialized = all.list.filter((definition) => definition.identity.legacyFqn === legacyFqn);
135129
135313
  const materializedOutcome = outcome({ kind: "call", span: { startByte: 0, endByte: 0, start: { row: 0, column: 0 }, end: { row: 0, column: 0 } }, name: legacyFqn }, materialized, "legacy");
135130
135314
  if (materializedOutcome)
135131
135315
  return materializedOutcome;
@@ -135158,7 +135342,7 @@ var init_scripting2 = __esm(() => {
135158
135342
  ...TYPESCRIPT_LANGUAGE_RESOLVER,
135159
135343
  dialects: Object.freeze(["python", "ruby", "php", "lua-luajit"]),
135160
135344
  resolve(file2, reference, definitions, build) {
135161
- return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(file2, reference, definitions.filter((definition) => definition.identity.dialect === file2.dialect), build);
135345
+ return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(file2, reference, cachedDialectScope(definitions, file2.dialect, (definition) => definition.identity.dialect === file2.dialect), build);
135162
135346
  }
135163
135347
  });
135164
135348
  });
@@ -135174,6 +135358,7 @@ var init_systems2 = __esm(() => {
135174
135358
  dialects: DIALECTS,
135175
135359
  resolve(file2, reference, definitions, build) {
135176
135360
  const compatible = file2.dialect === "header-default-c" ? ["c", "header-default-c"] : file2.dialect === "header-cpp" || file2.dialect === "header" ? ["cpp", "header", "header-cpp"] : [file2.dialect];
135361
+ const compatibleKey = compatible.join(",");
135177
135362
  const unresolvedTarget = reference.target.status === "unresolved" ? reference.target : undefined;
135178
135363
  const resolverFile = file2.dialect === "rust" ? {
135179
135364
  ...file2,
@@ -135192,7 +135377,7 @@ var init_systems2 = __esm(() => {
135192
135377
  return { ...item, bindings };
135193
135378
  })
135194
135379
  } : file2;
135195
- return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, definitions.filter((item) => compatible.includes(item.identity.dialect)), build);
135380
+ return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, cachedDialectScope(definitions, compatibleKey, (item) => compatible.includes(item.identity.dialect)), build);
135196
135381
  }
135197
135382
  });
135198
135383
  });
@@ -135237,7 +135422,7 @@ var init_managed2 = __esm(() => {
135237
135422
  return imported;
135238
135423
  return { ...imported, bindings: imported.bindings.map((binding) => binding.imported === "*" && binding.local === "*" ? { ...binding, imported: unresolved2.name, local: unresolved2.name } : binding) };
135239
135424
  }) } : file2;
135240
- return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, definitions.filter((item) => file2.dialect === "kotlin" || file2.dialect === "kotlin-script" ? item.identity.dialect === "kotlin" || item.identity.dialect === "kotlin-script" : item.identity.dialect === file2.dialect), build);
135425
+ return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, cachedDialectScope(definitions, file2.dialect === "kotlin" || file2.dialect === "kotlin-script" ? "kotlin" : file2.dialect, (item) => file2.dialect === "kotlin" || file2.dialect === "kotlin-script" ? item.identity.dialect === "kotlin" || item.identity.dialect === "kotlin-script" : item.identity.dialect === file2.dialect), build);
135241
135426
  }
135242
135427
  });
135243
135428
  });
@@ -135265,7 +135450,7 @@ var init_functional2 = __esm(() => {
135265
135450
  return imported;
135266
135451
  return { ...imported, bindings: imported.bindings.length === 0 ? [{ imported: `${owner}.${unresolved2.name}`, local: unresolved2.name, typeOnly: false }] : imported.bindings.map((binding) => binding.imported === "*" && (binding.local === "*" || imported.form === "elixir_import") ? { ...binding, imported: `${owner}.${unresolved2.name}`, local: unresolved2.name } : binding.imported.startsWith("!") ? binding : { ...binding, imported: `${owner}.${binding.imported}` }) };
135267
135452
  }) } : file2;
135268
- return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, definitions.filter((item) => file2.dialect === "elixir" || file2.dialect === "elixir-script" ? item.identity.dialect === "elixir" || item.identity.dialect === "elixir-script" : item.identity.dialect === file2.dialect), build);
135453
+ return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, cachedDialectScope(definitions, file2.dialect === "elixir" || file2.dialect === "elixir-script" ? "elixir" : file2.dialect, (item) => file2.dialect === "elixir" || file2.dialect === "elixir-script" ? item.identity.dialect === "elixir" || item.identity.dialect === "elixir-script" : item.identity.dialect === file2.dialect), build);
135269
135454
  }
135270
135455
  });
135271
135456
  });
@@ -135283,6 +135468,14 @@ var init_data_document2 = __esm(() => {
135283
135468
  // ../../packages/core/dist/services/etl/stages/resolve.js
135284
135469
  import path30 from "path";
135285
135470
  import fs21 from "fs";
135471
+ function knownRelPathsList(knownRelPaths) {
135472
+ const existing = KNOWN_REL_PATHS_LISTS.get(knownRelPaths);
135473
+ if (existing)
135474
+ return existing;
135475
+ const built = Object.freeze([...knownRelPaths]);
135476
+ KNOWN_REL_PATHS_LISTS.set(knownRelPaths, built);
135477
+ return built;
135478
+ }
135286
135479
 
135287
135480
  class ResolveStage {
135288
135481
  symbolRepository;
@@ -135366,7 +135559,7 @@ class ResolveStage {
135366
135559
  resolveStructuralFile(parsed, session2, knownRelPaths, rootAliases, monorepoPackages) {
135367
135560
  const filePath = parsed.file.relativePath;
135368
135561
  const structuralAliases = this.structuralAliasesFor(filePath, rootAliases, monorepoPackages);
135369
- const build = { knownFiles: [...knownRelPaths], pathAliasesByFile: { [filePath]: structuralAliases } };
135562
+ const build = { knownFiles: knownRelPathsList(knownRelPaths), pathAliasesByFile: { [filePath]: structuralAliases } };
135370
135563
  const resolvedImports = parsed.rawImports.map((raw2) => {
135371
135564
  const resolvedPath = resolveStructuralSpecifier(raw2.specifier, filePath, build) ?? null;
135372
135565
  return {
@@ -135666,7 +135859,7 @@ class ResolveStage {
135666
135859
  }));
135667
135860
  }
135668
135861
  }
135669
- var TS_EXTENSIONS, STRUCTURAL_SEED_EXTENSIONS;
135862
+ var KNOWN_REL_PATHS_LISTS, TS_EXTENSIONS, STRUCTURAL_SEED_EXTENSIONS;
135670
135863
  var init_resolve = __esm(() => {
135671
135864
  init_dist();
135672
135865
  init_symbol_repository_factory();
@@ -135680,14 +135873,28 @@ var init_resolve = __esm(() => {
135680
135873
  init_fqn_codec();
135681
135874
  init_language_manifest();
135682
135875
  init_types3();
135876
+ KNOWN_REL_PATHS_LISTS = new WeakMap;
135683
135877
  TS_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"];
135684
135878
  STRUCTURAL_SEED_EXTENSIONS = new Set([".ts", ".tsx", ".js", ".jsx", ".py", ".rb", ".php", ".lua", ".c", ".h", ".cpp", ".hpp", ".go", ".rs", ".zig", ".java", ".kt", ".kts", ".scala", ".cs", ".swift", ".dart", ".ex", ".exs", ".erl", ".clj", ".ml", ".hs", ".vue", ".md", ".json", ".yaml", ".yml"]);
135685
135879
  });
135686
135880
 
135687
135881
  // ../../packages/core/dist/data/with-deadlock-retry.js
135882
+ function isConnectionPoolAcquisitionError(error51) {
135883
+ if (!error51 || typeof error51 !== "object")
135884
+ return false;
135885
+ const code = error51.code;
135886
+ if (code === "P2024")
135887
+ return true;
135888
+ const message = error51.message;
135889
+ if (typeof message !== "string")
135890
+ return false;
135891
+ return message.includes("Unable to start a transaction in the given time") || message.includes("Timed out fetching a new connection from the connection pool");
135892
+ }
135688
135893
  function isRetriableTransactionError(error51) {
135689
135894
  if (!error51 || typeof error51 !== "object")
135690
135895
  return false;
135896
+ if (isConnectionPoolAcquisitionError(error51))
135897
+ return true;
135691
135898
  const code = error51.code;
135692
135899
  if (typeof code === "string" && RETRIABLE_SQLSTATES.has(code))
135693
135900
  return true;
@@ -135700,17 +135907,23 @@ function isRetriableTransactionError(error51) {
135700
135907
  async function withDeadlockRetry(operation, options = {}) {
135701
135908
  const maxAttempts = options.maxAttempts ?? 5;
135702
135909
  const baseDelayMs = options.baseDelayMs ?? 75;
135703
- for (let attempt = 1;attempt <= maxAttempts; attempt++) {
135910
+ const connectionDelayMs = options.connectionDelayMs ?? 30000;
135911
+ const loopBound = Math.max(maxAttempts, 10);
135912
+ for (let attempt = 1;attempt <= loopBound; attempt++) {
135704
135913
  try {
135705
135914
  return await operation();
135706
135915
  } catch (error51) {
135707
- if (!isRetriableTransactionError(error51) || attempt === maxAttempts)
135916
+ if (!isRetriableTransactionError(error51))
135917
+ throw error51;
135918
+ const isConn = isConnectionPoolAcquisitionError(error51);
135919
+ const effectiveMax = isConn ? Math.max(maxAttempts, 10) : maxAttempts;
135920
+ if (attempt >= effectiveMax)
135708
135921
  throw error51;
135709
- const delayMs = baseDelayMs * 2 ** (attempt - 1);
135710
- logger.warn("Retriable DB lock cycle; retrying operation", {
135922
+ const delayMs = isConn ? connectionDelayMs * attempt : baseDelayMs * 2 ** (attempt - 1);
135923
+ logger.warn("Retriable DB failure; retrying operation", {
135711
135924
  operation: options.operation ?? "unknown",
135712
135925
  attempt,
135713
- maxAttempts,
135926
+ maxAttempts: effectiveMax,
135714
135927
  delayMs,
135715
135928
  error: error51
135716
135929
  });