@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.
package/dist/index.js CHANGED
@@ -27179,6 +27179,15 @@ function estimateTokens(text, type = "code") {
27179
27179
  const charsPerToken = type === "code" ? 4 : 5;
27180
27180
  return Math.ceil(text.length / charsPerToken);
27181
27181
  }
27182
+ function truncateToTokenLimit(text, limit, type = "code") {
27183
+ const charsPerToken = type === "code" ? 4 : 5;
27184
+ const maxChars = limit * charsPerToken;
27185
+ if (text.length <= maxChars) {
27186
+ return text;
27187
+ }
27188
+ return text.slice(0, maxChars) + `
27189
+ ... (truncated)`;
27190
+ }
27182
27191
  // ../../packages/shared/dist/utils/metrics.js
27183
27192
  var FALLBACK_PRICING, MetricsCollector;
27184
27193
  var init_metrics = __esm(() => {
@@ -59594,12 +59603,55 @@ function _isAbortOrTimeoutError(err) {
59594
59603
  }
59595
59604
  return false;
59596
59605
  }
59606
+ function _isConnectionError(err) {
59607
+ let cur = err;
59608
+ for (let hops = 0;cur && hops < 5; hops++, cur = cur.lastError ?? cur.cause) {
59609
+ const code = typeof cur.code === "string" ? cur.code : "";
59610
+ if (/^(ECONNREFUSED|ECONNRESET|ENOTFOUND|EHOSTUNREACH|ConnectionRefused|ConnectionClosed|FailedToOpenSocket)$/.test(code)) {
59611
+ return true;
59612
+ }
59613
+ const message = typeof cur.message === "string" ? cur.message : "";
59614
+ if (message.startsWith("Cannot connect to API"))
59615
+ return true;
59616
+ }
59617
+ return false;
59618
+ }
59597
59619
  function summarizeZodIssues(error51, maxIssues = 5) {
59598
59620
  return error51.issues.slice(0, maxIssues).map((issue2) => `${issue2.path.join(".") || "(root)"}: ${issue2.message}`).join("; ");
59599
59621
  }
59622
+ function isEndpointCircuitOpen(baseUrl) {
59623
+ const circuit = endpointCircuits.get(baseUrl);
59624
+ if (!circuit || circuit.failures < ENDPOINT_FAILURE_THRESHOLD)
59625
+ return false;
59626
+ const now2 = Date.now();
59627
+ if (now2 < circuit.openUntil)
59628
+ return true;
59629
+ circuit.openUntil = now2 + ENDPOINT_COOLDOWN_MS;
59630
+ return false;
59631
+ }
59632
+ function recordEndpointOutcome(baseUrl, err) {
59633
+ if (!err || !_isConnectionError(err)) {
59634
+ endpointCircuits.delete(baseUrl);
59635
+ return;
59636
+ }
59637
+ const circuit = endpointCircuits.get(baseUrl) ?? { failures: 0, openUntil: 0 };
59638
+ circuit.failures++;
59639
+ if (circuit.failures >= ENDPOINT_FAILURE_THRESHOLD) {
59640
+ circuit.openUntil = Date.now() + ENDPOINT_COOLDOWN_MS;
59641
+ }
59642
+ if (circuit.failures === ENDPOINT_FAILURE_THRESHOLD) {
59643
+ logger.warn("LLM endpoint unreachable \u2014 pausing LLM calls", {
59644
+ provider: resolveProviderIdForLogging(baseUrl),
59645
+ consecutiveConnectionFailures: circuit.failures,
59646
+ cooldownMs: ENDPOINT_COOLDOWN_MS
59647
+ });
59648
+ }
59649
+ endpointCircuits.set(baseUrl, circuit);
59650
+ }
59600
59651
  function recordLlmFailure(label, role, model, baseUrl, timeoutMs, elapsedMs, err) {
59601
59652
  const consecutiveFailures = (llmFailureStreaks.get(label) ?? 0) + 1;
59602
59653
  llmFailureStreaks.set(label, consecutiveFailures);
59654
+ recordEndpointOutcome(baseUrl, err);
59603
59655
  logger.warn("LLM call failed \u2014 using non-LLM fallback", {
59604
59656
  label,
59605
59657
  role,
@@ -59613,7 +59665,8 @@ function recordLlmFailure(label, role, model, baseUrl, timeoutMs, elapsedMs, err
59613
59665
  });
59614
59666
  return consecutiveFailures;
59615
59667
  }
59616
- function recordLlmSuccess(label, model) {
59668
+ function recordLlmSuccess(label, model, baseUrl) {
59669
+ recordEndpointOutcome(baseUrl, null);
59617
59670
  const priorFailures = llmFailureStreaks.get(label) ?? 0;
59618
59671
  if (priorFailures > 0) {
59619
59672
  logger.info("LLM call recovered", { label, model, afterFailures: priorFailures });
@@ -59625,6 +59678,9 @@ async function llmComplete(prompt, opts) {
59625
59678
  return { ok: false, error: "llm disabled" };
59626
59679
  }
59627
59680
  const llm = getLlmConfig({ modelRole: opts.modelRole });
59681
+ if (isEndpointCircuitOpen(llm.baseUrl)) {
59682
+ return { ok: false, error: "llm endpoint unreachable (circuit open)" };
59683
+ }
59628
59684
  const role = opts.modelRole ?? "instruct";
59629
59685
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
59630
59686
  const startedAt = Date.now();
@@ -59639,7 +59695,7 @@ async function llmComplete(prompt, opts) {
59639
59695
  });
59640
59696
  const text2 = result.text ?? "";
59641
59697
  if (text2.length > 0) {
59642
- recordLlmSuccess(opts.label, llm.model);
59698
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
59643
59699
  return { ok: true, value: text2 };
59644
59700
  }
59645
59701
  if (llm.disableThink) {
@@ -59648,7 +59704,7 @@ async function llmComplete(prompt, opts) {
59648
59704
  logger.warn("llmComplete: empty content \u2014 recovered from reasoning channel", {
59649
59705
  reasoningLen: reasoning.length
59650
59706
  });
59651
- recordLlmSuccess(opts.label, llm.model);
59707
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
59652
59708
  return { ok: true, value: reasoning };
59653
59709
  }
59654
59710
  logger.warn("llm reasoning-recovery empty", {
@@ -59669,6 +59725,9 @@ async function llmObject(prompt, schema, opts) {
59669
59725
  return { ok: false, error: "llm disabled" };
59670
59726
  }
59671
59727
  const llm = getLlmConfig({ modelRole: opts.modelRole });
59728
+ if (isEndpointCircuitOpen(llm.baseUrl)) {
59729
+ return { ok: false, error: "llm endpoint unreachable (circuit open)" };
59730
+ }
59672
59731
  const role = opts.modelRole ?? "instruct";
59673
59732
  const timeoutMs = opts.timeoutMs ?? llm.timeoutMs;
59674
59733
  const startedAt = Date.now();
@@ -59687,7 +59746,7 @@ async function llmObject(prompt, schema, opts) {
59687
59746
  abortSignal: timeoutSignal(timeoutMs)
59688
59747
  });
59689
59748
  logger.debug("json_schema: constrained decoding used", { label: opts.label, model: llm.model });
59690
- recordLlmSuccess(opts.label, llm.model);
59749
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
59691
59750
  return { ok: true, value: result.object };
59692
59751
  }
59693
59752
  result = await generateObject({
@@ -59702,7 +59761,7 @@ async function llmObject(prompt, schema, opts) {
59702
59761
  const validated = schema.safeParse(result.object);
59703
59762
  if (validated.success) {
59704
59763
  logger.debug("json_schema: fallback to json_object \u2014 validated", { label: opts.label, model: llm.model });
59705
- recordLlmSuccess(opts.label, llm.model);
59764
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
59706
59765
  return { ok: true, value: validated.data };
59707
59766
  }
59708
59767
  if (llm.disableThink) {
@@ -59715,7 +59774,7 @@ async function llmObject(prompt, schema, opts) {
59715
59774
  logger.warn("llmObject: recovered object from reasoning channel (fallback path)", {
59716
59775
  reasoningLen: reasoning.length
59717
59776
  });
59718
- recordLlmSuccess(opts.label, llm.model);
59777
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
59719
59778
  return { ok: true, value: recovered.data };
59720
59779
  }
59721
59780
  }
@@ -59727,7 +59786,7 @@ async function llmObject(prompt, schema, opts) {
59727
59786
  recordLlmFailure(opts.label, role, llm.model, llm.baseUrl, timeoutMs, Date.now() - startedAt, validationErr);
59728
59787
  return { ok: false, error: validationErr.message };
59729
59788
  } catch (e) {
59730
- if (llm.disableThink && !_isAbortOrTimeoutError(e)) {
59789
+ if (llm.disableThink && !_isAbortOrTimeoutError(e) && !_isConnectionError(e)) {
59731
59790
  const reasoning = _reasoningToText(result).length > 0 ? _reasoningToText(result) : _reasoningToText(e);
59732
59791
  if (reasoning.length > 0) {
59733
59792
  const parsed = _extractJsonObject(reasoning);
@@ -59737,7 +59796,7 @@ async function llmObject(prompt, schema, opts) {
59737
59796
  logger.warn("llmObject: recovered object from reasoning channel", {
59738
59797
  reasoningLen: reasoning.length
59739
59798
  });
59740
- recordLlmSuccess(opts.label, llm.model);
59799
+ recordLlmSuccess(opts.label, llm.model, llm.baseUrl);
59741
59800
  return { ok: true, value: validated.data };
59742
59801
  }
59743
59802
  }
@@ -59751,7 +59810,7 @@ async function llmObject(prompt, schema, opts) {
59751
59810
  return { ok: false, error: e.message };
59752
59811
  }
59753
59812
  }
59754
- var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llmFailureStreaks, llm;
59813
+ var _jsonSchemaSupported = null, testEnabledOverride = null, testBaseUrlOverride = null, llmFailureStreaks, ENDPOINT_FAILURE_THRESHOLD = 3, ENDPOINT_COOLDOWN_MS = 60000, endpointCircuits, llm;
59755
59814
  var init_llm_client = __esm(() => {
59756
59815
  init_dist6();
59757
59816
  init_dist7();
@@ -59759,6 +59818,7 @@ var init_llm_client = __esm(() => {
59759
59818
  init_config();
59760
59819
  init_inference_providers();
59761
59820
  llmFailureStreaks = new Map;
59821
+ endpointCircuits = new Map;
59762
59822
  llm = {
59763
59823
  complete: llmComplete,
59764
59824
  object: llmObject,
@@ -130028,14 +130088,80 @@ function indexDefinitions(definitions) {
130028
130088
  });
130029
130089
  return { registry: registry3, definitions: Object.freeze(indexed) };
130030
130090
  }
130031
- function candidateKind(reference, definition) {
130032
- if (reference.kind === "type_ref" || reference.kind === "extend" || reference.kind === "implement") {
130033
- return ["class", "interface", "trait", "enum", "type", "type_parameter"].includes(definition.identity.kind);
130034
- }
130035
- if (reference.kind === "call" || reference.kind === "data_flow" || reference.kind === "http_call") {
130036
- return ["function", "method", "constructor", "class", "field", "variable", "constant", "export"].includes(definition.identity.kind);
130037
- }
130038
- return false;
130091
+ function buildPartition(list) {
130092
+ const byFqn = new Map;
130093
+ const byFile = new Map;
130094
+ const byFileQualifiedName = new Map;
130095
+ const byQualifiedName = new Map;
130096
+ for (const definition of list) {
130097
+ const identity = definition.identity;
130098
+ if (!byFqn.has(identity.fqn))
130099
+ byFqn.set(identity.fqn, definition);
130100
+ const fileBucket = byFile.get(identity.file);
130101
+ if (fileBucket)
130102
+ fileBucket.push(definition);
130103
+ else
130104
+ byFile.set(identity.file, [definition]);
130105
+ const fileQualifiedNameKey = `${identity.file}\x00${identity.qualifiedName}`;
130106
+ const fileQualifiedNameBucket = byFileQualifiedName.get(fileQualifiedNameKey);
130107
+ if (fileQualifiedNameBucket)
130108
+ fileQualifiedNameBucket.push(definition);
130109
+ else
130110
+ byFileQualifiedName.set(fileQualifiedNameKey, [definition]);
130111
+ const qualifiedNameBucket = byQualifiedName.get(identity.qualifiedName);
130112
+ if (qualifiedNameBucket)
130113
+ qualifiedNameBucket.push(definition);
130114
+ else
130115
+ byQualifiedName.set(identity.qualifiedName, [definition]);
130116
+ }
130117
+ return { list, byFqn, byFile, byFileQualifiedName, byQualifiedName };
130118
+ }
130119
+ function buildScopedIndex(rawDefinitions, familyOnly) {
130120
+ const scoped = familyOnly ? rawDefinitions.filter((definition) => FAMILY_DIALECTS.has(definition.identity.dialect)) : rawDefinitions;
130121
+ const { registry: registry3, definitions: all } = indexDefinitions(scoped);
130122
+ const typeRefs = [];
130123
+ const calls = [];
130124
+ for (const definition of all) {
130125
+ if (TYPE_REF_KINDS.has(definition.identity.kind))
130126
+ typeRefs.push(definition);
130127
+ if (CALL_KINDS.has(definition.identity.kind))
130128
+ calls.push(definition);
130129
+ }
130130
+ return { registry: registry3, typeRefs: buildPartition(typeRefs), calls: buildPartition(calls), all: buildPartition(all) };
130131
+ }
130132
+ function definitionIndex(rawDefinitions, familyOnly) {
130133
+ let byScope = RESOLVE_INDEX_CACHE.get(rawDefinitions);
130134
+ if (!byScope) {
130135
+ byScope = new Map;
130136
+ RESOLVE_INDEX_CACHE.set(rawDefinitions, byScope);
130137
+ }
130138
+ const existing = byScope.get(familyOnly);
130139
+ if (existing)
130140
+ return existing;
130141
+ const built = buildScopedIndex(rawDefinitions, familyOnly);
130142
+ byScope.set(familyOnly, built);
130143
+ return built;
130144
+ }
130145
+ function cachedDialectScope(definitions, dialectKey, predicate) {
130146
+ let byKey = DIALECT_SCOPE_CACHE.get(definitions);
130147
+ if (!byKey) {
130148
+ byKey = new Map;
130149
+ DIALECT_SCOPE_CACHE.set(definitions, byKey);
130150
+ }
130151
+ const existing = byKey.get(dialectKey);
130152
+ if (existing)
130153
+ return existing;
130154
+ const scoped = definitions.filter((definition) => predicate(definition));
130155
+ byKey.set(dialectKey, scoped);
130156
+ return scoped;
130157
+ }
130158
+ function normalizedKnownFiles(knownFiles) {
130159
+ const existing = KNOWN_FILES_CACHE.get(knownFiles);
130160
+ if (existing)
130161
+ return existing;
130162
+ const built = new Set(knownFiles.map(normalizeStructuralFile));
130163
+ KNOWN_FILES_CACHE.set(knownFiles, built);
130164
+ return built;
130039
130165
  }
130040
130166
  function probe(base, known, dialect = "typescript") {
130041
130167
  const bases = /\.[cm]?jsx?$/u.test(base) ? [base.replace(/\.[cm]?jsx?$/u, ".ts"), base.replace(/\.[cm]?jsx?$/u, ".tsx"), base] : [base];
@@ -130048,7 +130174,7 @@ function probe(base, known, dialect = "typescript") {
130048
130174
  return;
130049
130175
  }
130050
130176
  function resolveStructuralSpecifier(specifier, fromFile, build, dialect = "typescript") {
130051
- const known = new Set(build.knownFiles.map(normalizeStructuralFile));
130177
+ const known = normalizedKnownFiles(build.knownFiles);
130052
130178
  if (specifier.startsWith("./") || specifier.startsWith("../")) {
130053
130179
  return probe(path25.posix.join(path25.posix.dirname(fromFile), specifier), known, dialect);
130054
130180
  }
@@ -130085,12 +130211,12 @@ function matchesStructuralPathAlias(specifier, aliases) {
130085
130211
  return specifier.startsWith(prefix) && specifier.endsWith(suffix) && specifier.length >= prefix.length + suffix.length;
130086
130212
  });
130087
130213
  }
130088
- function exportedMatches(file2, sought, defaultOnly, definitions, build, visited = new Set) {
130214
+ function exportedMatches(file2, sought, defaultOnly, partition, build, visited = new Set) {
130089
130215
  const key = `${file2}\x00${sought}\x00${defaultOnly}`;
130090
130216
  if (visited.has(key))
130091
130217
  return [];
130092
130218
  visited.add(key);
130093
- const direct = definitions.filter((definition) => definition.identity.file === file2 && definition.exported && (defaultOnly ? definition.defaultExport : definition.identity.qualifiedName === sought));
130219
+ const direct = (partition.byFile.get(file2) ?? []).filter((definition) => definition.exported && (defaultOnly ? definition.defaultExport : definition.identity.qualifiedName === sought));
130094
130220
  const concrete = direct.filter((definition) => definition.identity.kind !== "export");
130095
130221
  if (concrete.length > 0) {
130096
130222
  if (!defaultOnly)
@@ -130108,7 +130234,7 @@ function exportedMatches(file2, sought, defaultOnly, definitions, build, visited
130108
130234
  for (const binding of reexport.bindings) {
130109
130235
  if (binding.local !== sought && binding.imported !== "*")
130110
130236
  continue;
130111
- forwarded.push(...exportedMatches(targetFile, binding.imported === "*" ? sought : binding.imported, defaultOnly || binding.imported === "default", definitions, build, visited));
130237
+ forwarded.push(...exportedMatches(targetFile, binding.imported === "*" ? sought : binding.imported, defaultOnly || binding.imported === "default", partition, build, visited));
130112
130238
  }
130113
130239
  }
130114
130240
  if (forwarded.length > 0)
@@ -130118,7 +130244,7 @@ function exportedMatches(file2, sought, defaultOnly, definitions, build, visited
130118
130244
  const namedDefault = direct.filter((definition) => definition.identity.name !== "default");
130119
130245
  return namedDefault.length > 0 ? namedDefault : direct;
130120
130246
  }
130121
- function importedMatches(file2, reference, definitions, build) {
130247
+ function importedMatches(file2, reference, partition, build) {
130122
130248
  const matches = [];
130123
130249
  let claimed = false;
130124
130250
  for (const imported of file2.imports) {
@@ -130160,31 +130286,30 @@ function importedMatches(file2, reference, definitions, build) {
130160
130286
  }
130161
130287
  if ((imported.typeOnly || binding.typeOnly) && !typeEdge)
130162
130288
  continue;
130163
- 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);
130289
+ 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);
130164
130290
  if (!importedFile)
130165
130291
  continue;
130166
130292
  const esmDefaultMember = imported.form === "esm_import" && binding.imported === "default" && qualifier[0] === binding.local;
130167
130293
  if (esmDefaultMember && sought !== undefined) {
130168
- const owners = exportedMatches(importedFile, "default", true, definitions, build);
130294
+ const owners = exportedMatches(importedFile, "default", true, partition, build);
130169
130295
  for (const owner of owners) {
130170
130296
  const ownerMember = `${owner.identity.qualifiedName}.${sought}`;
130171
- matches.push(...definitions.filter((definition) => definition.identity.file === owner.identity.file && definition.exported && definition.identity.qualifiedName === ownerMember));
130297
+ matches.push(...(partition.byFileQualifiedName.get(`${owner.identity.file}\x00${ownerMember}`) ?? []).filter((definition) => definition.exported));
130172
130298
  }
130173
130299
  continue;
130174
130300
  }
130175
130301
  if (defaultOnly)
130176
- matches.push(...exportedMatches(importedFile, "default", true, definitions, build));
130302
+ matches.push(...exportedMatches(importedFile, "default", true, partition, build));
130177
130303
  else if (sought !== undefined)
130178
- matches.push(...exportedMatches(importedFile, sought, false, definitions, build).filter((definition) => binding.arity === undefined || definition.arity === binding.arity));
130304
+ matches.push(...exportedMatches(importedFile, sought, false, partition, build).filter((definition) => binding.arity === undefined || definition.arity === binding.arity));
130179
130305
  }
130180
130306
  }
130181
130307
  return { matches, claimed };
130182
130308
  }
130183
- function sameFileMatches(file2, reference, definitions) {
130184
- const local = definitions.filter((definition) => definition.identity.file === file2);
130309
+ function sameFileMatches(file2, reference, partition) {
130185
130310
  if (reference.qualifier && reference.qualifier !== "this") {
130186
130311
  const exact = `${reference.qualifier}.${reference.name}`;
130187
- return local.filter((definition) => definition.identity.qualifiedName === exact);
130312
+ return partition.byFileQualifiedName.get(`${file2}\x00${exact}`) ?? [];
130188
130313
  }
130189
130314
  const lexical = reference.lexicalScope?.split(".").filter(Boolean) ?? [];
130190
130315
  if (lexical.length > 0)
@@ -130192,7 +130317,7 @@ function sameFileMatches(file2, reference, definitions) {
130192
130317
  for (let length = lexical.length;length >= 0; length -= 1) {
130193
130318
  const prefix = lexical.slice(0, length).join(".");
130194
130319
  const exact = prefix ? `${prefix}.${reference.name}` : reference.name;
130195
- const matches = local.filter((definition) => definition.identity.qualifiedName === exact);
130320
+ const matches = partition.byFileQualifiedName.get(`${file2}\x00${exact}`) ?? [];
130196
130321
  if (matches.length > 0)
130197
130322
  return matches;
130198
130323
  if (reference.qualifier === "this")
@@ -130200,7 +130325,7 @@ function sameFileMatches(file2, reference, definitions) {
130200
130325
  }
130201
130326
  return [];
130202
130327
  }
130203
- var TYPESCRIPT_RESOLVER_VERSION = "1.0.0", DIALECT_PROBES, REQUIRE_IMPORT_FORMS, TYPESCRIPT_LANGUAGE_RESOLVER;
130328
+ 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;
130204
130329
  var init_typescript2 = __esm(() => {
130205
130330
  init_fqn_codec();
130206
130331
  DIALECT_PROBES = Object.freeze({
@@ -130235,6 +130360,27 @@ var init_typescript2 = __esm(() => {
130235
130360
  ocaml: ["", ".ml"],
130236
130361
  haskell: ["", ".hs"]
130237
130362
  });
130363
+ TYPE_REF_KINDS = new Set(["class", "interface", "trait", "enum", "type", "type_parameter"]);
130364
+ CALL_KINDS = new Set(["function", "method", "constructor", "class", "field", "variable", "constant", "export"]);
130365
+ FAMILY_DIALECTS = new Set(["typescript", "tsx", "javascript", "jsx", "sfc"]);
130366
+ REFERENCE_PARTITION = Object.freeze({
130367
+ type_ref: "typeRefs",
130368
+ extend: "typeRefs",
130369
+ implement: "typeRefs",
130370
+ call: "calls",
130371
+ data_flow: "calls",
130372
+ http_call: "calls"
130373
+ });
130374
+ EMPTY_PARTITION = Object.freeze({
130375
+ list: Object.freeze([]),
130376
+ byFqn: new Map,
130377
+ byFile: new Map,
130378
+ byFileQualifiedName: new Map,
130379
+ byQualifiedName: new Map
130380
+ });
130381
+ RESOLVE_INDEX_CACHE = new WeakMap;
130382
+ DIALECT_SCOPE_CACHE = new WeakMap;
130383
+ KNOWN_FILES_CACHE = new WeakMap;
130238
130384
  REQUIRE_IMPORT_FORMS = new Set(["commonjs_require", "dynamic_import", "ruby_require", "lua_require"]);
130239
130385
  TYPESCRIPT_LANGUAGE_RESOLVER = Object.freeze({
130240
130386
  version: TYPESCRIPT_RESOLVER_VERSION,
@@ -130242,21 +130388,19 @@ var init_typescript2 = __esm(() => {
130242
130388
  resolve(file2, rawReference, rawDefinitions, build) {
130243
130389
  const normalizedFile = normalizeStructuralFile(file2.file);
130244
130390
  const reference = normalizedReference(rawReference);
130245
- const familyDialects = ["typescript", "tsx", "javascript", "jsx", "sfc"];
130246
- const scopedDefinitions = familyDialects.includes(file2.dialect) ? rawDefinitions.filter((definition) => familyDialects.includes(definition.identity.dialect)) : rawDefinitions;
130247
- const { registry: registry3, definitions: allDefinitions } = indexDefinitions(scopedDefinitions);
130248
- const definitions = allDefinitions.filter((definition) => candidateKind(reference, definition));
130391
+ const index = definitionIndex(rawDefinitions, FAMILY_DIALECTS.has(file2.dialect));
130392
+ const partition = reference.kind && REFERENCE_PARTITION[reference.kind] ? index[REFERENCE_PARTITION[reference.kind]] : EMPTY_PARTITION;
130249
130393
  if (reference.existingFqn) {
130250
- const prepared = definitions.find((definition) => definition.identity.fqn === reference.existingFqn)?.identity;
130251
- const exact = prepared ? { found: true, identity: prepared } : registry3.resolveModern(reference.existingFqn);
130394
+ const prepared = partition.byFqn.get(reference.existingFqn)?.identity;
130395
+ const exact = prepared ? { found: true, identity: prepared } : index.registry.resolveModern(reference.existingFqn);
130252
130396
  return exact.found ? Object.freeze({ status: "resolved", fqn: exact.identity.fqn, identity: exact.identity, source: "exact" }) : Object.freeze({ status: "unresolved", name: reference.existingFqn });
130253
130397
  }
130254
130398
  const soughtQualified = reference.qualifier ? `${reference.qualifier}.${reference.name}` : reference.name;
130255
- const local = sameFileMatches(normalizedFile, reference, definitions);
130399
+ const local = sameFileMatches(normalizedFile, reference, partition);
130256
130400
  const localOutcome = outcome(reference, local, "same_file");
130257
130401
  if (localOutcome)
130258
130402
  return localOutcome;
130259
- const imported = importedMatches({ ...file2, file: normalizedFile }, reference, definitions, build);
130403
+ const imported = importedMatches({ ...file2, file: normalizedFile }, reference, partition, build);
130260
130404
  const importOutcome = outcome(reference, imported.matches, "import");
130261
130405
  if (importOutcome)
130262
130406
  return importOutcome;
@@ -130266,16 +130410,16 @@ var init_typescript2 = __esm(() => {
130266
130410
  name: reference.name,
130267
130411
  ...reference.qualifier ? { qualifier: reference.qualifier } : {}
130268
130412
  });
130269
- const global2 = definitions.filter((definition) => definition.exported && (reference.qualifier ? definition.identity.qualifiedName === soughtQualified : definition.identity.name === reference.name && definition.identity.qualifiedName === definition.identity.name));
130270
- return outcome(reference, global2, "global") ?? Object.freeze({
130413
+ 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);
130414
+ return outcome(reference, globalBucket, "global") ?? Object.freeze({
130271
130415
  status: "unresolved",
130272
130416
  name: reference.name,
130273
130417
  ...reference.qualifier ? { qualifier: reference.qualifier } : {}
130274
130418
  });
130275
130419
  },
130276
130420
  resolveLegacy(legacyFqn, rawDefinitions) {
130277
- const { registry: registry3, definitions } = indexDefinitions(rawDefinitions);
130278
- const materialized = definitions.filter((definition) => definition.identity.legacyFqn === legacyFqn);
130421
+ const { registry: registry3, all } = definitionIndex(rawDefinitions, false);
130422
+ const materialized = all.list.filter((definition) => definition.identity.legacyFqn === legacyFqn);
130279
130423
  const materializedOutcome = outcome({ kind: "call", span: { startByte: 0, endByte: 0, start: { row: 0, column: 0 }, end: { row: 0, column: 0 } }, name: legacyFqn }, materialized, "legacy");
130280
130424
  if (materializedOutcome)
130281
130425
  return materializedOutcome;
@@ -130308,7 +130452,7 @@ var init_scripting2 = __esm(() => {
130308
130452
  ...TYPESCRIPT_LANGUAGE_RESOLVER,
130309
130453
  dialects: Object.freeze(["python", "ruby", "php", "lua-luajit"]),
130310
130454
  resolve(file2, reference, definitions, build) {
130311
- return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(file2, reference, definitions.filter((definition) => definition.identity.dialect === file2.dialect), build);
130455
+ return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(file2, reference, cachedDialectScope(definitions, file2.dialect, (definition) => definition.identity.dialect === file2.dialect), build);
130312
130456
  }
130313
130457
  });
130314
130458
  });
@@ -130324,6 +130468,7 @@ var init_systems2 = __esm(() => {
130324
130468
  dialects: DIALECTS,
130325
130469
  resolve(file2, reference, definitions, build) {
130326
130470
  const compatible = file2.dialect === "header-default-c" ? ["c", "header-default-c"] : file2.dialect === "header-cpp" || file2.dialect === "header" ? ["cpp", "header", "header-cpp"] : [file2.dialect];
130471
+ const compatibleKey = compatible.join(",");
130327
130472
  const unresolvedTarget = reference.target.status === "unresolved" ? reference.target : undefined;
130328
130473
  const resolverFile = file2.dialect === "rust" ? {
130329
130474
  ...file2,
@@ -130342,7 +130487,7 @@ var init_systems2 = __esm(() => {
130342
130487
  return { ...item, bindings };
130343
130488
  })
130344
130489
  } : file2;
130345
- return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, definitions.filter((item) => compatible.includes(item.identity.dialect)), build);
130490
+ return TYPESCRIPT_LANGUAGE_RESOLVER.resolve(resolverFile, reference, cachedDialectScope(definitions, compatibleKey, (item) => compatible.includes(item.identity.dialect)), build);
130346
130491
  }
130347
130492
  });
130348
130493
  });
@@ -130387,7 +130532,7 @@ var init_managed2 = __esm(() => {
130387
130532
  return imported;
130388
130533
  return { ...imported, bindings: imported.bindings.map((binding) => binding.imported === "*" && binding.local === "*" ? { ...binding, imported: unresolved2.name, local: unresolved2.name } : binding) };
130389
130534
  }) } : file2;
130390
- 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);
130535
+ 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);
130391
130536
  }
130392
130537
  });
130393
130538
  });
@@ -130415,7 +130560,7 @@ var init_functional2 = __esm(() => {
130415
130560
  return imported;
130416
130561
  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}` }) };
130417
130562
  }) } : file2;
130418
- 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);
130563
+ 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);
130419
130564
  }
130420
130565
  });
130421
130566
  });
@@ -130433,6 +130578,14 @@ var init_data_document2 = __esm(() => {
130433
130578
  // ../../packages/core/dist/services/etl/stages/resolve.js
130434
130579
  import path27 from "path";
130435
130580
  import fs18 from "fs";
130581
+ function knownRelPathsList(knownRelPaths) {
130582
+ const existing = KNOWN_REL_PATHS_LISTS.get(knownRelPaths);
130583
+ if (existing)
130584
+ return existing;
130585
+ const built = Object.freeze([...knownRelPaths]);
130586
+ KNOWN_REL_PATHS_LISTS.set(knownRelPaths, built);
130587
+ return built;
130588
+ }
130436
130589
 
130437
130590
  class ResolveStage {
130438
130591
  symbolRepository;
@@ -130516,7 +130669,7 @@ class ResolveStage {
130516
130669
  resolveStructuralFile(parsed, session2, knownRelPaths, rootAliases, monorepoPackages) {
130517
130670
  const filePath = parsed.file.relativePath;
130518
130671
  const structuralAliases = this.structuralAliasesFor(filePath, rootAliases, monorepoPackages);
130519
- const build = { knownFiles: [...knownRelPaths], pathAliasesByFile: { [filePath]: structuralAliases } };
130672
+ const build = { knownFiles: knownRelPathsList(knownRelPaths), pathAliasesByFile: { [filePath]: structuralAliases } };
130520
130673
  const resolvedImports = parsed.rawImports.map((raw2) => {
130521
130674
  const resolvedPath = resolveStructuralSpecifier(raw2.specifier, filePath, build) ?? null;
130522
130675
  return {
@@ -130816,7 +130969,7 @@ class ResolveStage {
130816
130969
  }));
130817
130970
  }
130818
130971
  }
130819
- var TS_EXTENSIONS, STRUCTURAL_SEED_EXTENSIONS;
130972
+ var KNOWN_REL_PATHS_LISTS, TS_EXTENSIONS, STRUCTURAL_SEED_EXTENSIONS;
130820
130973
  var init_resolve = __esm(() => {
130821
130974
  init_dist();
130822
130975
  init_symbol_repository_factory();
@@ -130830,14 +130983,28 @@ var init_resolve = __esm(() => {
130830
130983
  init_fqn_codec();
130831
130984
  init_language_manifest();
130832
130985
  init_types3();
130986
+ KNOWN_REL_PATHS_LISTS = new WeakMap;
130833
130987
  TS_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"];
130834
130988
  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"]);
130835
130989
  });
130836
130990
 
130837
130991
  // ../../packages/core/dist/data/with-deadlock-retry.js
130992
+ function isConnectionPoolAcquisitionError(error51) {
130993
+ if (!error51 || typeof error51 !== "object")
130994
+ return false;
130995
+ const code = error51.code;
130996
+ if (code === "P2024")
130997
+ return true;
130998
+ const message = error51.message;
130999
+ if (typeof message !== "string")
131000
+ return false;
131001
+ return message.includes("Unable to start a transaction in the given time") || message.includes("Timed out fetching a new connection from the connection pool");
131002
+ }
130838
131003
  function isRetriableTransactionError(error51) {
130839
131004
  if (!error51 || typeof error51 !== "object")
130840
131005
  return false;
131006
+ if (isConnectionPoolAcquisitionError(error51))
131007
+ return true;
130841
131008
  const code = error51.code;
130842
131009
  if (typeof code === "string" && RETRIABLE_SQLSTATES.has(code))
130843
131010
  return true;
@@ -130850,17 +131017,23 @@ function isRetriableTransactionError(error51) {
130850
131017
  async function withDeadlockRetry(operation, options = {}) {
130851
131018
  const maxAttempts = options.maxAttempts ?? 5;
130852
131019
  const baseDelayMs = options.baseDelayMs ?? 75;
130853
- for (let attempt = 1;attempt <= maxAttempts; attempt++) {
131020
+ const connectionDelayMs = options.connectionDelayMs ?? 30000;
131021
+ const loopBound = Math.max(maxAttempts, 10);
131022
+ for (let attempt = 1;attempt <= loopBound; attempt++) {
130854
131023
  try {
130855
131024
  return await operation();
130856
131025
  } catch (error51) {
130857
- if (!isRetriableTransactionError(error51) || attempt === maxAttempts)
131026
+ if (!isRetriableTransactionError(error51))
131027
+ throw error51;
131028
+ const isConn = isConnectionPoolAcquisitionError(error51);
131029
+ const effectiveMax = isConn ? Math.max(maxAttempts, 10) : maxAttempts;
131030
+ if (attempt >= effectiveMax)
130858
131031
  throw error51;
130859
- const delayMs = baseDelayMs * 2 ** (attempt - 1);
130860
- logger.warn("Retriable DB lock cycle; retrying operation", {
131032
+ const delayMs = isConn ? connectionDelayMs * attempt : baseDelayMs * 2 ** (attempt - 1);
131033
+ logger.warn("Retriable DB failure; retrying operation", {
130861
131034
  operation: options.operation ?? "unknown",
130862
131035
  attempt,
130863
- maxAttempts,
131036
+ maxAttempts: effectiveMax,
130864
131037
  delayMs,
130865
131038
  error: error51
130866
131039
  });
@@ -146632,6 +146805,7 @@ var init_auto_improve_job = __esm(() => {
146632
146805
  var exports_observation_consolidation_job = {};
146633
146806
  __export(exports_observation_consolidation_job, {
146634
146807
  observationConsolidationJob: () => observationConsolidationJob,
146808
+ buildObservationPrompt: () => buildObservationPrompt,
146635
146809
  ObservationConsolidationJob: () => ObservationConsolidationJob
146636
146810
  });
146637
146811
  import { randomUUID as randomUUID9 } from "crypto";
@@ -146659,6 +146833,7 @@ class ObservationConsolidationJob {
146659
146833
  maxWindow;
146660
146834
  lastRunAt = 0;
146661
146835
  newSinceRun = 0;
146836
+ running = false;
146662
146837
  runCalls = 0;
146663
146838
  get store() {
146664
146839
  return this.injectedStore ?? getObservationStore();
@@ -146702,6 +146877,18 @@ class ObservationConsolidationJob {
146702
146877
  }
146703
146878
  async runOnce(projectId) {
146704
146879
  this.runCalls++;
146880
+ if (this.running) {
146881
+ logger.debug("observation consolidation: skipped, a run is in flight", { projectId });
146882
+ return { consolidated: false, batchesCreated: 0 };
146883
+ }
146884
+ this.running = true;
146885
+ try {
146886
+ return await this.consolidateWindow(projectId);
146887
+ } finally {
146888
+ this.running = false;
146889
+ }
146890
+ }
146891
+ async consolidateWindow(projectId) {
146705
146892
  const noop2 = {
146706
146893
  consolidated: false,
146707
146894
  batchesCreated: 0
@@ -146791,8 +146978,9 @@ class ObservationConsolidationJob {
146791
146978
  }
146792
146979
  }
146793
146980
  function buildObservationPrompt(window2) {
146981
+ const observationTokens = Math.min(MAX_OBSERVATION_TOKENS, Math.floor(MAX_WINDOW_TOKENS / Math.max(window2.length, 1)));
146794
146982
  const items = window2.map((o, i) => `[${i}] id=${o.id} source=${o.source} importance=${o.importance.toFixed(2)}
146795
- ${o.payloadJson}`).join(`
146983
+ ${digestPayload(o.payloadJson, observationTokens)}`).join(`
146796
146984
  `);
146797
146985
  return [
146798
146986
  "You are consolidating a window of passive lifecycle observations (agent telemetry)",
@@ -146807,7 +146995,20 @@ ${o.payloadJson}`).join(`
146807
146995
  ].join(`
146808
146996
  `);
146809
146997
  }
146810
- var FALLBACK_BRIDGE, observationConsolidationJob;
146998
+ function digestPayload(payloadJson, maxTokens) {
146999
+ let payload;
147000
+ try {
147001
+ payload = JSON.parse(payloadJson);
147002
+ } catch {
147003
+ return truncateToTokenLimit(payloadJson, maxTokens);
147004
+ }
147005
+ if (payload && typeof payload === "object" && !Array.isArray(payload)) {
147006
+ payload = Object.fromEntries(Object.entries(payload).filter(([key]) => !PROMPT_BOOKKEEPING_KEYS.has(key)));
147007
+ }
147008
+ 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);
147009
+ return truncateToTokenLimit(compact ?? "", maxTokens);
147010
+ }
147011
+ var FALLBACK_BRIDGE, observationConsolidationJob, PROMPT_BOOKKEEPING_KEYS, MAX_PROMPT_FIELD_CHARS = 400, MAX_OBSERVATION_TOKENS = 300, MAX_WINDOW_TOKENS = 2400;
146811
147012
  var init_observation_consolidation_job = __esm(() => {
146812
147013
  init_dist();
146813
147014
  init_dist();
@@ -146823,6 +147024,18 @@ var init_observation_consolidation_job = __esm(() => {
146823
147024
  maxWindow: 8
146824
147025
  };
146825
147026
  observationConsolidationJob = new ObservationConsolidationJob;
147027
+ PROMPT_BOOKKEEPING_KEYS = new Set([
147028
+ "session_id",
147029
+ "transcript_path",
147030
+ "cwd",
147031
+ "prompt_id",
147032
+ "tool_use_id",
147033
+ "agent_id",
147034
+ "hook_event_name",
147035
+ "permission_mode",
147036
+ "effort",
147037
+ "duration_ms"
147038
+ ]);
146826
147039
  });
146827
147040
 
146828
147041
  // ../../packages/core/dist/services/scheduler/scheduler-defaults.js