@warmdrift/kgauto-compiler 2.0.0-alpha.63 → 2.0.0-alpha.65

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.mjs CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  import {
16
16
  LIBRARY_VERSION,
17
17
  createKeyHealthRoute
18
- } from "./chunk-ZU62HRWK.mjs";
18
+ } from "./chunk-XTZ2ZQJQ.mjs";
19
19
  import {
20
20
  ABSOLUTE_FLOOR,
21
21
  ARCHETYPE_FLOOR_DEFAULT,
@@ -40,7 +40,7 @@ import {
40
40
  loadChainsFromBrain,
41
41
  readBrainReadEnv,
42
42
  resolveProviderKey
43
- } from "./chunk-YZRPNSSQ.mjs";
43
+ } from "./chunk-DJVGJEJU.mjs";
44
44
  import {
45
45
  ALIASES,
46
46
  LATENCY_TIER_MS,
@@ -51,7 +51,7 @@ import {
51
51
  latencyTierOf,
52
52
  profilesByProvider,
53
53
  tryGetProfile
54
- } from "./chunk-QKXTMVCT.mjs";
54
+ } from "./chunk-4UO4CCSP.mjs";
55
55
  import {
56
56
  emitAdvisoryFired,
57
57
  emitCompileDone,
@@ -739,6 +739,7 @@ function passApplyCliffs(ir, profile, estimatedInputTokens) {
739
739
  var LATENCY_OVERAGE_WEIGHT = 0.6;
740
740
  var LATENCY_PENALTY_CAP = 1;
741
741
  var QUALITY_GATE_PENALTY = 4;
742
+ var PROMOTION_BOOST = 5;
742
743
  function effectiveConventions(profile) {
743
744
  const own = profile.archetypeConventions ?? [];
744
745
  if (own.length > 0) return own;
@@ -756,6 +757,9 @@ function passScoreTargets(ir, opts) {
756
757
  const preferredSet = new Set(policy.preferredModels ?? []);
757
758
  const scores = [];
758
759
  const policyMutations = [];
760
+ const rawPromotion = opts.promotion;
761
+ const promotionDeferred = rawPromotion !== void 0 && (policy.preferredModels?.length ?? 0) > 0;
762
+ const promotion = promotionDeferred ? void 0 : rawPromotion;
759
763
  const modelIds = ir.models.filter((m) => typeof m === "string");
760
764
  for (const modelId of modelIds) {
761
765
  let profile;
@@ -820,7 +824,12 @@ function passScoreTargets(ir, opts) {
820
824
  );
821
825
  if (schemaWeak) qualityGatePenalty = QUALITY_GATE_PENALTY;
822
826
  }
823
- const rank = qualityScore + callerOrderBoost - costPenalty - reasons.length * 10 + preferredBoost - latencyPenalty - qualityGatePenalty;
827
+ const isPromoted = promotion?.promotedModel === modelId;
828
+ if (isPromoted && promotion.suppressQualityGate) {
829
+ qualityGatePenalty = 0;
830
+ }
831
+ const promotionBoost = isPromoted ? PROMOTION_BOOST : 0;
832
+ const rank = qualityScore + callerOrderBoost - costPenalty - reasons.length * 10 + preferredBoost - latencyPenalty - qualityGatePenalty + promotionBoost;
824
833
  scores.push({
825
834
  modelId,
826
835
  estimatedCostUsd,
@@ -870,6 +879,22 @@ function passScoreTargets(ir, opts) {
870
879
  description: `Model ${modelId} gated below the quality floor for archetype '${ir.intent.archetype}' \u2014 declared structuredOutput + kgauto convention flags it schema-weak for this contract (structuredOutputHint:'avoid'). Down-ranked out of leadership; retained as graceful fallback only.`
871
880
  });
872
881
  }
882
+ if (isPromoted && reasons.length === 0) {
883
+ policyMutations.push({
884
+ id: `promotion-applied-${modelId}`,
885
+ source: "surface_promotion",
886
+ passName: "score_targets",
887
+ description: `Model ${modelId} boosted to surface leadership by active promotion #${promotion.id} (golden-eval run ${promotion.evalRunId ?? "n/a"}, Stage 2 auto-promote, 7-day rollback guard)` + (promotion.suppressQualityGate ? " \u2014 schema-weak quality gate suppressed for this tuple (eval measured the floor holding on real workload)" : "")
888
+ });
889
+ }
890
+ }
891
+ if (promotionDeferred && rawPromotion && modelIds.includes(rawPromotion.promotedModel)) {
892
+ policyMutations.push({
893
+ id: `promotion-deferred-consumer-preference-${rawPromotion.promotedModel}`,
894
+ source: "surface_promotion",
895
+ passName: "score_targets",
896
+ description: `Active promotion #${rawPromotion.id} for ${rawPromotion.promotedModel} deferred \u2014 CompilePolicy.preferredModels is declared and explicit consumer preference outranks brain evidence.`
897
+ });
873
898
  }
874
899
  return { value: scores, mutations: policyMutations };
875
900
  }
@@ -1077,6 +1102,10 @@ function lower(ir, profile, hints = {}) {
1077
1102
  return lowerOpenAI(ir, profile, hints);
1078
1103
  case "deepseek":
1079
1104
  return lowerDeepSeek(ir, profile);
1105
+ case "zai":
1106
+ return lowerZai(ir, profile, hints);
1107
+ case "moonshot":
1108
+ return lowerMoonshot(ir, profile);
1080
1109
  default:
1081
1110
  throw new Error(`No lowering implementation for provider: ${profile.provider}`);
1082
1111
  }
@@ -1365,6 +1394,68 @@ function lowerDeepSeek(ir, profile) {
1365
1394
  }
1366
1395
  };
1367
1396
  }
