@warmdrift/kgauto-compiler 2.0.0-alpha.86 → 2.0.0-alpha.87

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
@@ -19,7 +19,7 @@ import {
19
19
  LIBRARY_VERSION,
20
20
  createKeyHealthRoute,
21
21
  keyFingerprint
22
- } from "./chunk-V4T2CBRI.mjs";
22
+ } from "./chunk-GMZT4ZXD.mjs";
23
23
  import {
24
24
  ABSOLUTE_FLOOR,
25
25
  ARCHETYPE_FLOOR_DEFAULT,
@@ -29,6 +29,7 @@ import {
29
29
  PROVIDER_ENV_KEYS,
30
30
  canonicalPolicySet,
31
31
  chainProviderSpread,
32
+ configFreshness,
32
33
  configureBrainQuery,
33
34
  createBrainQueryCache,
34
35
  ensureCrossProviderTail,
@@ -56,19 +57,23 @@ import {
56
57
  policySetHas,
57
58
  readBrainReadEnv,
58
59
  resolveProviderKey
59
- } from "./chunk-QDWOMQYN.mjs";
60
+ } from "./chunk-G3MKT7IR.mjs";
60
61
  import {
61
62
  ALIASES,
62
63
  LATENCY_TIER_MS,
63
64
  _setProfileBrainHook,
65
+ _testClearConsumerProfiles,
64
66
  allProfiles,
65
67
  allProfilesRaw,
68
+ bestEffortProfile,
66
69
  getProfile,
70
+ inferProviderFromId,
67
71
  latencyTierOf,
68
72
  profilesByProvider,
73
+ registerProfiles,
69
74
  resolveModelAlias,
70
75
  tryGetProfile
71
- } from "./chunk-2MQIVVEU.mjs";
76
+ } from "./chunk-YVKTTTTB.mjs";
72
77
  import {
73
78
  emitAdvisoryFired,
74
79
  emitCompileDone,
@@ -265,6 +270,9 @@ function mapRowsToFindings(rows) {
265
270
  return out;
266
271
  }
267
272
  var snapshots = /* @__PURE__ */ new Map();
273
+ function exclusionFindingsFreshness(appId) {
274
+ return snapshots.get(appId)?.loaded ? "warm" : "cold";
275
+ }
268
276
  var runtime;
269
277
  var warnedOnce = false;
270
278
  var DEFAULT_FINDINGS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/findings/exclusions";
@@ -325,6 +333,7 @@ async function doRefresh(rt, appId) {
325
333
  if (runtime !== rt) return;
326
334
  const rows = Array.isArray(body) ? mapRowsToFindings(body) : [];
327
335
  snap.data = rows;
336
+ snap.loaded = true;
328
337
  snap.expiresAt = Date.now() + rt.ttlMs;
329
338
  snap.refreshing = false;
330
339
  } catch (err) {
@@ -1628,6 +1637,9 @@ function judgeMeasuredFailure(row, cfg = MEASURED_FAILURE_CFG) {
1628
1637
  };
1629
1638
  }
1630
1639
  var snapshots2 = /* @__PURE__ */ new Map();
1640
+ function measuredFailureFreshness(appId) {
1641
+ return snapshots2.get(appId)?.loaded ? "warm" : "cold";
1642
+ }
1631
1643
  var runtime2;
1632
1644
  var warnedOnce2 = false;
1633
1645
  var DEFAULT_MEASURED_FAILURE_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/measured-failure";
@@ -1725,6 +1737,7 @@ async function doRefresh2(rt, appId) {
1725
1737
  const body = await res.json();
1726
1738
  if (runtime2 !== rt) return;
1727
1739
  snap.data = Array.isArray(body) ? mapRows(body) : [];
1740
+ snap.loaded = true;
1728
1741
  snap.expiresAt = Date.now() + rt.ttlMs;
1729
1742
  snap.refreshing = false;
1730
1743
  } catch (err) {
@@ -1796,6 +1809,9 @@ function mapRowsToPromotions(rows) {
1796
1809
  return out;
1797
1810
  }
1798
1811
  var snapshots3 = /* @__PURE__ */ new Map();
1812
+ function promotionsFreshness(appId) {
1813
+ return snapshots3.get(appId)?.loaded ? "warm" : "cold";
1814
+ }
1799
1815
  var runtime3;
1800
1816
  var warnedOnce3 = false;
1801
1817
  var DEFAULT_PROMOTIONS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions";
@@ -1880,6 +1896,7 @@ async function doRefresh3(rt, appId) {
1880
1896
  if (runtime3 !== rt) return;
1881
1897
  const rows = Array.isArray(body) ? mapRowsToPromotions(body) : [];
1882
1898
  snap.data = rows;
1899
+ snap.loaded = true;
1883
1900
  snap.expiresAt = Date.now() + rt.ttlMs;
1884
1901
  snap.refreshing = false;
1885
1902
  } catch (err) {
@@ -1980,6 +1997,9 @@ function mapRowsToFindings2(rows) {
1980
1997
  return out;
1981
1998
  }
1982
1999
  var snapshots4 = /* @__PURE__ */ new Map();
2000
+ function promoteReadyFreshness(appId) {
2001
+ return snapshots4.get(appId)?.loaded ? "warm" : "cold";
2002
+ }
1983
2003
  var runtime4;
1984
2004
  var warnedOnce4 = false;
1985
2005
  function isPromoteReadyBrainActive() {
@@ -2038,6 +2058,7 @@ async function doRefresh4(rt, appId) {
2038
2058
  if (runtime4 !== rt) return;
2039
2059
  const rows = Array.isArray(body) ? mapRowsToFindings2(body) : [];
2040
2060
  snap.data = rows;
2061
+ snap.loaded = true;
2041
2062
  snap.expiresAt = Date.now() + rt.ttlMs;
2042
2063
  snap.refreshing = false;
2043
2064
  } catch (err) {
@@ -2987,7 +3008,16 @@ function makeHandle() {
2987
3008
  return `c${Date.now().toString(36)}-${counter.toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
2988
3009
  }
2989
3010
  function compile(ir, opts = {}) {
2990
- const resolver = opts.profileResolver ?? getProfile;
3011
+ const baseResolver = opts.profileResolver ?? getProfile;
3012
+ const resolver = opts.policy?.onUnprofiledModel === "best-effort" ? (id) => {
3013
+ try {
3014
+ return baseResolver(id);
3015
+ } catch (err) {
3016
+ const synth = bestEffortProfile(id);
3017
+ if (!synth) throw err;
3018
+ return synth;
3019
+ }
3020
+ } : baseResolver;
2991
3021
  validateIR(ir);
2992
3022
  ir = resolveModelEntries(ir);
2993
3023
  const sliced = passSlice(ir);
@@ -3047,11 +3077,26 @@ function compile(ir, opts = {}) {
3047
3077
  accumulatedMutations.push(...scores.mutations);
3048
3078
  const target = pickTarget(workingIR, scores.value);
3049
3079
  if (!target) {
3080
+ const unknownIds = scores.value.filter((s) => s.rejectReasons?.includes("unknown_model_id")).map((s) => s.modelId);
3081
+ const uninferable = unknownIds.filter((id) => !inferProviderFromId(id));
3082
+ const unknownHint = unknownIds.length > 0 ? ` Unprofiled model id(s): ${unknownIds.join(", ")}. registerProfiles([...]) supplies a full profile; policy.onUnprofiledModel:'best-effort' compiles with guards skipped.` + (uninferable.length > 0 ? ` Note: provider is not inferable from ${uninferable.join(", ")}, so best-effort cannot lower it \u2014 registerProfiles is the only path for those.` : "") : "";
3050
3083
  throw new Error(
3051
- `compile(): no allowed model fits the request. Scores: ${JSON.stringify(scores.value, null, 2)}`
3084
+ `compile(): no allowed model fits the request.${unknownHint} Scores: ${JSON.stringify(scores.value, null, 2)}`
3052
3085
  );
3053
3086
  }
3054
3087
  const profile = resolver(target.modelId);
3088
+ const bestEffortWarnings = [];
3089
+ if (profile.bestEffort) {
3090
+ bestEffortWarnings.push(
3091
+ `best-effort profile in use for "${profile.id}" (provider ${profile.provider} inferred from the id; wire mechanics borrowed). SKIPPED for this model: cliff guards, recovery rules, measured archetype knowledge, structured-output capability (treated as 'none'), parallel tools (treated as sequential). Cost is UNKNOWN and recorded as $0 \u2014 cost gates and cost attribution are meaningless for this model. registerProfiles() restores real guards.`
3092
+ );
3093
+ accumulatedMutations.push({
3094
+ id: `best_effort_profile_${profile.id}`,
3095
+ source: "best_effort",
3096
+ passName: "resolve-profile",
3097
+ description: `Unprofiled model "${profile.id}" compiled under onUnprofiledModel:'best-effort' \u2014 guards skipped, cost unknown. See diagnostics.cliffWarnings for the full list.`
3098
+ });
3099
+ }
3055
3100
  const fallbackChain = scores.value.filter((s) => s.modelId !== target.modelId && s.fits).sort((a, b) => b.rank - a.rank).map((s) => s.modelId);
3056
3101
  const cliffs = passApplyCliffs(workingIR, profile, inputTokens);
3057
3102
  workingIR = cliffs.value.ir;
@@ -3137,6 +3182,23 @@ function compile(ir, opts = {}) {
3137
3182
  const historyCacheMarkIndex = computeHistoryCacheMarkIndex(workingIR);
3138
3183
  const systemMessages = buildSystemMessages(workingIR, profile.provider);
3139
3184
  const systemCacheMarkIndex = lastCacheableSystemIndex(systemMessages);
3185
+ const keptSectionIds = new Set(workingIR.sections.map((s) => s.id));
3186
+ const cachePrefixActive = lowered.diagnostics.cacheableTokens > 0;
3187
+ const cacheReadFraction = profile.lowering.cache.discount ?? 0.25;
3188
+ const sectionAttribution = ir.sections.map((s) => {
3189
+ const tokens = countTokens(s.text);
3190
+ const kept = keptSectionIds.has(s.id);
3191
+ const estCostUsdFirstCall = kept ? tokens / 1e6 * profile.costInputPer1m : 0;
3192
+ const inActiveCachePrefix = kept && s.cacheable === true && cachePrefixActive;
3193
+ return {
3194
+ id: s.id,
3195
+ tokens,
3196
+ kept,
3197
+ cacheable: s.cacheable === true,
3198
+ estCostUsdFirstCall,
3199
+ estCostUsdWarm: inActiveCachePrefix ? estCostUsdFirstCall * cacheReadFraction : estCostUsdFirstCall
3200
+ };
3201
+ });
3140
3202
  const diagnostics = {
3141
3203
  sectionsKept: workingIR.sections.length,
3142
3204
  sectionsDropped: ir.sections.length - workingIR.sections.length,
@@ -3160,11 +3222,25 @@ function compile(ir, opts = {}) {
3160
3222
  // text the consumer can route on without changing behavior).
3161
3223
  cliffWarnings: [
3162
3224
  ...cliffs.value.loweringHints.qualityWarning ?? [],
3163
- ...conventions.value.cliffWarnings
3225
+ ...conventions.value.cliffWarnings,
3226
+ // alpha.87 — best-effort profile in use (loud on EVERY compile).
3227
+ ...bestEffortWarnings
3164
3228
  ],
3165
3229
  // alpha.68 / Release A — measured discipline gate-token tax (§5.D). 0 when
3166
3230
  // the gate didn't fire.
3167
- disciplineGateTokens
3231
+ disciplineGateTokens,
3232
+ // alpha.87 — per-source freshness stamped at the moment the compile's
3233
+ // reads have all happened, from state each source already tracks (the
3234
+ // "one-line stamp at the point where the source is already known and
3235
+ // discarded" this filing reduced to once alpha.73/.86 warmed the caches).
3236
+ freshness: {
3237
+ config: configFreshness(),
3238
+ measuredFailure: measuredFailureFreshness(ir.appId),
3239
+ promotions: promotionsFreshness(ir.appId),
3240
+ exclusions: exclusionFindingsFreshness(ir.appId),
3241
+ promoteReady: promoteReadyFreshness(ir.appId)
3242
+ },
3243
+ sections: sectionAttribution
3168
3244
  };
3169
3245
  if (ir.intent.archetype === "hunt" && ir.constraints?.toolOrchestration === "sequential") {
3170
3246
  accumulatedMutations.push({
@@ -3700,6 +3776,26 @@ function maybeWarnDiscardedCompile(reg, handle) {
3700
3776
  `[kgauto] compile-then-discard: compileForAISDKv6() output for handle ${handle} (archetype=${reg.archetype}, model=${reg.model}) was recorded but neither .system, .model, nor .raw was read before record(). The brain row's mutations_applied / estimated_tokens_in / system_prompt_chars describe a compile that did NOT shape the served call. Pass compiled.system + compiled.model into your generateText/streamText (or use call()). Silence via configureBrain({ warnOnDiscardedCompile: false }).`
3701
3777
  );
3702
3778
  }
3779
+ var OUTCOME_SOURCES = ["canary", "smoke", "eval", "probe", "synthetic"];
3780
+ var warnedInvalidEnvSource = false;
3781
+ function resolveOutcomeSource(explicit) {
3782
+ if (explicit) return explicit;
3783
+ const raw = typeof process !== "undefined" ? process.env?.KGAUTO_SOURCE : void 0;
3784
+ if (!raw) return void 0;
3785
+ const trimmed = raw.trim();
3786
+ if (!trimmed) return void 0;
3787
+ if (OUTCOME_SOURCES.includes(trimmed)) return trimmed;
3788
+ if (!warnedInvalidEnvSource) {
3789
+ warnedInvalidEnvSource = true;
3790
+ console.warn(
3791
+ `[kgauto] KGAUTO_SOURCE="${trimmed}" is not one of ${OUTCOME_SOURCES.join("|")} \u2014 recording as 'synthetic' so the row survives the brain's CHECK constraint and stays out of organic-liveness stats.`
3792
+ );
3793
+ }
3794
+ return "synthetic";
3795
+ }
3796
+ function _testResetOutcomeSourceWarning() {
3797
+ warnedInvalidEnvSource = false;
3798
+ }
3703
3799
  async function record(input) {
3704
3800
  const reg = compileRegistry.get(input.handle);
3705
3801
  if (reg) {
@@ -3814,7 +3910,9 @@ function buildPayload(input, reg) {
3814
3910
  latency_ms: input.latencyMs,
3815
3911
  success: input.success,
3816
3912
  empty_response: input.emptyResponse ?? input.tokensOut === 0,
3817
- source: input.source,
3913
+ // alpha.87 — explicit source wins; KGAUTO_SOURCE env fills the gap (the
3914
+ // zero-code synthetic self-mark for harness/smoke processes).
3915
+ source: resolveOutcomeSource(input.source),
3818
3916
  error_type: input.errorType,
3819
3917
  tools_called: input.toolsCalled,
3820
3918
  oracle_score: input.oracleScore?.score,
@@ -7429,7 +7527,9 @@ export {
7429
7527
  STRATEGY_AUTHORSHIP_INDEPENDENT,
7430
7528
  STRATEGY_AUTHORSHIP_LIMITATION,
7431
7529
  TRANSLATOR_FLOOR,
7530
+ _testClearConsumerProfiles,
7432
7531
  _testResetMeasuredFailure,
7532
+ _testResetOutcomeSourceWarning,
7433
7533
  _testResetPromotions,
7434
7534
  _testWaitForMeasuredFailureRefresh,
7435
7535
  _testWaitForPromotionsRefresh,
@@ -7441,6 +7541,7 @@ export {
7441
7541
  attachCacheControlToStreamTextInput,
7442
7542
  awaitMeasuredFailureReady,
7443
7543
  awaitPromotionsReady,
7544
+ bestEffortProfile,
7444
7545
  brainHealth,
7445
7546
  bucketContext,
7446
7547
  bucketHistory,
@@ -7495,6 +7596,7 @@ export {
7495
7596
  getStarterChainWithGrounding,
7496
7597
  hasMutation,
7497
7598
  hashShape,
7599
+ inferProviderFromId,
7498
7600
  isAltStrategy,
7499
7601
  isArchetype,
7500
7602
  isAutoPromoteEnabledFromEnv,
@@ -7536,11 +7638,13 @@ export {
7536
7638
  recordGoldenIr,
7537
7639
  recordOutcome,
7538
7640
  recordShadowProbe,
7641
+ registerProfiles,
7539
7642
  renderIrForJudge,
7540
7643
  resetTokenizer,
7541
7644
  resolveConventionsForProfile,
7542
7645
  resolveGoldenCaptureRate,
7543
7646
  resolveModelAlias,
7647
+ resolveOutcomeSource,
7544
7648
  resolvePricingAt,
7545
7649
  resolveProviderKey,
7546
7650
  rowToAdvisory,
@@ -363,6 +363,26 @@ interface CompilePolicy {
363
363
  * advisor; otherwise unspecified.
364
364
  */
365
365
  posture?: 'locked' | 'preferred' | 'open';
366
+ /**
367
+ * alpha.87 — what compile() does with a model id no profile covers
368
+ * (gateway review §6; both cold readers hit this wall).
369
+ *
370
+ * - `'refuse'` (default) — throw, naming `registerProfiles()` and this
371
+ * option. The fleet's safety posture, unchanged: guards can only be
372
+ * honest about models kgauto knows.
373
+ * - `'best-effort'` — synthesize a conservative profile (provider
374
+ * inferred from the id prefix; wire mechanics borrowed from a bundled
375
+ * profile of that provider; NO cliffs, NO measured knowledge, cost
376
+ * UNKNOWN and recorded as 0) and compile anyway, with a loud
377
+ * `cliffWarnings` entry + `best_effort_profile` mutation naming
378
+ * every guard that is skipped. If the provider cannot be inferred,
379
+ * refusal still applies — best-effort cannot lower a wire format it
380
+ * cannot name.
381
+ *
382
+ * The option converts "wait for the maintainer's weekend" into a
383
+ * consumer's informed choice; it does not make the unknown model safe.
384
+ */
385
+ onUnprofiledModel?: 'refuse' | 'best-effort';
366
386
  }
367
387
  /**
368
388
  * alpha.41 — entry in `PromptIR.models[]`. Either a literal model id (the
@@ -899,6 +919,69 @@ interface CompileResult {
899
919
  * number the cost-watcher can weigh against the lift.
900
920
  */
901
921
  disciplineGateTokens: number;
922
+ /**
923
+ * alpha.87 — which world answered THIS compile, per data source (the
924
+ * `per-source-freshness-marker-on-callresult` ask, PB s76). kgauto
925
+ * legitimately ranks on bundled profiles when cold and brain-re-ranked
926
+ * profiles when warm, and before this field the response said nothing
927
+ * about which had answered — PB drew three wrong conclusions across
928
+ * s74–s76 from observations taken at unknown temperature. A FLAT marker
929
+ * was rejected in the s76 consult: the app-scoped gates (measured
930
+ * failure, promotions, exclusions, promote-ready) carry cache state
931
+ * independent of the shared config snapshot, and a config-derived
932
+ * marker would read 'brain' in exactly the window where the
933
+ * measured-failure gate is still cold.
934
+ *
935
+ * Semantics: `config` is `'brain'` iff the shared `/v2/config` snapshot
936
+ * held fetched data at compile time (else `'bundled'`). The per-gate
937
+ * fields are `'warm'` iff a successful app-scoped load had completed in
938
+ * this process — `'cold'` covers never-loaded, load-failed, and
939
+ * feature-disabled alike, because in all three the gate read no data.
940
+ * With alpha.73/.86 prefetch + `gateWarmupMs`, a `call()` after warmup
941
+ * should read all-warm; a cold isolate's first compile may not.
942
+ */
943
+ freshness: {
944
+ config: 'bundled' | 'brain';
945
+ measuredFailure: 'cold' | 'warm';
946
+ promotions: 'cold' | 'warm';
947
+ exclusions: 'cold' | 'warm';
948
+ promoteReady: 'cold' | 'warm';
949
+ };
950
+ /**
951
+ * alpha.87 — per-section cost attribution (cc's
952
+ * `per-section-cost-attribution-in-diagnostics` ask, from Sacha's
953
+ * oracle read). `compile()` already receives sections IDed by the
954
+ * consumer, so this itemization is arithmetic on values the compiler
955
+ * computes anyway: zero model calls, no brain write, counts and IDs
956
+ * only — never section text (G3-compatible by construction). Always-on:
957
+ * an itemization nobody remembers to ask for is absent at the moment
958
+ * it is needed, and the payload is one small object per section.
959
+ *
960
+ * One row per INPUT section, in input order — dropped sections appear
961
+ * with `kept: false` and zero cost so a consumer can see what a pass
962
+ * removed and what it was worth.
963
+ *
964
+ * The cacheable interaction is deliberately two explicit columns
965
+ * rather than one blended number or a compile-time `cacheState` guess:
966
+ * whether a given call pays the first-call or the warm price is decided
967
+ * at the provider AFTER compile, so the honest compile-time statement
968
+ * is both prices. `estCostUsdFirstCall` is the section's tokens at the
969
+ * selected model's uncached input price (provider cache-WRITE
970
+ * surcharges, e.g. Anthropic's 1.25×, are not modeled — this
971
+ * understates first-call cost slightly). `estCostUsdWarm` applies the
972
+ * profile's cache-read discount when the section sits in an ACTIVE
973
+ * cacheable prefix (cacheable, and the prefix met the provider's
974
+ * minimum); otherwise it equals `estCostUsdFirstCall` — for a
975
+ * non-cached section the two worlds cost the same.
976
+ */
977
+ sections: Array<{
978
+ id: string;
979
+ tokens: number;
980
+ kept: boolean;
981
+ cacheable: boolean;
982
+ estCostUsdFirstCall: number;
983
+ estCostUsdWarm: number;
984
+ }>;
902
985
  };
903
986
  /**
904
987
  * alpha.33. Structured `system` for AI-SDK `streamText({ system })`
@@ -1785,4 +1868,4 @@ interface PerAxisMetrics {
1785
1868
  /** Per-axis metrics keyed by model — used for chain-comparison views. */
1786
1869
  type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
1787
1870
 
1788
- export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, captureGoldenIr as D, type EffortLevel as E, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, hasMutation as J, mutationId as K, parseGoldenCaptureRate as L, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, resolveGoldenCaptureRate as Q, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, shouldCaptureGolden as U, type CompiledRequest as a, type PromptIR as b, type CallOptions as c, type CallResult as d, type CompileResult as e, type SectionRewrite as f, type RecordOutcomeInput as g, type OracleScore as h, type Adapter as i, type PerAxisMetrics as j, type Provider as k, type ChainEntry as l, type CallAttempt as m, CallError as n, type ChainModelEntry as o, type ChainWithGrounding as p, type Constraints as q, type GoldenCaptureOptions as r, type MutationApplied as s, type NormalizedTokens as t, type OutcomeKind as u, type PerAxisMetricsByModel as v, type PromptSection as w, type SectionKind as x, type ShadowProbeConfig as y, type ToolDefinition as z };
1871
+ export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, type ToolDefinition as D, type EffortLevel as E, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, captureGoldenIr as J, hasMutation as K, mutationId as L, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, parseGoldenCaptureRate as Q, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, resolveGoldenCaptureRate as U, shouldCaptureGolden as V, type CompiledRequest as a, type PromptIR as b, type CallOptions as c, type CallResult as d, type CompileResult as e, type SectionRewrite as f, type RecordOutcomeInput as g, type OutcomeSource as h, type OracleScore as i, type Adapter as j, type PerAxisMetrics as k, type Provider as l, type ChainEntry as m, type CallAttempt as n, CallError as o, type ChainModelEntry as p, type ChainWithGrounding as q, type Constraints as r, type GoldenCaptureOptions as s, type MutationApplied as t, type NormalizedTokens as u, type OutcomeKind as v, type PerAxisMetricsByModel as w, type PromptSection as x, type SectionKind as y, type ShadowProbeConfig as z };
@@ -363,6 +363,26 @@ interface CompilePolicy {
363
363
  * advisor; otherwise unspecified.
364
364
  */
365
365
  posture?: 'locked' | 'preferred' | 'open';
366
+ /**
367
+ * alpha.87 — what compile() does with a model id no profile covers
368
+ * (gateway review §6; both cold readers hit this wall).
369
+ *
370
+ * - `'refuse'` (default) — throw, naming `registerProfiles()` and this
371
+ * option. The fleet's safety posture, unchanged: guards can only be
372
+ * honest about models kgauto knows.
373
+ * - `'best-effort'` — synthesize a conservative profile (provider
374
+ * inferred from the id prefix; wire mechanics borrowed from a bundled
375
+ * profile of that provider; NO cliffs, NO measured knowledge, cost
376
+ * UNKNOWN and recorded as 0) and compile anyway, with a loud
377
+ * `cliffWarnings` entry + `best_effort_profile` mutation naming
378
+ * every guard that is skipped. If the provider cannot be inferred,
379
+ * refusal still applies — best-effort cannot lower a wire format it
380
+ * cannot name.
381
+ *
382
+ * The option converts "wait for the maintainer's weekend" into a
383
+ * consumer's informed choice; it does not make the unknown model safe.
384
+ */
385
+ onUnprofiledModel?: 'refuse' | 'best-effort';
366
386
  }
367
387
  /**
368
388
  * alpha.41 — entry in `PromptIR.models[]`. Either a literal model id (the
@@ -899,6 +919,69 @@ interface CompileResult {
899
919
  * number the cost-watcher can weigh against the lift.
900
920
  */
901
921
  disciplineGateTokens: number;
922
+ /**
923
+ * alpha.87 — which world answered THIS compile, per data source (the
924
+ * `per-source-freshness-marker-on-callresult` ask, PB s76). kgauto
925
+ * legitimately ranks on bundled profiles when cold and brain-re-ranked
926
+ * profiles when warm, and before this field the response said nothing
927
+ * about which had answered — PB drew three wrong conclusions across
928
+ * s74–s76 from observations taken at unknown temperature. A FLAT marker
929
+ * was rejected in the s76 consult: the app-scoped gates (measured
930
+ * failure, promotions, exclusions, promote-ready) carry cache state
931
+ * independent of the shared config snapshot, and a config-derived
932
+ * marker would read 'brain' in exactly the window where the
933
+ * measured-failure gate is still cold.
934
+ *
935
+ * Semantics: `config` is `'brain'` iff the shared `/v2/config` snapshot
936
+ * held fetched data at compile time (else `'bundled'`). The per-gate
937
+ * fields are `'warm'` iff a successful app-scoped load had completed in
938
+ * this process — `'cold'` covers never-loaded, load-failed, and
939
+ * feature-disabled alike, because in all three the gate read no data.
940
+ * With alpha.73/.86 prefetch + `gateWarmupMs`, a `call()` after warmup
941
+ * should read all-warm; a cold isolate's first compile may not.
942
+ */
943
+ freshness: {
944
+ config: 'bundled' | 'brain';
945
+ measuredFailure: 'cold' | 'warm';
946
+ promotions: 'cold' | 'warm';
947
+ exclusions: 'cold' | 'warm';
948
+ promoteReady: 'cold' | 'warm';
949
+ };
950
+ /**
951
+ * alpha.87 — per-section cost attribution (cc's
952
+ * `per-section-cost-attribution-in-diagnostics` ask, from Sacha's
953
+ * oracle read). `compile()` already receives sections IDed by the
954
+ * consumer, so this itemization is arithmetic on values the compiler
955
+ * computes anyway: zero model calls, no brain write, counts and IDs
956
+ * only — never section text (G3-compatible by construction). Always-on:
957
+ * an itemization nobody remembers to ask for is absent at the moment
958
+ * it is needed, and the payload is one small object per section.
959
+ *
960
+ * One row per INPUT section, in input order — dropped sections appear
961
+ * with `kept: false` and zero cost so a consumer can see what a pass
962
+ * removed and what it was worth.
963
+ *
964
+ * The cacheable interaction is deliberately two explicit columns
965
+ * rather than one blended number or a compile-time `cacheState` guess:
966
+ * whether a given call pays the first-call or the warm price is decided
967
+ * at the provider AFTER compile, so the honest compile-time statement
968
+ * is both prices. `estCostUsdFirstCall` is the section's tokens at the
969
+ * selected model's uncached input price (provider cache-WRITE
970
+ * surcharges, e.g. Anthropic's 1.25×, are not modeled — this
971
+ * understates first-call cost slightly). `estCostUsdWarm` applies the
972
+ * profile's cache-read discount when the section sits in an ACTIVE
973
+ * cacheable prefix (cacheable, and the prefix met the provider's
974
+ * minimum); otherwise it equals `estCostUsdFirstCall` — for a
975
+ * non-cached section the two worlds cost the same.
976
+ */
977
+ sections: Array<{
978
+ id: string;
979
+ tokens: number;
980
+ kept: boolean;
981
+ cacheable: boolean;
982
+ estCostUsdFirstCall: number;
983
+ estCostUsdWarm: number;
984
+ }>;
902
985
  };
903
986
  /**
904
987
  * alpha.33. Structured `system` for AI-SDK `streamText({ system })`
@@ -1785,4 +1868,4 @@ interface PerAxisMetrics {
1785
1868
  /** Per-axis metrics keyed by model — used for chain-comparison views. */
1786
1869
  type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
1787
1870
 
1788
- export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, captureGoldenIr as D, type EffortLevel as E, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, hasMutation as J, mutationId as K, parseGoldenCaptureRate as L, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, resolveGoldenCaptureRate as Q, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, shouldCaptureGolden as U, type CompiledRequest as a, type PromptIR as b, type CallOptions as c, type CallResult as d, type CompileResult as e, type SectionRewrite as f, type RecordOutcomeInput as g, type OracleScore as h, type Adapter as i, type PerAxisMetrics as j, type Provider as k, type ChainEntry as l, type CallAttempt as m, CallError as n, type ChainModelEntry as o, type ChainWithGrounding as p, type Constraints as q, type GoldenCaptureOptions as r, type MutationApplied as s, type NormalizedTokens as t, type OutcomeKind as u, type PerAxisMetricsByModel as v, type PromptSection as w, type SectionKind as x, type ShadowProbeConfig as y, type ToolDefinition as z };
1871
+ export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, type ToolDefinition as D, type EffortLevel as E, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, captureGoldenIr as J, hasMutation as K, mutationId as L, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, parseGoldenCaptureRate as Q, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, resolveGoldenCaptureRate as U, shouldCaptureGolden as V, type CompiledRequest as a, type PromptIR as b, type CallOptions as c, type CallResult as d, type CompileResult as e, type SectionRewrite as f, type RecordOutcomeInput as g, type OutcomeSource as h, type OracleScore as i, type Adapter as j, type PerAxisMetrics as k, type Provider as l, type ChainEntry as m, type CallAttempt as n, CallError as o, type ChainModelEntry as p, type ChainWithGrounding as q, type Constraints as r, type GoldenCaptureOptions as s, type MutationApplied as t, type NormalizedTokens as u, type OutcomeKind as v, type PerAxisMetricsByModel as w, type PromptSection as x, type SectionKind as y, type ShadowProbeConfig as z };
@@ -28,7 +28,7 @@ __export(key_health_exports, {
28
28
  module.exports = __toCommonJS(key_health_exports);
29
29
 
30
30
  // src/version.ts
31
- var LIBRARY_VERSION = "2.0.0-alpha.86";
31
+ var LIBRARY_VERSION = "2.0.0-alpha.87";
32
32
 
33
33
  // src/key-health.ts
34
34
  var JSON_HEADERS = { "Content-Type": "application/json" };
@@ -3,7 +3,7 @@ import {
3
3
  KEY_FINGERPRINT_LENGTH,
4
4
  createKeyHealthRoute,
5
5
  keyFingerprint
6
- } from "./chunk-V4T2CBRI.mjs";
6
+ } from "./chunk-GMZT4ZXD.mjs";
7
7
  export {
8
8
  KEY_FINGERPRINT_DOMAIN,
9
9
  KEY_FINGERPRINT_LENGTH,
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-5TJLAYKR.mjs';
1
+ import { l as Provider } from './ir-P3NEU8z4.mjs';
2
2
  import { IntentArchetypeName } from './dialect.mjs';
3
3
 
4
4
  /**
@@ -263,6 +263,15 @@ interface ModelProfile {
263
263
  * See `ArchetypeConvention` for field semantics.
264
264
  */
265
265
  archetypeConventions?: ArchetypeConvention[];
266
+ /**
267
+ * alpha.87 — true ONLY on profiles synthesized by
268
+ * `onUnprofiledModel: 'best-effort'`. Lets compile() (and any consumer)
269
+ * distinguish "kgauto knows this model" from "kgauto is winging it with
270
+ * borrowed wire mechanics" on every call, not just the one that
271
+ * triggered synthesis. Never set on bundled, brain, or
272
+ * `registerProfiles()` entries.
273
+ */
274
+ bestEffort?: true;
266
275
  }
267
276
  /**
268
277
  * Representative p50 latency (ms) per tier. Coarse on purpose — used only to
@@ -291,6 +300,38 @@ interface ProfileBrainHook {
291
300
  }
292
301
  /** @internal — called by models-brain.ts at module load. */
293
302
  declare function _setProfileBrainHook(hook: ProfileBrainHook): void;
303
+ /**
304
+ * Register consumer-supplied profiles. They take precedence over both
305
+ * brain-curated and bundled profiles for the same id (explicit > learned >
306
+ * shipped — see block comment above for the tradeoff). Re-registering an
307
+ * id overwrites the previous consumer entry, including any best-effort
308
+ * synthesized profile.
309
+ */
310
+ declare function registerProfiles(profiles: readonly ModelProfile[]): void;
311
+ /** @internal — test hook. */
312
+ declare function _testClearConsumerProfiles(): void;
313
+ /** Provider inference for best-effort mode — id prefix conventions only. */
314
+ declare function inferProviderFromId(id: string): Provider | undefined;
315
+ /**
316
+ * alpha.87 — best-effort profile synthesis for unprofiled ids (opt-in via
317
+ * `CompilePolicy.onUnprofiledModel: 'best-effort'`; the default posture
318
+ * stays refuse). Returns undefined when the provider cannot be inferred
319
+ * from the id or kgauto ships no donor profile for that provider — in
320
+ * both cases the caller falls back to the standard refusal, which names
321
+ * `registerProfiles()` as the informed path.
322
+ *
323
+ * What a synthesized profile is: the inferred provider's wire mechanics
324
+ * (LoweringSpec / systemPromptMode / streaming are provider-wide, borrowed
325
+ * from a current bundled profile of that provider) around deliberately
326
+ * conservative capability claims — no cliffs, no recovery, no measured
327
+ * knowledge, `structuredOutput: 'none'`, sequential tools, modest output
328
+ * budget, and **cost 0 because cost is UNKNOWN** (cost gates and cost
329
+ * attribution are meaningless for this model; the compile carries a loud
330
+ * warning saying exactly that). It is registered into the consumer index
331
+ * on first synthesis so every later lookup in the process (fallback walk,
332
+ * passes, telemetry) sees one consistent object.
333
+ */
334
+ declare function bestEffortProfile(id: string): ModelProfile | undefined;
294
335
  /**
295
336
  * Resolve a model id to its canonical form (alias → canonical, unknown ids
296
337
  * returned unchanged). This is the same resolution `getProfile` applies, so
@@ -308,4 +349,4 @@ declare function allProfiles(): readonly ModelProfile[];
308
349
  declare function allProfilesRaw(): readonly ModelProfile[];
309
350
  declare function profilesByProvider(provider: Provider): readonly ModelProfile[];
310
351
 
311
- export { ALIASES, type ArchetypeConvention, type CacheStrategy, type CliffRule, LATENCY_TIER_MS, type LatencyTier, type LoweringSpec, type ModelProfile, type RecoveryRule, type StructuredOutputCapability, type SystemPromptMode, _setProfileBrainHook, allProfiles, allProfilesRaw, getProfile, latencyTierOf, profilesByProvider, resolveModelAlias, tryGetProfile };
352
+ export { ALIASES, type ArchetypeConvention, type CacheStrategy, type CliffRule, LATENCY_TIER_MS, type LatencyTier, type LoweringSpec, type ModelProfile, type RecoveryRule, type StructuredOutputCapability, type SystemPromptMode, _setProfileBrainHook, _testClearConsumerProfiles, allProfiles, allProfilesRaw, bestEffortProfile, getProfile, inferProviderFromId, latencyTierOf, profilesByProvider, registerProfiles, resolveModelAlias, tryGetProfile };
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-C1zmvAh6.js';
1
+ import { l as Provider } from './ir-ZgN2KkuF.js';
2
2
  import { IntentArchetypeName } from './dialect.js';
3
3
 
4
4
  /**
@@ -263,6 +263,15 @@ interface ModelProfile {
263
263
  * See `ArchetypeConvention` for field semantics.
264
264
  */
265
265
  archetypeConventions?: ArchetypeConvention[];
266
+ /**
267
+ * alpha.87 — true ONLY on profiles synthesized by
268
+ * `onUnprofiledModel: 'best-effort'`. Lets compile() (and any consumer)
269
+ * distinguish "kgauto knows this model" from "kgauto is winging it with
270
+ * borrowed wire mechanics" on every call, not just the one that
271
+ * triggered synthesis. Never set on bundled, brain, or
272
+ * `registerProfiles()` entries.
273
+ */
274
+ bestEffort?: true;
266
275
  }
267
276
  /**
268
277
  * Representative p50 latency (ms) per tier. Coarse on purpose — used only to
@@ -291,6 +300,38 @@ interface ProfileBrainHook {
291
300
  }
292
301
  /** @internal — called by models-brain.ts at module load. */
293
302
  declare function _setProfileBrainHook(hook: ProfileBrainHook): void;
303
+ /**
304
+ * Register consumer-supplied profiles. They take precedence over both
305
+ * brain-curated and bundled profiles for the same id (explicit > learned >
306
+ * shipped — see block comment above for the tradeoff). Re-registering an
307
+ * id overwrites the previous consumer entry, including any best-effort
308
+ * synthesized profile.
309
+ */
310
+ declare function registerProfiles(profiles: readonly ModelProfile[]): void;
311
+ /** @internal — test hook. */
312
+ declare function _testClearConsumerProfiles(): void;
313
+ /** Provider inference for best-effort mode — id prefix conventions only. */
314
+ declare function inferProviderFromId(id: string): Provider | undefined;
315
+ /**
316
+ * alpha.87 — best-effort profile synthesis for unprofiled ids (opt-in via
317
+ * `CompilePolicy.onUnprofiledModel: 'best-effort'`; the default posture
318
+ * stays refuse). Returns undefined when the provider cannot be inferred
319
+ * from the id or kgauto ships no donor profile for that provider — in
320
+ * both cases the caller falls back to the standard refusal, which names
321
+ * `registerProfiles()` as the informed path.
322
+ *
323
+ * What a synthesized profile is: the inferred provider's wire mechanics
324
+ * (LoweringSpec / systemPromptMode / streaming are provider-wide, borrowed
325
+ * from a current bundled profile of that provider) around deliberately
326
+ * conservative capability claims — no cliffs, no recovery, no measured
327
+ * knowledge, `structuredOutput: 'none'`, sequential tools, modest output
328
+ * budget, and **cost 0 because cost is UNKNOWN** (cost gates and cost
329
+ * attribution are meaningless for this model; the compile carries a loud
330
+ * warning saying exactly that). It is registered into the consumer index
331
+ * on first synthesis so every later lookup in the process (fallback walk,
332
+ * passes, telemetry) sees one consistent object.
333
+ */
334
+ declare function bestEffortProfile(id: string): ModelProfile | undefined;
294
335
  /**
295
336
  * Resolve a model id to its canonical form (alias → canonical, unknown ids
296
337
  * returned unchanged). This is the same resolution `getProfile` applies, so
@@ -308,4 +349,4 @@ declare function allProfiles(): readonly ModelProfile[];
308
349
  declare function allProfilesRaw(): readonly ModelProfile[];
309
350
  declare function profilesByProvider(provider: Provider): readonly ModelProfile[];
310
351
 
311
- export { ALIASES, type ArchetypeConvention, type CacheStrategy, type CliffRule, LATENCY_TIER_MS, type LatencyTier, type LoweringSpec, type ModelProfile, type RecoveryRule, type StructuredOutputCapability, type SystemPromptMode, _setProfileBrainHook, allProfiles, allProfilesRaw, getProfile, latencyTierOf, profilesByProvider, resolveModelAlias, tryGetProfile };
352
+ export { ALIASES, type ArchetypeConvention, type CacheStrategy, type CliffRule, LATENCY_TIER_MS, type LatencyTier, type LoweringSpec, type ModelProfile, type RecoveryRule, type StructuredOutputCapability, type SystemPromptMode, _setProfileBrainHook, _testClearConsumerProfiles, allProfiles, allProfilesRaw, bestEffortProfile, getProfile, inferProviderFromId, latencyTierOf, profilesByProvider, registerProfiles, resolveModelAlias, tryGetProfile };