@warmdrift/kgauto-compiler 2.0.0-alpha.85 → 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/{chunk-LO2JXTGG.mjs → chunk-G3MKT7IR.mjs} +25 -13
- package/dist/{chunk-WXN7FNXP.mjs → chunk-GMZT4ZXD.mjs} +1 -1
- package/dist/{chunk-FD3NFXDC.mjs → chunk-YVKTTTTB.mjs} +189 -23
- package/dist/glassbox/index.d.mts +3 -3
- package/dist/glassbox/index.d.ts +3 -3
- package/dist/glassbox-routes/format.d.mts +2 -2
- package/dist/glassbox-routes/format.d.ts +2 -2
- package/dist/glassbox-routes/index.d.mts +4 -4
- package/dist/glassbox-routes/index.d.ts +4 -4
- package/dist/glassbox-routes/index.js +152 -34
- package/dist/glassbox-routes/index.mjs +2 -2
- package/dist/glassbox-routes/react/index.d.mts +2 -2
- package/dist/glassbox-routes/react/index.d.ts +2 -2
- package/dist/index.d.mts +60 -5
- package/dist/index.d.ts +60 -5
- package/dist/index.js +409 -44
- package/dist/index.mjs +200 -11
- package/dist/{ir-JUoybVM-.d.mts → ir-P3NEU8z4.d.mts} +116 -1
- package/dist/{ir-DfrM71pA.d.ts → ir-ZgN2KkuF.d.ts} +116 -1
- package/dist/key-health.js +1 -1
- package/dist/key-health.mjs +1 -1
- package/dist/profiles.d.mts +43 -2
- package/dist/profiles.d.ts +43 -2
- package/dist/profiles.js +193 -23
- package/dist/profiles.mjs +9 -1
- package/dist/{types-y42mwdvM.d.mts → types-7sF3adLO.d.mts} +1 -1
- package/dist/{types-BqTKRECa.d.ts → types-B_MjEB0h.d.ts} +1 -1
- package/dist/{types-DLDJbCha.d.ts → types-BgfuVIVI.d.ts} +1 -1
- package/dist/{types-BGH_KAHu.d.mts → types-CK0zUlVE.d.mts} +1 -1
- package/package.json +8 -2
package/dist/index.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
LIBRARY_VERSION,
|
|
20
20
|
createKeyHealthRoute,
|
|
21
21
|
keyFingerprint
|
|
22
|
-
} from "./chunk-
|
|
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-
|
|
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-
|
|
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) {
|
|
@@ -683,9 +692,12 @@ function passApplyCliffs(ir, profile, estimatedInputTokens) {
|
|
|
683
692
|
if (!triggered) continue;
|
|
684
693
|
switch (cliff.action) {
|
|
685
694
|
case "drop_to_top_relevant": {
|
|
686
|
-
const targetCount = Math.
|
|
687
|
-
|
|
688
|
-
Math.
|
|
695
|
+
const targetCount = Math.max(
|
|
696
|
+
1,
|
|
697
|
+
Math.min(
|
|
698
|
+
Math.floor(cliff.threshold * 0.75),
|
|
699
|
+
Math.floor((nextIR.tools?.length ?? 0) / 2)
|
|
700
|
+
)
|
|
689
701
|
);
|
|
690
702
|
if (nextIR.tools && nextIR.tools.length > targetCount) {
|
|
691
703
|
const intent = nextIR.intent.archetype;
|
|
@@ -1625,6 +1637,9 @@ function judgeMeasuredFailure(row, cfg = MEASURED_FAILURE_CFG) {
|
|
|
1625
1637
|
};
|
|
1626
1638
|
}
|
|
1627
1639
|
var snapshots2 = /* @__PURE__ */ new Map();
|
|
1640
|
+
function measuredFailureFreshness(appId) {
|
|
1641
|
+
return snapshots2.get(appId)?.loaded ? "warm" : "cold";
|
|
1642
|
+
}
|
|
1628
1643
|
var runtime2;
|
|
1629
1644
|
var warnedOnce2 = false;
|
|
1630
1645
|
var DEFAULT_MEASURED_FAILURE_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/measured-failure";
|
|
@@ -1722,6 +1737,7 @@ async function doRefresh2(rt, appId) {
|
|
|
1722
1737
|
const body = await res.json();
|
|
1723
1738
|
if (runtime2 !== rt) return;
|
|
1724
1739
|
snap.data = Array.isArray(body) ? mapRows(body) : [];
|
|
1740
|
+
snap.loaded = true;
|
|
1725
1741
|
snap.expiresAt = Date.now() + rt.ttlMs;
|
|
1726
1742
|
snap.refreshing = false;
|
|
1727
1743
|
} catch (err) {
|
|
@@ -1793,6 +1809,9 @@ function mapRowsToPromotions(rows) {
|
|
|
1793
1809
|
return out;
|
|
1794
1810
|
}
|
|
1795
1811
|
var snapshots3 = /* @__PURE__ */ new Map();
|
|
1812
|
+
function promotionsFreshness(appId) {
|
|
1813
|
+
return snapshots3.get(appId)?.loaded ? "warm" : "cold";
|
|
1814
|
+
}
|
|
1796
1815
|
var runtime3;
|
|
1797
1816
|
var warnedOnce3 = false;
|
|
1798
1817
|
var DEFAULT_PROMOTIONS_ENDPOINT = "https://kgauto-dashboard.vercel.app/api/kgauto-v2/promotions";
|
|
@@ -1877,6 +1896,7 @@ async function doRefresh3(rt, appId) {
|
|
|
1877
1896
|
if (runtime3 !== rt) return;
|
|
1878
1897
|
const rows = Array.isArray(body) ? mapRowsToPromotions(body) : [];
|
|
1879
1898
|
snap.data = rows;
|
|
1899
|
+
snap.loaded = true;
|
|
1880
1900
|
snap.expiresAt = Date.now() + rt.ttlMs;
|
|
1881
1901
|
snap.refreshing = false;
|
|
1882
1902
|
} catch (err) {
|
|
@@ -1895,6 +1915,40 @@ function defaultOnError3(err) {
|
|
|
1895
1915
|
err
|
|
1896
1916
|
);
|
|
1897
1917
|
}
|
|
1918
|
+
function prefetchPromotions(appId) {
|
|
1919
|
+
const rt = runtime3;
|
|
1920
|
+
if (!rt || !appId) return void 0;
|
|
1921
|
+
let snap = snapshots3.get(appId);
|
|
1922
|
+
if (!snap) {
|
|
1923
|
+
snap = { data: [], expiresAt: 0, refreshing: false };
|
|
1924
|
+
snapshots3.set(appId, snap);
|
|
1925
|
+
}
|
|
1926
|
+
if (snap.expiresAt > Date.now()) return void 0;
|
|
1927
|
+
const inflight = pendingRefreshes3.get(appId);
|
|
1928
|
+
if (inflight) return inflight;
|
|
1929
|
+
if (snap.refreshing) return void 0;
|
|
1930
|
+
snap.refreshing = true;
|
|
1931
|
+
void asyncRefresh3(rt, appId);
|
|
1932
|
+
return pendingRefreshes3.get(appId);
|
|
1933
|
+
}
|
|
1934
|
+
async function awaitPromotionsReady(appId, timeoutMs) {
|
|
1935
|
+
if (!runtime3 || !appId) return;
|
|
1936
|
+
const pending = prefetchPromotions(appId) ?? pendingRefreshes3.get(appId);
|
|
1937
|
+
if (!(timeoutMs > 0)) return;
|
|
1938
|
+
if (!pending) return;
|
|
1939
|
+
let timer;
|
|
1940
|
+
try {
|
|
1941
|
+
await Promise.race([
|
|
1942
|
+
pending,
|
|
1943
|
+
new Promise((resolve) => {
|
|
1944
|
+
timer = setTimeout(resolve, timeoutMs);
|
|
1945
|
+
})
|
|
1946
|
+
]);
|
|
1947
|
+
} catch {
|
|
1948
|
+
} finally {
|
|
1949
|
+
if (timer) clearTimeout(timer);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1898
1952
|
function _testResetPromotions() {
|
|
1899
1953
|
runtime3 = void 0;
|
|
1900
1954
|
snapshots3.clear();
|
|
@@ -1943,6 +1997,9 @@ function mapRowsToFindings2(rows) {
|
|
|
1943
1997
|
return out;
|
|
1944
1998
|
}
|
|
1945
1999
|
var snapshots4 = /* @__PURE__ */ new Map();
|
|
2000
|
+
function promoteReadyFreshness(appId) {
|
|
2001
|
+
return snapshots4.get(appId)?.loaded ? "warm" : "cold";
|
|
2002
|
+
}
|
|
1946
2003
|
var runtime4;
|
|
1947
2004
|
var warnedOnce4 = false;
|
|
1948
2005
|
function isPromoteReadyBrainActive() {
|
|
@@ -2001,6 +2058,7 @@ async function doRefresh4(rt, appId) {
|
|
|
2001
2058
|
if (runtime4 !== rt) return;
|
|
2002
2059
|
const rows = Array.isArray(body) ? mapRowsToFindings2(body) : [];
|
|
2003
2060
|
snap.data = rows;
|
|
2061
|
+
snap.loaded = true;
|
|
2004
2062
|
snap.expiresAt = Date.now() + rt.ttlMs;
|
|
2005
2063
|
snap.refreshing = false;
|
|
2006
2064
|
} catch (err) {
|
|
@@ -2425,6 +2483,31 @@ function advisorRuleBlockedModelDrift(ctx) {
|
|
|
2425
2483
|
return out;
|
|
2426
2484
|
}
|
|
2427
2485
|
|
|
2486
|
+
// src/advisor-rules/preferred-blocked-overlap.ts
|
|
2487
|
+
var PREFERRED_MODEL_BLOCKED_CODE = "preferred-model-blocked";
|
|
2488
|
+
var DOCS_URL2 = "https://github.com/stue/command-center/blob/main/interfaces/kgauto.md#best-practice-advisories";
|
|
2489
|
+
function advisorRulePreferredBlockedOverlap(ctx) {
|
|
2490
|
+
const preferred = ctx.policy?.preferredModels;
|
|
2491
|
+
const blocked = ctx.policy?.blockedModels;
|
|
2492
|
+
if (!preferred?.length || !blocked?.length) return [];
|
|
2493
|
+
const blockedSet = canonicalPolicySet(blocked);
|
|
2494
|
+
const deadPins = [...new Set(preferred)].filter((p) => policySetHas(blockedSet, p)).sort();
|
|
2495
|
+
if (deadPins.length === 0) return [];
|
|
2496
|
+
const list = deadPins.map((p) => `\`${p}\``).join(", ");
|
|
2497
|
+
const one = deadPins.length === 1;
|
|
2498
|
+
const preferredSet = canonicalPolicySet(preferred);
|
|
2499
|
+
const servedIsPinned = policySetHas(preferredSet, ctx.selectedModelId);
|
|
2500
|
+
return [
|
|
2501
|
+
{
|
|
2502
|
+
level: "warn",
|
|
2503
|
+
code: PREFERRED_MODEL_BLOCKED_CODE,
|
|
2504
|
+
message: `CompilePolicy.preferredModels entr${one ? "y" : "ies"} ${list} ${one ? "is" : "are"} also in \`blockedModels\` (matched canonically, aliases included). A blocked model is hard-rejected before preference boosts apply, so ${one ? "this pin" : "these pins"} can never serve. ` + (servedIsPinned ? `This call was served by \`${ctx.selectedModelId}\`, which is itself a live pin \u2014 the dead entr${one ? "y is" : "ies are"} latent, not currently rerouting traffic.` : `Substitution is your steady state: this call landed on \`${ctx.selectedModelId}\`, which you did not pin.`),
|
|
2505
|
+
suggestion: `Two readings, and kgauto cannot tell them apart: (1) intentional \u2014 your spend gate deliberately outranks the pin, in which case nothing needs doing and you can filter this code; (2) misconfiguration \u2014 the pin and the block were written at different times and the overlap is an accident. tt-intel hit reading (2) on 2026-08-01: a summarize site pinned \`claude-sonnet\` while \`KGAUTO_BLOCKED_MODELS\` carried the same family, and every call silently substituted a reasoning model whose reasoning burn exceeded the site's \`maxOutputTokens\` \u2014 100% empty payloads under HTTP 200. If the block should win, remove the pin so the policy says what it does. If the pin should win, remove ${one ? "the blocking entry" : "the blocking entries"} or re-scope the block to the exact ids you mean. Check what the substitute costs at your input shape while you are here \u2014 a spend gate that lands traffic on a pricier model than the one it blocked is a cost inversion, not a saving.`,
|
|
2506
|
+
docsUrl: DOCS_URL2
|
|
2507
|
+
}
|
|
2508
|
+
];
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2428
2511
|
// src/advisor.ts
|
|
2429
2512
|
var QUALITY_FLOOR_FOR_RECOMMENDATION = 6;
|
|
2430
2513
|
var TIER_DOWN_COST_RATIO = 0.5;
|
|
@@ -2449,6 +2532,12 @@ function runAdvisor(ir, result, profile, policy, phase2) {
|
|
|
2449
2532
|
selectedModelId: profile.id
|
|
2450
2533
|
})
|
|
2451
2534
|
);
|
|
2535
|
+
out.push(
|
|
2536
|
+
...advisorRulePreferredBlockedOverlap({
|
|
2537
|
+
policy,
|
|
2538
|
+
selectedModelId: profile.id
|
|
2539
|
+
})
|
|
2540
|
+
);
|
|
2452
2541
|
if (policy?.posture !== "locked") {
|
|
2453
2542
|
out.push(...detectCostMismatchedArchetype(ir, profile, phase2));
|
|
2454
2543
|
out.push(...detectModelStaleEvidence(ir, profile));
|
|
@@ -2919,7 +3008,16 @@ function makeHandle() {
|
|
|
2919
3008
|
return `c${Date.now().toString(36)}-${counter.toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
|
2920
3009
|
}
|
|
2921
3010
|
function compile(ir, opts = {}) {
|
|
2922
|
-
const
|
|
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;
|
|
2923
3021
|
validateIR(ir);
|
|
2924
3022
|
ir = resolveModelEntries(ir);
|
|
2925
3023
|
const sliced = passSlice(ir);
|
|
@@ -2979,11 +3077,26 @@ function compile(ir, opts = {}) {
|
|
|
2979
3077
|
accumulatedMutations.push(...scores.mutations);
|
|
2980
3078
|
const target = pickTarget(workingIR, scores.value);
|
|
2981
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.` : "") : "";
|
|
2982
3083
|
throw new Error(
|
|
2983
|
-
`compile(): no allowed model fits the request
|
|
3084
|
+
`compile(): no allowed model fits the request.${unknownHint} Scores: ${JSON.stringify(scores.value, null, 2)}`
|
|
2984
3085
|
);
|
|
2985
3086
|
}
|
|
2986
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
|
+
}
|
|
2987
3100
|
const fallbackChain = scores.value.filter((s) => s.modelId !== target.modelId && s.fits).sort((a, b) => b.rank - a.rank).map((s) => s.modelId);
|
|
2988
3101
|
const cliffs = passApplyCliffs(workingIR, profile, inputTokens);
|
|
2989
3102
|
workingIR = cliffs.value.ir;
|
|
@@ -3069,6 +3182,23 @@ function compile(ir, opts = {}) {
|
|
|
3069
3182
|
const historyCacheMarkIndex = computeHistoryCacheMarkIndex(workingIR);
|
|
3070
3183
|
const systemMessages = buildSystemMessages(workingIR, profile.provider);
|
|
3071
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
|
+
});
|
|
3072
3202
|
const diagnostics = {
|
|
3073
3203
|
sectionsKept: workingIR.sections.length,
|
|
3074
3204
|
sectionsDropped: ir.sections.length - workingIR.sections.length,
|
|
@@ -3092,11 +3222,25 @@ function compile(ir, opts = {}) {
|
|
|
3092
3222
|
// text the consumer can route on without changing behavior).
|
|
3093
3223
|
cliffWarnings: [
|
|
3094
3224
|
...cliffs.value.loweringHints.qualityWarning ?? [],
|
|
3095
|
-
...conventions.value.cliffWarnings
|
|
3225
|
+
...conventions.value.cliffWarnings,
|
|
3226
|
+
// alpha.87 — best-effort profile in use (loud on EVERY compile).
|
|
3227
|
+
...bestEffortWarnings
|
|
3096
3228
|
],
|
|
3097
3229
|
// alpha.68 / Release A — measured discipline gate-token tax (§5.D). 0 when
|
|
3098
3230
|
// the gate didn't fire.
|
|
3099
|
-
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
|
|
3100
3244
|
};
|
|
3101
3245
|
if (ir.intent.archetype === "hunt" && ir.constraints?.toolOrchestration === "sequential") {
|
|
3102
3246
|
accumulatedMutations.push({
|
|
@@ -3369,6 +3513,12 @@ function configureBrain(config) {
|
|
|
3369
3513
|
fetchImpl: config.fetchImpl ?? fetch,
|
|
3370
3514
|
onError: config.onError
|
|
3371
3515
|
});
|
|
3516
|
+
if (config.appId) {
|
|
3517
|
+
try {
|
|
3518
|
+
void prefetchPromotions(config.appId);
|
|
3519
|
+
} catch {
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3372
3522
|
} else {
|
|
3373
3523
|
configurePromotionsBrain(void 0);
|
|
3374
3524
|
}
|
|
@@ -3626,6 +3776,26 @@ function maybeWarnDiscardedCompile(reg, handle) {
|
|
|
3626
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 }).`
|
|
3627
3777
|
);
|
|
3628
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
|
+
}
|
|
3629
3799
|
async function record(input) {
|
|
3630
3800
|
const reg = compileRegistry.get(input.handle);
|
|
3631
3801
|
if (reg) {
|
|
@@ -3740,6 +3910,9 @@ function buildPayload(input, reg) {
|
|
|
3740
3910
|
latency_ms: input.latencyMs,
|
|
3741
3911
|
success: input.success,
|
|
3742
3912
|
empty_response: input.emptyResponse ?? input.tokensOut === 0,
|
|
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),
|
|
3743
3916
|
error_type: input.errorType,
|
|
3744
3917
|
tools_called: input.toolsCalled,
|
|
3745
3918
|
oracle_score: input.oracleScore?.score,
|
|
@@ -4838,7 +5011,11 @@ async function call(ir, opts = {}) {
|
|
|
4838
5011
|
)
|
|
4839
5012
|
})
|
|
4840
5013
|
);
|
|
4841
|
-
|
|
5014
|
+
const warmupMs = resolveGateWarmupMs(opts);
|
|
5015
|
+
await Promise.all([
|
|
5016
|
+
awaitMeasuredFailureReady(ir.appId, warmupMs),
|
|
5017
|
+
awaitPromotionsReady(ir.appId, warmupMs)
|
|
5018
|
+
]);
|
|
4842
5019
|
const initial = compileAndRegister(ir, opts);
|
|
4843
5020
|
safeEmit(
|
|
4844
5021
|
() => emitCompileDone(traceId, ir.appId, {
|
|
@@ -4878,6 +5055,7 @@ async function call(ir, opts = {}) {
|
|
|
4878
5055
|
const latencyMs2 = Date.now() - start;
|
|
4879
5056
|
await record({
|
|
4880
5057
|
handle: initial.handle,
|
|
5058
|
+
source: opts.source,
|
|
4881
5059
|
tokensIn: 0,
|
|
4882
5060
|
tokensOut: 0,
|
|
4883
5061
|
latencyMs: latencyMs2,
|
|
@@ -4930,6 +5108,7 @@ async function call(ir, opts = {}) {
|
|
|
4930
5108
|
const latencyMs2 = Date.now() - start;
|
|
4931
5109
|
await record({
|
|
4932
5110
|
handle: initial.handle,
|
|
5111
|
+
source: opts.source,
|
|
4933
5112
|
tokensIn: 0,
|
|
4934
5113
|
tokensOut: 0,
|
|
4935
5114
|
latencyMs: latencyMs2,
|
|
@@ -5071,6 +5250,7 @@ async function call(ir, opts = {}) {
|
|
|
5071
5250
|
const goldenShapeKey = goldenRate > 0 ? peekRegisteredShapeKey(initial.handle) : void 0;
|
|
5072
5251
|
await record({
|
|
5073
5252
|
handle: initial.handle,
|
|
5253
|
+
source: opts.source,
|
|
5074
5254
|
tokensIn: validated.response.tokens.input,
|
|
5075
5255
|
tokensOut: validated.response.tokens.output,
|
|
5076
5256
|
latencyMs: latencyMs2,
|
|
@@ -5193,6 +5373,7 @@ async function call(ir, opts = {}) {
|
|
|
5193
5373
|
const latencyMs = Date.now() - start;
|
|
5194
5374
|
await record({
|
|
5195
5375
|
handle: initial.handle,
|
|
5376
|
+
source: opts.source,
|
|
5196
5377
|
tokensIn: lastErr?.tokens?.input ?? 0,
|
|
5197
5378
|
tokensOut: lastErr?.tokens?.output ?? 0,
|
|
5198
5379
|
latencyMs,
|
|
@@ -7346,7 +7527,9 @@ export {
|
|
|
7346
7527
|
STRATEGY_AUTHORSHIP_INDEPENDENT,
|
|
7347
7528
|
STRATEGY_AUTHORSHIP_LIMITATION,
|
|
7348
7529
|
TRANSLATOR_FLOOR,
|
|
7530
|
+
_testClearConsumerProfiles,
|
|
7349
7531
|
_testResetMeasuredFailure,
|
|
7532
|
+
_testResetOutcomeSourceWarning,
|
|
7350
7533
|
_testResetPromotions,
|
|
7351
7534
|
_testWaitForMeasuredFailureRefresh,
|
|
7352
7535
|
_testWaitForPromotionsRefresh,
|
|
@@ -7357,6 +7540,8 @@ export {
|
|
|
7357
7540
|
applySectionRewrites,
|
|
7358
7541
|
attachCacheControlToStreamTextInput,
|
|
7359
7542
|
awaitMeasuredFailureReady,
|
|
7543
|
+
awaitPromotionsReady,
|
|
7544
|
+
bestEffortProfile,
|
|
7360
7545
|
brainHealth,
|
|
7361
7546
|
bucketContext,
|
|
7362
7547
|
bucketHistory,
|
|
@@ -7411,6 +7596,7 @@ export {
|
|
|
7411
7596
|
getStarterChainWithGrounding,
|
|
7412
7597
|
hasMutation,
|
|
7413
7598
|
hashShape,
|
|
7599
|
+
inferProviderFromId,
|
|
7414
7600
|
isAltStrategy,
|
|
7415
7601
|
isArchetype,
|
|
7416
7602
|
isAutoPromoteEnabledFromEnv,
|
|
@@ -7443,6 +7629,7 @@ export {
|
|
|
7443
7629
|
peekBrainDeadLetter,
|
|
7444
7630
|
planDecomposition,
|
|
7445
7631
|
prefetchMeasuredFailure,
|
|
7632
|
+
prefetchPromotions,
|
|
7446
7633
|
probeShadow,
|
|
7447
7634
|
profileToRow,
|
|
7448
7635
|
profilesByProvider,
|
|
@@ -7451,11 +7638,13 @@ export {
|
|
|
7451
7638
|
recordGoldenIr,
|
|
7452
7639
|
recordOutcome,
|
|
7453
7640
|
recordShadowProbe,
|
|
7641
|
+
registerProfiles,
|
|
7454
7642
|
renderIrForJudge,
|
|
7455
7643
|
resetTokenizer,
|
|
7456
7644
|
resolveConventionsForProfile,
|
|
7457
7645
|
resolveGoldenCaptureRate,
|
|
7458
7646
|
resolveModelAlias,
|
|
7647
|
+
resolveOutcomeSource,
|
|
7459
7648
|
resolvePricingAt,
|
|
7460
7649
|
resolveProviderKey,
|
|
7461
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 })`
|
|
@@ -1084,6 +1167,13 @@ interface ShadowProbeConfig {
|
|
|
1084
1167
|
skipSlowTierInSync?: boolean;
|
|
1085
1168
|
}
|
|
1086
1169
|
interface CallOptions {
|
|
1170
|
+
/**
|
|
1171
|
+
* alpha.86 — self-mark for synthetic callers (canaries, smokes, eval
|
|
1172
|
+
* replays, probes). Passed through to every outcome row this call
|
|
1173
|
+
* records, including failure rows. OMIT for real traffic. See
|
|
1174
|
+
* {@link OutcomeSource}.
|
|
1175
|
+
*/
|
|
1176
|
+
source?: OutcomeSource;
|
|
1087
1177
|
/**
|
|
1088
1178
|
* alpha.84 — fires once per FAILED attempt during the fallback walk, before
|
|
1089
1179
|
* the walk continues. IC-Cairn's filing, 2026-07-29.
|
|
@@ -1458,9 +1548,34 @@ interface OracleScore {
|
|
|
1458
1548
|
/** Free-form explanation for debugging. */
|
|
1459
1549
|
rationale?: string;
|
|
1460
1550
|
}
|
|
1551
|
+
/**
|
|
1552
|
+
* alpha.86 — who originated an outcome row (migration 056).
|
|
1553
|
+
*
|
|
1554
|
+
* Absent/undefined means ORGANIC: a real consumer call on behalf of a real
|
|
1555
|
+
* user. Consumers change nothing. Synthetic writers — canaries, smoke
|
|
1556
|
+
* gates, eval replays, probe harnesses — self-mark, so liveness and volume
|
|
1557
|
+
* rules can compute over consumer-originated rows only.
|
|
1558
|
+
*
|
|
1559
|
+
* The incident this closes (cost-watch 2026-08-06 → 08-08): playbacksam's
|
|
1560
|
+
* daily canary wrote exactly 8 rows/day for 13 straight days while PB's
|
|
1561
|
+
* organic traffic was near-zero, and the liveness rule scored PB the
|
|
1562
|
+
* healthiest consumer in the portfolio. On 08-08 EVERY row the brain
|
|
1563
|
+
* received in 24h was canary, and no rule could say so — distinguishing a
|
|
1564
|
+
* replay from real traffic took a hand-reconstructed time-window +
|
|
1565
|
+
* token-fingerprint argument, three mornings running. A consumer whose
|
|
1566
|
+
* only rows are written by kgauto's own machinery is dark, not healthy;
|
|
1567
|
+
* this column is what lets a rule print that sentence.
|
|
1568
|
+
*/
|
|
1569
|
+
type OutcomeSource = 'canary' | 'smoke' | 'eval' | 'probe' | 'synthetic';
|
|
1461
1570
|
interface RecordInput {
|
|
1462
1571
|
/** Handle from CompileResult. */
|
|
1463
1572
|
handle: string;
|
|
1573
|
+
/**
|
|
1574
|
+
* alpha.86 — self-mark for synthetic writers (migration 056). OMIT for
|
|
1575
|
+
* real traffic; never write an explicit "organic" value. See
|
|
1576
|
+
* {@link OutcomeSource}.
|
|
1577
|
+
*/
|
|
1578
|
+
source?: OutcomeSource;
|
|
1464
1579
|
/** Actual tokens consumed (post-call). */
|
|
1465
1580
|
tokensIn: number;
|
|
1466
1581
|
tokensOut: number;
|
|
@@ -1753,4 +1868,4 @@ interface PerAxisMetrics {
|
|
|
1753
1868
|
/** Per-axis metrics keyed by model — used for chain-comparison views. */
|
|
1754
1869
|
type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
|
|
1755
1870
|
|
|
1756
|
-
export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C,
|
|
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 };
|