@warmdrift/kgauto-compiler 2.0.0-alpha.47 → 2.0.0-alpha.48

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/README.md CHANGED
@@ -89,6 +89,37 @@ await record({
89
89
  });
90
90
  ```
91
91
 
92
+ ### `probeShadow()` — measure a swap candidate from an AI-SDK route (alpha.48)
93
+
94
+ `call()` runs a full-IR shadow probe internally (`shadowProbe` option). AI-SDK consumers who drive `streamText()` themselves never call `call()`, so they reach the same probe via the standalone `probeShadow()` export — fire it from `onFinish`, passing the served leg you already have, wrapped in `waitUntil()`/`after()` so it never blocks the response.
95
+
96
+ ```ts
97
+ import { probeShadow, configureBrain } from '@warmdrift/kgauto-compiler';
98
+ import { after } from 'next/server'; // or the platform's waitUntil()
99
+
100
+ configureBrain({ endpoint: 'https://your-app.com/api/kgauto/v2', apiKey: '...' });
101
+
102
+ const t0 = Date.now();
103
+ const result = streamText({
104
+ model, system, messages,
105
+ onFinish: ({ text, usage }) => {
106
+ after(() => probeShadow(ir, {
107
+ served: {
108
+ model: servedModelId,
109
+ responseText: text,
110
+ tokensIn: usage.promptTokens,
111
+ tokensOut: usage.completionTokens,
112
+ latencyMs: Date.now() - t0,
113
+ },
114
+ candidates: ['deepseek-v4-pro'], // what you'd consider swapping to
115
+ sampleRate: 0.05, // pin 1 for a dogfood window
116
+ }));
117
+ },
118
+ });
119
+ ```
120
+
121
+ kgauto runs each candidate on the **same IR** and persists a `probe_outcomes` row (`replay_source='inline-full-ir'`, `prompt_fidelity=1.0`, both latency legs). Phase 1 is `judge:'off'` — rows accumulate for an offline verdict rollup; inline Opus judging is Phase 2. Fire-and-forget: never throws into your `onFinish`.
122
+
92
123
  ## Structured advisories API (alpha.29+)
93
124
 
94
125
  kgauto's compile-time advisories (`caching-off-on-claude`, `tool-bloat`,
package/dist/index.d.mts CHANGED
@@ -102,6 +102,70 @@ declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promi
102
102
  * exhausted without success.
103
103
  */
104
104
  declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
105
+ /** Served-side result the AI-SDK consumer already holds from streamText. */
106
+ interface ProbeShadowServed {
107
+ /** Model id that actually served the user (becomes `current_model` on the row). */
108
+ model: string;
109
+ /** The served response text (stored as a preview; never the prompt). */
110
+ responseText: string;
111
+ /** Served prompt tokens (AI SDK `usage.promptTokens`). */
112
+ tokensIn: number;
113
+ /** Served completion tokens (AI SDK `usage.completionTokens`). */
114
+ tokensOut: number;
115
+ /** The user's actual wait in ms (alpha.46 served-latency axis). */
116
+ latencyMs: number;
117
+ }
118
+ /** Options for the standalone {@link probeShadow} export. */
119
+ interface ProbeShadowOptions {
120
+ /** The served leg the consumer supplies; kgauto runs the candidate leg. */
121
+ served: ProbeShadowServed;
122
+ /** Model id(s)/family alias(es) to shadow-test against the served model. */
123
+ candidates: string | string[];
124
+ /** Probability [0,1] a given call fires a probe. Default 0.05; pin 1 for dogfood. */
125
+ sampleRate?: number;
126
+ /** Phase 1 = 'off' (offline rollup). 'opus' inline judge is Phase 2. Default 'off'. */
127
+ judge?: 'off' | 'opus';
128
+ /** Override API keys (defaults: process.env). Gates candidate reachability. */
129
+ apiKeys?: ApiKeys;
130
+ /** Override fetch (for tests / custom transport). */
131
+ fetchImpl?: typeof fetch;
132
+ /** Provider-specific request fields shallow-merged into the candidate request. */
133
+ providerOverrides?: ProviderOverrides;
134
+ /** Forwarded to compile() for the candidate run (match the served-side compile). */
135
+ policy?: CompilePolicy;
136
+ toolRelevanceThreshold?: number;
137
+ compressHistoryAfter?: number;
138
+ }
139
+ /**
140
+ * s54 — standalone full-IR shadow probe for AI-SDK consumers (tt-intel hunt, IC
141
+ * chat) that own their own streamText round-trip and never call call(). Fire it
142
+ * from the streamText `onFinish` callback, wrapped in the platform's
143
+ * `waitUntil()` / `after()`, so it runs after the response is flushed — no
144
+ * blocking, no `sync:true`, no teardown race (cleaner than call()'s in-process
145
+ * fire-and-forget for Edge runtimes; L-086).
146
+ *
147
+ * Runs the SAME candidate loop as the call()-inline probe ({@link
148
+ * runProbeCandidates}): same gates (sample, self-skip, G4 judge-self,
149
+ * reachability, G6), same fidelity=1.0 full-IR rows, same alpha.46 latency
150
+ * capture. The consumer supplies the served leg it already has; kgauto runs the
151
+ * candidate(s) and writes the `probe_outcomes` row.
152
+ *
153
+ * Requires `configureBrain()` to have been called (same as call()).
154
+ * Fire-and-forget: never throws into the caller.
155
+ *
156
+ * @example
157
+ * const result = streamText({ model, system, messages,
158
+ * onFinish: ({ text, usage }) => {
159
+ * after(() => probeShadow(ir, {
160
+ * served: { model: servedModelId, responseText: text,
161
+ * tokensIn: usage.promptTokens, tokensOut: usage.completionTokens,
162
+ * latencyMs: Date.now() - t0 },
163
+ * candidates: ['deepseek-v4-pro'], sampleRate: 0.05,
164
+ * }));
165
+ * },
166
+ * });
167
+ */
168
+ declare function probeShadow(ir: PromptIR, opts: ProbeShadowOptions): Promise<void>;
105
169
 
106
170
  /**
107
171
  * alpha.33 — AI-SDK streamText helpers.
@@ -2195,4 +2259,4 @@ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions):
2195
2259
  */
2196
2260
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2197
2261
 
2198
- export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, Grounding, IntentArchetypeName, type LLMJudgeOptions, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, buildShadowProbeRow, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, profileToRow, readBrainReadEnv, record, recordOutcome, recordShadowProbe, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
2262
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, Grounding, IntentArchetypeName, type LLMJudgeOptions, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, buildShadowProbeRow, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, probeShadow, profileToRow, readBrainReadEnv, record, recordOutcome, recordShadowProbe, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
package/dist/index.d.ts CHANGED
@@ -102,6 +102,70 @@ declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promi
102
102
  * exhausted without success.
103
103
  */
104
104
  declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
105
+ /** Served-side result the AI-SDK consumer already holds from streamText. */
106
+ interface ProbeShadowServed {
107
+ /** Model id that actually served the user (becomes `current_model` on the row). */
108
+ model: string;
109
+ /** The served response text (stored as a preview; never the prompt). */
110
+ responseText: string;
111
+ /** Served prompt tokens (AI SDK `usage.promptTokens`). */
112
+ tokensIn: number;
113
+ /** Served completion tokens (AI SDK `usage.completionTokens`). */
114
+ tokensOut: number;
115
+ /** The user's actual wait in ms (alpha.46 served-latency axis). */
116
+ latencyMs: number;
117
+ }
118
+ /** Options for the standalone {@link probeShadow} export. */
119
+ interface ProbeShadowOptions {
120
+ /** The served leg the consumer supplies; kgauto runs the candidate leg. */
121
+ served: ProbeShadowServed;
122
+ /** Model id(s)/family alias(es) to shadow-test against the served model. */
123
+ candidates: string | string[];
124
+ /** Probability [0,1] a given call fires a probe. Default 0.05; pin 1 for dogfood. */
125
+ sampleRate?: number;
126
+ /** Phase 1 = 'off' (offline rollup). 'opus' inline judge is Phase 2. Default 'off'. */
127
+ judge?: 'off' | 'opus';
128
+ /** Override API keys (defaults: process.env). Gates candidate reachability. */
129
+ apiKeys?: ApiKeys;
130
+ /** Override fetch (for tests / custom transport). */
131
+ fetchImpl?: typeof fetch;
132
+ /** Provider-specific request fields shallow-merged into the candidate request. */
133
+ providerOverrides?: ProviderOverrides;
134
+ /** Forwarded to compile() for the candidate run (match the served-side compile). */
135
+ policy?: CompilePolicy;
136
+ toolRelevanceThreshold?: number;
137
+ compressHistoryAfter?: number;
138
+ }
139
+ /**
140
+ * s54 — standalone full-IR shadow probe for AI-SDK consumers (tt-intel hunt, IC
141
+ * chat) that own their own streamText round-trip and never call call(). Fire it
142
+ * from the streamText `onFinish` callback, wrapped in the platform's
143
+ * `waitUntil()` / `after()`, so it runs after the response is flushed — no
144
+ * blocking, no `sync:true`, no teardown race (cleaner than call()'s in-process
145
+ * fire-and-forget for Edge runtimes; L-086).
146
+ *
147
+ * Runs the SAME candidate loop as the call()-inline probe ({@link
148
+ * runProbeCandidates}): same gates (sample, self-skip, G4 judge-self,
149
+ * reachability, G6), same fidelity=1.0 full-IR rows, same alpha.46 latency
150
+ * capture. The consumer supplies the served leg it already has; kgauto runs the
151
+ * candidate(s) and writes the `probe_outcomes` row.
152
+ *
153
+ * Requires `configureBrain()` to have been called (same as call()).
154
+ * Fire-and-forget: never throws into the caller.
155
+ *
156
+ * @example
157
+ * const result = streamText({ model, system, messages,
158
+ * onFinish: ({ text, usage }) => {
159
+ * after(() => probeShadow(ir, {
160
+ * served: { model: servedModelId, responseText: text,
161
+ * tokensIn: usage.promptTokens, tokensOut: usage.completionTokens,
162
+ * latencyMs: Date.now() - t0 },
163
+ * candidates: ['deepseek-v4-pro'], sampleRate: 0.05,
164
+ * }));
165
+ * },
166
+ * });
167
+ */
168
+ declare function probeShadow(ir: PromptIR, opts: ProbeShadowOptions): Promise<void>;
105
169
 
106
170
  /**
107
171
  * alpha.33 — AI-SDK streamText helpers.
@@ -2195,4 +2259,4 @@ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions):
2195
2259
  */
2196
2260
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2197
2261
 
2198
- export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, Grounding, IntentArchetypeName, type LLMJudgeOptions, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, buildShadowProbeRow, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, profileToRow, readBrainReadEnv, record, recordOutcome, recordShadowProbe, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
2262
+ export { ABSOLUTE_FLOOR, type AISDKConvertedMessage, ARCHETYPE_FAMILY_FITS, ARCHETYPE_FLOOR_DEFAULT, type ActionableAdvisory, Adapter, type AdvisoryResolutionSource, type AdvisorySeverity, type AdvisoryStatus, type AdvisorySuggestedFix, ApiKeys, type AppOracle, type ApplySectionRewritesArgs, type ApplySectionRewritesResult, ArchetypeConvention, type ArchetypeFamilyFit, type ArchetypePerfMap, type ArchetypePerfNMap, type ArchetypePerfScoreResult, type AttachCacheControlResult, BestPracticeAdvisory, type BrainConfig, type BrainQueryConfig, type BrainReadEnv, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DEFAULT_FINDINGS_ENDPOINT, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type FallbackPosture, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetDefaultFallbackChainOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, Grounding, IntentArchetypeName, type LLMJudgeOptions, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, PromptIR, Provider, ProviderOverrides, type ProviderReachability, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, SectionRewrite, type ShadowProbeRecordInput, type SupportedProvider, SystemModelMessage, TRANSLATOR_FLOOR, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, buildLLMJudge, buildShadowProbeRow, call, clearBrain, compile, configureBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isModelReachable, isProviderReachable, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, probeShadow, profileToRow, readBrainReadEnv, record, recordOutcome, recordShadowProbe, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, runAdvisor, setTokenizer };
package/dist/index.js CHANGED
@@ -88,6 +88,7 @@ __export(index_exports, {
88
88
  markAdvisoryResolved: () => markAdvisoryResolved,
89
89
  markExclusionFindingHandled: () => markExclusionFindingHandled,
90
90
  markPromoteReadyHandled: () => markPromoteReadyHandled,
91
+ probeShadow: () => probeShadow,
91
92
  profileToRow: () => profileToRow,
92
93
  profilesByProvider: () => profilesByProvider,
93
94
  readBrainReadEnv: () => readBrainReadEnv,
@@ -6157,16 +6158,15 @@ function hashForProbe(s) {
6157
6158
  for (let i = 0; i < s.length; i++) h = (h << 5) - h + s.charCodeAt(i) | 0;
6158
6159
  return `h${(h >>> 0).toString(16)}`;
6159
6160
  }
6160
- async function runShadowProbe(args) {
6161
+ async function runProbeCandidates(args) {
6161
6162
  try {
6162
- const cfg = args.opts.shadowProbe;
6163
- if (!shouldSampleProbe(cfg.sampleRate ?? 0.05)) return;
6164
- const candidates = normalizeProbeCandidates(cfg.candidates);
6163
+ if (!shouldSampleProbe(args.cfg.sampleRate ?? 0.05)) return;
6164
+ const candidates = normalizeProbeCandidates(args.cfg.candidates);
6165
6165
  const promptHash = hashForProbe(args.ir.currentTurn?.content ?? "");
6166
6166
  for (const candidate of candidates) {
6167
6167
  if (candidate === args.servedModel) continue;
6168
6168
  if (deriveFamilyFromModelId(candidate) === "claude-opus") continue;
6169
- if (!isModelReachable(candidate, { apiKeys: args.opts.apiKeys })) continue;
6169
+ if (!isModelReachable(candidate, { apiKeys: args.exec.apiKeys })) continue;
6170
6170
  try {
6171
6171
  const candCompile = compileAndRegister(
6172
6172
  {
@@ -6174,13 +6174,13 @@ async function runShadowProbe(args) {
6174
6174
  models: args.ir.models.includes(candidate) ? args.ir.models : [candidate, ...args.ir.models],
6175
6175
  constraints: { ...args.ir.constraints ?? {}, forceModel: candidate }
6176
6176
  },
6177
- args.opts
6177
+ args.exec
6178
6178
  );
6179
6179
  const candStart = Date.now();
6180
6180
  const exec = await execute(candCompile.request, {
6181
- apiKeys: args.opts.apiKeys,
6182
- fetchImpl: args.opts.fetchImpl,
6183
- providerOverrides: args.opts.providerOverrides
6181
+ apiKeys: args.exec.apiKeys,
6182
+ fetchImpl: args.exec.fetchImpl,
6183
+ providerOverrides: args.exec.providerOverrides
6184
6184
  });
6185
6185
  const candidateLatencyMs = Date.now() - candStart;
6186
6186
  if (!exec.ok) continue;
@@ -6209,6 +6209,54 @@ async function runShadowProbe(args) {
6209
6209
  } catch {
6210
6210
  }
6211
6211
  }
6212
+ async function runShadowProbe(args) {
6213
+ const cfg = args.opts.shadowProbe;
6214
+ if (!cfg) return;
6215
+ await runProbeCandidates({
6216
+ ir: args.ir,
6217
+ cfg,
6218
+ servedModel: args.servedModel,
6219
+ servedResponse: args.servedResponse,
6220
+ servedLatencyMs: args.servedLatencyMs,
6221
+ // CallOptions is a structural superset of ProbeExecOpts.
6222
+ exec: args.opts
6223
+ });
6224
+ }
6225
+ async function probeShadow(ir, opts) {
6226
+ try {
6227
+ const servedResponse = {
6228
+ text: opts.served.responseText,
6229
+ structuredOutput: null,
6230
+ toolCalls: [],
6231
+ tokens: {
6232
+ input: opts.served.tokensIn,
6233
+ output: opts.served.tokensOut,
6234
+ total: opts.served.tokensIn + opts.served.tokensOut
6235
+ },
6236
+ raw: null
6237
+ };
6238
+ await runProbeCandidates({
6239
+ ir,
6240
+ cfg: {
6241
+ candidates: opts.candidates,
6242
+ sampleRate: opts.sampleRate,
6243
+ judge: opts.judge ?? "off"
6244
+ },
6245
+ servedModel: opts.served.model,
6246
+ servedResponse,
6247
+ servedLatencyMs: opts.served.latencyMs,
6248
+ exec: {
6249
+ policy: opts.policy,
6250
+ toolRelevanceThreshold: opts.toolRelevanceThreshold,
6251
+ compressHistoryAfter: opts.compressHistoryAfter,
6252
+ apiKeys: opts.apiKeys,
6253
+ fetchImpl: opts.fetchImpl,
6254
+ providerOverrides: opts.providerOverrides
6255
+ }
6256
+ });
6257
+ } catch {
6258
+ }
6259
+ }
6212
6260
  function validateStructuredContract(exec, ir) {
6213
6261
  if (!ir.constraints?.structuredOutput) {
6214
6262
  return { ok: true, response: exec.response };
@@ -6795,6 +6843,7 @@ function compile2(ir, opts) {
6795
6843
  markAdvisoryResolved,
6796
6844
  markExclusionFindingHandled,
6797
6845
  markPromoteReadyHandled,
6846
+ probeShadow,
6798
6847
  profileToRow,
6799
6848
  profilesByProvider,
6800
6849
  readBrainReadEnv,
package/dist/index.mjs CHANGED
@@ -3768,16 +3768,15 @@ function hashForProbe(s) {
3768
3768
  for (let i = 0; i < s.length; i++) h = (h << 5) - h + s.charCodeAt(i) | 0;
3769
3769
  return `h${(h >>> 0).toString(16)}`;
3770
3770
  }
3771
- async function runShadowProbe(args) {
3771
+ async function runProbeCandidates(args) {
3772
3772
  try {
3773
- const cfg = args.opts.shadowProbe;
3774
- if (!shouldSampleProbe(cfg.sampleRate ?? 0.05)) return;
3775
- const candidates = normalizeProbeCandidates(cfg.candidates);
3773
+ if (!shouldSampleProbe(args.cfg.sampleRate ?? 0.05)) return;
3774
+ const candidates = normalizeProbeCandidates(args.cfg.candidates);
3776
3775
  const promptHash = hashForProbe(args.ir.currentTurn?.content ?? "");
3777
3776
  for (const candidate of candidates) {
3778
3777
  if (candidate === args.servedModel) continue;
3779
3778
  if (deriveFamilyFromModelId(candidate) === "claude-opus") continue;
3780
- if (!isModelReachable(candidate, { apiKeys: args.opts.apiKeys })) continue;
3779
+ if (!isModelReachable(candidate, { apiKeys: args.exec.apiKeys })) continue;
3781
3780
  try {
3782
3781
  const candCompile = compileAndRegister(
3783
3782
  {
@@ -3785,13 +3784,13 @@ async function runShadowProbe(args) {
3785
3784
  models: args.ir.models.includes(candidate) ? args.ir.models : [candidate, ...args.ir.models],
3786
3785
  constraints: { ...args.ir.constraints ?? {}, forceModel: candidate }
3787
3786
  },
3788
- args.opts
3787
+ args.exec
3789
3788
  );
3790
3789
  const candStart = Date.now();
3791
3790
  const exec = await execute(candCompile.request, {
3792
- apiKeys: args.opts.apiKeys,
3793
- fetchImpl: args.opts.fetchImpl,
3794
- providerOverrides: args.opts.providerOverrides
3791
+ apiKeys: args.exec.apiKeys,
3792
+ fetchImpl: args.exec.fetchImpl,
3793
+ providerOverrides: args.exec.providerOverrides
3795
3794
  });
3796
3795
  const candidateLatencyMs = Date.now() - candStart;
3797
3796
  if (!exec.ok) continue;
@@ -3820,6 +3819,54 @@ async function runShadowProbe(args) {
3820
3819
  } catch {
3821
3820
  }
3822
3821
  }
3822
+ async function runShadowProbe(args) {
3823
+ const cfg = args.opts.shadowProbe;
3824
+ if (!cfg) return;
3825
+ await runProbeCandidates({
3826
+ ir: args.ir,
3827
+ cfg,
3828
+ servedModel: args.servedModel,
3829
+ servedResponse: args.servedResponse,
3830
+ servedLatencyMs: args.servedLatencyMs,
3831
+ // CallOptions is a structural superset of ProbeExecOpts.
3832
+ exec: args.opts
3833
+ });
3834
+ }
3835
+ async function probeShadow(ir, opts) {
3836
+ try {
3837
+ const servedResponse = {
3838
+ text: opts.served.responseText,
3839
+ structuredOutput: null,
3840
+ toolCalls: [],
3841
+ tokens: {
3842
+ input: opts.served.tokensIn,
3843
+ output: opts.served.tokensOut,
3844
+ total: opts.served.tokensIn + opts.served.tokensOut
3845
+ },
3846
+ raw: null
3847
+ };
3848
+ await runProbeCandidates({
3849
+ ir,
3850
+ cfg: {
3851
+ candidates: opts.candidates,
3852
+ sampleRate: opts.sampleRate,
3853
+ judge: opts.judge ?? "off"
3854
+ },
3855
+ servedModel: opts.served.model,
3856
+ servedResponse,
3857
+ servedLatencyMs: opts.served.latencyMs,
3858
+ exec: {
3859
+ policy: opts.policy,
3860
+ toolRelevanceThreshold: opts.toolRelevanceThreshold,
3861
+ compressHistoryAfter: opts.compressHistoryAfter,
3862
+ apiKeys: opts.apiKeys,
3863
+ fetchImpl: opts.fetchImpl,
3864
+ providerOverrides: opts.providerOverrides
3865
+ }
3866
+ });
3867
+ } catch {
3868
+ }
3869
+ }
3823
3870
  function validateStructuredContract(exec, ir) {
3824
3871
  if (!ir.constraints?.structuredOutput) {
3825
3872
  return { ok: true, response: exec.response };
@@ -4405,6 +4452,7 @@ export {
4405
4452
  markAdvisoryResolved,
4406
4453
  markExclusionFindingHandled,
4407
4454
  markPromoteReadyHandled,
4455
+ probeShadow,
4408
4456
  profileToRow,
4409
4457
  profilesByProvider,
4410
4458
  readBrainReadEnv,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warmdrift/kgauto-compiler",
3
- "version": "2.0.0-alpha.47",
3
+ "version": "2.0.0-alpha.48",
4
4
  "description": "Prompt compiler + central learning brain for multi-model AI apps. Swap models without rewriting prompts.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",