1397
+ function buildOpenAICompatibleParts(ir) {
1398
+ const ordered = sortSections(ir.sections);
1399
+ const systemText = ordered.map((s) => s.text).join("\n\n");
1400
+ const messages = systemText ? [{ role: "system", content: systemText }] : [];
1401
+ for (const m of ir.history ?? []) {
1402
+ if (m.role === "system") continue;
1403
+ messages.push({ role: m.role, content: m.parts ?? m.content });
1404
+ }
1405
+ if (ir.currentTurn && ir.currentTurn.role !== "system") {
1406
+ messages.push({
1407
+ role: ir.currentTurn.role,
1408
+ content: ir.currentTurn.parts ?? ir.currentTurn.content
1409
+ });
1410
+ }
1411
+ const history = (ir.history ?? []).filter((m) => m.role !== "system");
1412
+ const histMarkIndex = resolveHistoryMarkIndex(history.length, ir.historyCachePolicy);
1413
+ const historyCacheableTokens = histMarkIndex >= 0 ? sumHistoryTokens(history, histMarkIndex) : 0;
1414
+ return {
1415
+ messages,
1416
+ tools: ir.tools && ir.tools.length > 0 ? toOpenAITools(ir.tools) : void 0,
1417
+ response_format: ir.constraints?.structuredOutput ? { type: "json_object" } : void 0,
1418
+ historyCacheableTokens
1419
+ };
1420
+ }
1421
+ function lowerZai(ir, profile, hints) {
1422
+ const parts = buildOpenAICompatibleParts(ir);
1423
+ return {
1424
+ request: {
1425
+ provider: "zai",
1426
+ model: profile.id,
1427
+ messages: parts.messages,
1428
+ tools: parts.tools,
1429
+ response_format: parts.response_format,
1430
+ // Z.ai thinking defaults to enabled server-side; emit an explicit
1431
+ // disable only when a cliff forced thinking off (the GLM analogue of
1432
+ // Gemini's thinkingBudget=0).
1433
+ thinking: hints.forceThinkingZero ? { type: "disabled" } : void 0
1434
+ },
1435
+ diagnostics: {
1436
+ cacheableTokens: 0,
1437
+ historyCacheableTokens: parts.historyCacheableTokens,
1438
+ estimatedCacheSavingsUsd: 0
1439
+ }
1440
+ };
1441
+ }
1442
+ function lowerMoonshot(ir, profile) {
1443
+ const parts = buildOpenAICompatibleParts(ir);
1444
+ return {
1445
+ request: {
1446
+ provider: "moonshot",
1447
+ model: profile.id,
1448
+ messages: parts.messages,
1449
+ tools: parts.tools,
1450
+ response_format: parts.response_format
1451
+ },
1452
+ diagnostics: {
1453
+ cacheableTokens: 0,
1454
+ historyCacheableTokens: parts.historyCacheableTokens,
1455
+ estimatedCacheSavingsUsd: 0
1456
+ }
1457
+ };
1458
+ }
1368
1459
  function sortSections(sections) {
1369
1460
  return [...sections].sort((a, b) => {
1370
1461
  const wa = a.weight ?? 100;
@@ -2258,6 +2349,130 @@ ${originalText}`;
2258
2349
  return { rewrittenIR, rewrites };
2259
2350
  }
2260
2351
 
2352
+ // src/promotions-brain.ts
2353
+ function isRawPromotionRow(x) {
2354
+ if (!x || typeof x !== "object") return false;
2355
+ const r = x;
2356
+ return (typeof r.id === "number" || typeof r.id === "string") && typeof r.intent_archetype === "string" && typeof r.promoted_model === "string" && typeof r.incumbent_model === "string";
2357
+ }
2358
+ function coerceId(v) {
2359
+ if (typeof v === "number") return Number.isFinite(v) ? v : null;
2360
+ if (typeof v === "string") {
2361
+ const n = Number(v);
2362
+ return Number.isFinite(n) ? n : null;
2363
+ }
2364
+ return null;
2365
+ }
2366
+ function mapRowsToPromotions(rows) {
2367
+ const out = [];
2368
+ for (const row of rows) {
2369
+ if (!isRawPromotionRow(row)) continue;
2370
+ const id = coerceId(row.id);
2371
+ if (id === null) continue;
2372
+ out.push({
2373
+ id,
2374
+ archetype: row.intent_archetype,
2375
+ promotedModel: row.promoted_model,
2376
+ incumbentModel: row.incumbent_model,
2377
+ evalRunId: coerceId(row.eval_run_id ?? null),
2378
+ suppressQualityGate: row.suppress_quality_gate === true,
2379
+ promotedAt: typeof row.promoted_at === "string" ? row.promoted_at : ""
2380
+ });
2381
+ }
2382
+ return out;
2383
+ }
2384
+ var snapshots4 = /* @__PURE__ */ new Map();
2385
+ var runtime4;
2386
+ var warnedOnce4 = false;
2387
+ var DEFAULT_PROMOTIONS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions";
2388
+ function isAutoPromoteEnabledFromEnv(envSource) {
2389
+ const env = envSource ?? (typeof process !== "undefined" && process.env ? process.env : {});
2390
+ const raw = (env.KGAUTO_AUTO_PROMOTE ?? "").trim().toLowerCase();
2391
+ return raw === "1" || raw === "true";
2392
+ }
2393
+ function configurePromotionsBrain(rt) {
2394
+ runtime4 = rt;
2395
+ snapshots4.clear();
2396
+ warnedOnce4 = false;
2397
+ }
2398
+ function isPromotionsBrainActive() {
2399
+ return runtime4 !== void 0;
2400
+ }
2401
+ function getApplicablePromotion(opts) {
2402
+ const rt = runtime4;
2403
+ if (!rt) return void 0;
2404
+ const appId = opts.appId;
2405
+ if (!appId || !opts.archetype) return void 0;
2406
+ let snap = snapshots4.get(appId);
2407
+ if (!snap) {
2408
+ snap = { data: [], expiresAt: 0, refreshing: false };
2409
+ snapshots4.set(appId, snap);
2410
+ }
2411
+ const now = Date.now();
2412
+ const stale = snap.expiresAt <= now;
2413
+ if (stale && !snap.refreshing) {
2414
+ snap.refreshing = true;
2415
+ void asyncRefresh4(rt, appId);
2416
+ }
2417
+ return snap.data.find((p) => p.archetype === opts.archetype);
2418
+ }
2419
+ var pendingRefreshes4 = /* @__PURE__ */ new Map();
2420
+ async function asyncRefresh4(rt, appId) {
2421
+ const promise = doRefresh4(rt, appId);
2422
+ pendingRefreshes4.set(appId, promise);
2423
+ try {
2424
+ await promise;
2425
+ } finally {
2426
+ if (pendingRefreshes4.get(appId) === promise) {
2427
+ pendingRefreshes4.delete(appId);
2428
+ }
2429
+ }
2430
+ }
2431
+ async function doRefresh4(rt, appId) {
2432
+ const url = `${rt.endpoint}?app_id=${encodeURIComponent(appId)}`;
2433
+ let snap = snapshots4.get(appId);
2434
+ if (!snap) {
2435
+ snap = { data: [], expiresAt: 0, refreshing: false };
2436
+ snapshots4.set(appId, snap);
2437
+ }
2438
+ try {
2439
+ const res = await rt.fetchImpl(url, { method: "GET" });
2440
+ if (!res.ok) {
2441
+ throw new Error(`promotions ${res.status}: ${res.statusText}`);
2442
+ }
2443
+ const body = await res.json();
2444
+ if (runtime4 !== rt) return;
2445
+ const rows = Array.isArray(body) ? mapRowsToPromotions(body) : [];
2446
+ snap.data = rows;
2447
+ snap.expiresAt = Date.now() + rt.ttlMs;
2448
+ snap.refreshing = false;
2449
+ } catch (err) {
2450
+ if (runtime4 !== rt) return;
2451
+ snap.refreshing = false;
2452
+ snap.expiresAt = Date.now() + rt.ttlMs;
2453
+ if (!warnedOnce4) {
2454
+ warnedOnce4 = true;
2455
+ (rt.onError ?? defaultOnError4)(err);
2456
+ }
2457
+ }
2458
+ }
2459
+ function defaultOnError4(err) {
2460
+ console.warn(
2461
+ "[kgauto] promotions fetch failed (promotion boost inactive until next refresh):",
2462
+ err
2463
+ );
2464
+ }
2465
+ function _testResetPromotions() {
2466
+ runtime4 = void 0;
2467
+ snapshots4.clear();
2468
+ pendingRefreshes4 = /* @__PURE__ */ new Map();
2469
+ warnedOnce4 = false;
2470
+ }
2471
+ async function _testWaitForPromotionsRefresh() {
2472
+ const pending = Array.from(pendingRefreshes4.values());
2473
+ if (pending.length > 0) await Promise.all(pending);
2474
+ }
2475
+
2261
2476
  // src/compile.ts
2262
2477
  var counter = 0;
2263
2478
  function makeHandle() {
@@ -2284,11 +2499,22 @@ function compile(ir, opts = {}) {
2284
2499
  ...toolFiltered.mutations,
2285
2500
  ...compressed.mutations
2286
2501
  ];
2502
+ const activePromotion = getApplicablePromotion({
2503
+ appId: ir.appId,
2504
+ archetype: ir.intent.archetype
2505
+ });
2506
+ const promotion = activePromotion ? {
2507
+ id: activePromotion.id,
2508
+ promotedModel: activePromotion.promotedModel,
2509
+ evalRunId: activePromotion.evalRunId,
2510
+ suppressQualityGate: activePromotion.suppressQualityGate
2511
+ } : void 0;
2287
2512
  const inputTokens = estimateInputTokens(workingIR);
2288
2513
  const scores = passScoreTargets(workingIR, {
2289
2514
  estimatedInputTokens: inputTokens,
2290
2515
  profilesById: resolver,
2291
- policy: opts.policy
2516
+ policy: opts.policy,
2517
+ promotion
2292
2518
  });
2293
2519
  accumulatedMutations.push(...scores.mutations);
2294
2520
  const target = pickTarget(workingIR, scores.value);
@@ -2620,11 +2846,23 @@ function configureBrain(config) {
2620
2846
  } else {
2621
2847
  configureExclusionFindingsBrain(void 0);
2622
2848
  }
2849
+ const promotionsConsent = config.autoPromote ?? isAutoPromoteEnabledFromEnv();
2850
+ if (promotionsConsent && bq.promotions !== false) {
2851
+ configurePromotionsBrain({
2852
+ endpoint: bq.promotionsEndpoint ?? DEFAULT_PROMOTIONS_ENDPOINT,
2853
+ ttlMs: bq.cacheTtlMs ?? 3e5,
2854
+ fetchImpl: config.fetchImpl ?? fetch,
2855
+ onError: config.onError
2856
+ });
2857
+ } else {
2858
+ configurePromotionsBrain(void 0);
2859
+ }
2623
2860
  }
2624
2861
  function clearBrain() {
2625
2862
  activeConfig = void 0;
2626
2863
  configureBrainQuery(void 0);
2627
2864
  configureExclusionFindingsBrain(void 0);
2865
+ configurePromotionsBrain(void 0);
2628
2866
  }
2629
2867
  var DEAD_LETTER_MAX_ENTRIES = 50;
2630
2868
  var DEAD_LETTER_MAX_ATTEMPTS = 3;
@@ -2741,7 +2979,7 @@ async function flushBrainDeadLetter() {
2741
2979
  if (entry.attempts >= DEAD_LETTER_MAX_ATTEMPTS) {
2742
2980
  const idx = deadLetter.indexOf(entry);
2743
2981
  if (idx !== -1) deadLetter.splice(idx, 1);
2744
- (config.onError ?? defaultOnError4)(
2982
+ (config.onError ?? defaultOnError5)(
2745
2983
  new Error(
2746
2984
  `brain dead-letter: dropping ${entry.route} payload after ${entry.attempts} attempts \u2014 last error: ${entry.lastError}`
2747
2985
  )
@@ -2891,7 +3129,7 @@ async function record(input) {
2891
3129
  } catch (err) {
2892
3130
  noteFailure(err);
2893
3131
  pushDeadLetter("outcomes", config.endpoint, payload, err);
2894
- (config.onError ?? defaultOnError4)(err);
3132
+ (config.onError ?? defaultOnError5)(err);
2895
3133
  return;
2896
3134
  }
2897
3135
  maybeAutoFlush();
@@ -2919,7 +3157,7 @@ async function record(input) {
2919
3157
  } catch (err) {
2920
3158
  noteFailure(err);
2921
3159
  pushDeadLetter("compile_outcome_advisories", config.endpoint, advisoryPayload, err);
2922
- (config.onError ?? defaultOnError4)(err);
3160
+ (config.onError ?? defaultOnError5)(err);
2923
3161
  }
2924
3162
  };
2925
3163
  if (config.sync) {
@@ -2928,7 +3166,7 @@ async function record(input) {
2928
3166
  void send();
2929
3167
  }
2930
3168
  }
2931
- function defaultOnError4(err) {
3169
+ function defaultOnError5(err) {
2932
3170
  console.warn("[kgauto] brain record failed:", err);
2933
3171
  }
2934
3172
  function describeBrainWriteFailure(status, route, body) {
@@ -3080,7 +3318,7 @@ async function recordOutcome(input) {
3080
3318
  } catch (err) {
3081
3319
  noteFailure(err);
3082
3320
  pushDeadLetter("compile_outcome_quality", config.endpoint, payload, err);
3083
- (config.onError ?? defaultOnError4)(err);
3321
+ (config.onError ?? defaultOnError5)(err);
3084
3322
  return { ok: false, reason: "persistence_failed" };
3085
3323
  }
3086
3324
  };
@@ -3151,7 +3389,7 @@ async function recordShadowProbe(input) {
3151
3389
  } catch (err) {
3152
3390
  noteFailure(err);
3153
3391
  pushDeadLetter("probe_outcomes", config.endpoint, row, err);
3154
- (config.onError ?? defaultOnError4)(err);
3392
+ (config.onError ?? defaultOnError5)(err);
3155
3393
  }
3156
3394
  };
3157
3395
  if (config.sync) {
@@ -3206,7 +3444,7 @@ async function recordGoldenIr(input) {
3206
3444
  } catch (err) {
3207
3445
  noteFailure(err);
3208
3446
  pushDeadLetter("golden_irs", config.endpoint, row, err);
3209
- (config.onError ?? defaultOnError4)(err);
3447
+ (config.onError ?? defaultOnError5)(err);
3210
3448
  }
3211
3449
  };
3212
3450
  if (config.sync) {
@@ -3560,6 +3798,8 @@ function retryableError(status, code, message, raw) {
3560
3798
  var ANTHROPIC_URL2 = "https://api.anthropic.com/v1/messages";
3561
3799
  var OPENAI_URL = "https://api.openai.com/v1/chat/completions";
3562
3800
  var DEEPSEEK_URL = "https://api.deepseek.com/chat/completions";
3801
+ var ZAI_URL = "https://api.z.ai/api/paas/v4/chat/completions";
3802
+ var MOONSHOT_URL = "https://api.moonshot.ai/v1/chat/completions";
3563
3803
  async function execute(request, opts = {}) {
3564
3804
  const merged = applyOverrides(request, opts.providerOverrides);
3565
3805
  switch (merged.provider) {
@@ -3571,6 +3811,18 @@ async function execute(request, opts = {}) {
3571
3811
  return executeOpenAI(merged, opts);
3572
3812
  case "deepseek":
3573
3813
  return executeDeepSeek(merged, opts);
3814
+ case "zai":
3815
+ return executeOpenAICompatible(
3816
+ merged,
3817
+ opts,
3818
+ { provider: "zai", url: ZAI_URL, missingKeyMessage: "ZAI_API_KEY missing" }
3819
+ );
3820
+ case "moonshot":
3821
+ return executeOpenAICompatible(
3822
+ merged,
3823
+ opts,
3824
+ { provider: "moonshot", url: MOONSHOT_URL, missingKeyMessage: "MOONSHOT_API_KEY missing" }
3825
+ );
3574
3826
  default: {
3575
3827
  const _exhaustive = merged;
3576
3828
  throw new Error(`execute(): no executor for provider: ${JSON.stringify(_exhaustive)}`);
@@ -3720,6 +3972,34 @@ async function executeDeepSeek(request, opts) {
3720
3972
  if (!res.ok) return classifyHttpError2(res.status, json);
3721
3973
  return { ok: true, status: res.status, response: normalizeOpenAILike(json) };
3722
3974
  }
3975
+ async function executeOpenAICompatible(request, opts, spec) {
3976
+ const apiKey = resolveProviderKey(spec.provider, { apiKeys: opts.apiKeys });
3977
+ if (!apiKey) {
3978
+ return terminalError(401, "auth", spec.missingKeyMessage);
3979
+ }
3980
+ if (opts.onChunk) {
3981
+ return streamOpenAILike(spec.url, request, apiKey, spec.provider, {
3982
+ onChunk: opts.onChunk,
3983
+ fetchImpl: opts.fetchImpl
3984
+ });
3985
+ }
3986
+ const { provider: _provider, ...body } = request;
3987
+ const fetchFn = opts.fetchImpl ?? fetch;
3988
+ let res;
3989
+ let json;
3990
+ try {
3991
+ res = await fetchFn(spec.url, {
3992
+ method: "POST",
3993
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
3994
+ body: JSON.stringify(body)
3995
+ });
3996
+ json = await res.json().catch(() => ({}));
3997
+ } catch (err) {
3998
+ return retryableError2(0, "network_error", String(err), null);
3999
+ }
4000
+ if (!res.ok) return classifyHttpError2(res.status, json);
4001
+ return { ok: true, status: res.status, response: normalizeOpenAILike(json) };
4002
+ }
3723
4003
  function normalizeOpenAILike(raw) {
3724
4004
  const r = raw;
3725
4005
  const choice = r.choices?.[0];
@@ -5448,6 +5728,7 @@ export {
5448
5728
  ARCHETYPE_FLOOR_DEFAULT,
5449
5729
  CallError,
5450
5730
  DEFAULT_FINDINGS_ENDPOINT,
5731
+ DEFAULT_PROMOTIONS_ENDPOINT,
5451
5732
  DIALECT_VERSION,
5452
5733
  FamilyResolutionError,
5453
5734
  INTENT_ARCHETYPES,
@@ -5459,6 +5740,8 @@ export {
5459
5740
  PROVIDER_ENV_KEYS,
5460
5741
  RULE_SEQUENTIAL_TOOL_CLIFF,
5461
5742
  TRANSLATOR_FLOOR,
5743
+ _testResetPromotions,
5744
+ _testWaitForPromotionsRefresh,
5462
5745
  allProfiles,
5463
5746
  applyArchetypeConvention,
5464
5747
  applySectionRewrites,
@@ -5478,6 +5761,7 @@ export {
5478
5761
  compile2 as compile,
5479
5762
  compileForAISDKv6,
5480
5763
  configureBrain,
5764
+ configurePromotionsBrain,
5481
5765
  countTokens,
5482
5766
  createBrainForwardRoutes,
5483
5767
  createKeyHealthRoute,
@@ -5489,6 +5773,7 @@ export {
5489
5773
  getActionableAdvisories,
5490
5774
  getAllStarterChains,
5491
5775
  getAllStarterChainsWithGrounding,
5776
+ getApplicablePromotion,
5492
5777
  getArchetypePerfScore,
5493
5778
  getDefaultFallbackChain,
5494
5779
  getDefaultFallbackChainWithGrounding,
@@ -5504,10 +5789,12 @@ export {
5504
5789
  getStarterChainWithGrounding,
5505
5790
  hashShape,
5506
5791
  isArchetype,
5792
+ isAutoPromoteEnabledFromEnv,
5507
5793
  isBrainQueryActiveFor,
5508
5794
  isBrainSync,
5509
5795
  isExclusionFindingsBrainActive,
5510
5796
  isModelReachable,
5797
+ isPromotionsBrainActive,
5511
5798
  isProviderReachable,
5512
5799
  latencyTierOf,
5513
5800
  learningKey,
@@ -373,7 +373,7 @@ interface PromptIR {
373
373
  */
374
374
  historyCachePolicy?: HistoryCachePolicy;
375
375
  }
376
- type Provider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'mistral' | 'xai';
376
+ type Provider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'zai' | 'moonshot' | 'mistral' | 'xai';
377
377
  /**
378
378
  * Mutation IDs that fired during compile. Empty in v1 (no mutation engine
379
379
  * yet). Populated when the brain is online and pushing mutations.
@@ -456,6 +456,33 @@ type CompiledRequest = {
456
456
  content: unknown;
457
457
  }>;
458
458
  tools?: unknown[];
459
+ } | {
460
+ provider: 'zai';
461
+ model: string;
462
+ messages: Array<{
463
+ role: string;
464
+ content: unknown;
465
+ }>;
466
+ tools?: unknown[];
467
+ response_format?: unknown;
468
+ /**
469
+ * alpha.65 — Z.ai thinking knob (docs.z.ai chat-completion reference):
470
+ * `thinking.type` is 'enabled' (default) or 'disabled'. Emitted only
471
+ * when a cliff forces thinking off (`force_thinking_budget_zero`);
472
+ * omitted otherwise so the provider default applies.
473
+ */
474
+ thinking?: {
475
+ type: 'enabled' | 'disabled';
476
+ };
477
+ } | {
478
+ provider: 'moonshot';
479
+ model: string;
480
+ messages: Array<{
481
+ role: string;
482
+ content: unknown;
483
+ }>;
484
+ tools?: unknown[];
485
+ response_format?: unknown;
459
486
  };
460
487
  /**
461
488
  * Best-practice advisory emitted by the compiler at compile time. Non-fatal —
@@ -866,6 +893,8 @@ interface ApiKeys {
866
893
  google?: string;
867
894
  openai?: string;
868
895
  deepseek?: string;
896
+ zai?: string;
897
+ moonshot?: string;
869
898
  }
870
899
  /**
871
900
  * Per-provider override fields shallow-merged into the lowered request before
@@ -877,6 +906,8 @@ interface ProviderOverrides {
877
906
  google?: Record<string, unknown>;
878
907
  openai?: Record<string, unknown>;
879
908
  deepseek?: Record<string, unknown>;
909
+ zai?: Record<string, unknown>;
910
+ moonshot?: Record<string, unknown>;
880
911
  }
881
912
  /**
882
913
  * Full-IR inline shadow-probe config (Shape B, Phase 1 — 2026-05-29 s51).
@@ -373,7 +373,7 @@ interface PromptIR {
373
373
  */
374
374
  historyCachePolicy?: HistoryCachePolicy;
375
375
  }
376
- type Provider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'mistral' | 'xai';
376
+ type Provider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'zai' | 'moonshot' | 'mistral' | 'xai';
377
377
  /**
378
378
  * Mutation IDs that fired during compile. Empty in v1 (no mutation engine
379
379
  * yet). Populated when the brain is online and pushing mutations.
@@ -456,6 +456,33 @@ type CompiledRequest = {
456
456
  content: unknown;
457
457
  }>;
458
458
  tools?: unknown[];
459
+ } | {
460
+ provider: 'zai';
461
+ model: string;
462
+ messages: Array<{
463
+ role: string;
464
+ content: unknown;
465
+ }>;
466
+ tools?: unknown[];
467
+ response_format?: unknown;
468
+ /**
469
+ * alpha.65 — Z.ai thinking knob (docs.z.ai chat-completion reference):
470
+ * `thinking.type` is 'enabled' (default) or 'disabled'. Emitted only
471
+ * when a cliff forces thinking off (`force_thinking_budget_zero`);
472
+ * omitted otherwise so the provider default applies.
473
+ */
474
+ thinking?: {
475
+ type: 'enabled' | 'disabled';
476
+ };
477
+ } | {
478
+ provider: 'moonshot';
479
+ model: string;
480
+ messages: Array<{
481
+ role: string;
482
+ content: unknown;
483
+ }>;
484
+ tools?: unknown[];
485
+ response_format?: unknown;
459
486
  };
460
487
  /**
461
488
  * Best-practice advisory emitted by the compiler at compile time. Non-fatal —
@@ -866,6 +893,8 @@ interface ApiKeys {
866
893
  google?: string;
867
894
  openai?: string;
868
895
  deepseek?: string;
896
+ zai?: string;
897
+ moonshot?: string;
869
898
  }
870
899
  /**
871
900
  * Per-provider override fields shallow-merged into the lowered request before
@@ -877,6 +906,8 @@ interface ProviderOverrides {
877
906
  google?: Record<string, unknown>;
878
907
  openai?: Record<string, unknown>;
879
908
  deepseek?: Record<string, unknown>;
909
+ zai?: Record<string, unknown>;
910
+ moonshot?: Record<string, unknown>;
880
911
  }
881
912
  /**
882
913
  * Full-IR inline shadow-probe config (Shape B, Phase 1 — 2026-05-29 s51).
@@ -73,7 +73,7 @@
73
73
  * ]
74
74
  * }
75
75
  */
76
- type KeyHealthProvider = 'anthropic' | 'deepseek' | 'google' | 'openai';
76
+ type KeyHealthProvider = 'anthropic' | 'deepseek' | 'google' | 'moonshot' | 'openai';
77
77
  interface KeyHealthConfig {
78
78
  /** Consumer app id echoed as `app_id` in the response (e.g. 'playbacksam'). */
79
79
  appId: string;
@@ -73,7 +73,7 @@
73
73
  * ]
74
74
  * }
75
75
  */
76
- type KeyHealthProvider = 'anthropic' | 'deepseek' | 'google' | 'openai';
76
+ type KeyHealthProvider = 'anthropic' | 'deepseek' | 'google' | 'moonshot' | 'openai';
77
77
  interface KeyHealthConfig {
78
78
  /** Consumer app id echoed as `app_id` in the response (e.g. 'playbacksam'). */
79
79
  appId: string;
@@ -25,7 +25,7 @@ __export(key_health_exports, {
25
25
  module.exports = __toCommonJS(key_health_exports);
26
26
 
27
27
  // src/version.ts
28
- var LIBRARY_VERSION = "2.0.0-alpha.63";
28
+ var LIBRARY_VERSION = "2.0.0-alpha.65";
29
29
 
30
30
  // src/key-health.ts
31
31
  var JSON_HEADERS = { "Content-Type": "application/json" };
@@ -74,6 +74,14 @@ var PROBE_SPECS = [
74
74
  return Number.isFinite(n) ? n : void 0;
75
75
  }
76
76
  },
77
+ {
78
+ provider: "moonshot",
79
+ canonicalEnvName: "MOONSHOT_API_KEY",
80
+ buildRequest: (key) => ({
81
+ url: "https://api.moonshot.ai/v1/models",
82
+ headers: { Authorization: `Bearer ${key}` }
83
+ })
84
+ },
77
85
  {
78
86
  provider: "google",
79
87
  canonicalEnvName: "GEMINI_API_KEY",
@@ -105,6 +113,11 @@ function createKeyHealthRoute(config) {
105
113
  const aiSdk = envKey(env, "GOOGLE_GENERATIVE_AI_API_KEY");
106
114
  key = gemini ?? google ?? aiSdk;
107
115
  envName = gemini ? "GEMINI_API_KEY" : google ? "GOOGLE_API_KEY" : aiSdk ? "GOOGLE_GENERATIVE_AI_API_KEY" : "GEMINI_API_KEY";
116
+ } else if (spec.provider === "moonshot") {
117
+ const moonshot = envKey(env, "MOONSHOT_API_KEY");
118
+ const kimi = envKey(env, "KIMI_API_KEY");
119
+ key = moonshot ?? kimi;
120
+ envName = moonshot ? "MOONSHOT_API_KEY" : kimi ? "KIMI_API_KEY" : "MOONSHOT_API_KEY";
108
121
  } else {
109
122
  key = envKey(env, spec.canonicalEnvName);
110
123
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createKeyHealthRoute
3
- } from "./chunk-ZU62HRWK.mjs";
3
+ } from "./chunk-XTZ2ZQJQ.mjs";
4
4
  export {
5
5
  createKeyHealthRoute
6
6
  };
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-B2dRyJXO.mjs';
1
+ import { k as Provider } from './ir-9rrfI3yB.mjs';
2
2
  import { IntentArchetypeName } from './dialect.mjs';
3
3
 
4
4
  /**