@warmdrift/kgauto-compiler 2.0.0-alpha.51 → 2.0.0-alpha.52

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.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, B as BestPracticeAdvisory, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-dDcG8Pvu.mjs';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-dDcG8Pvu.mjs';
2
2
  export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, r as MutationApplied, s as NormalizedTokens, t as OutcomeKind, u as PerAxisMetricsByModel, v as PromptSection, w as SectionKind, x as ShadowProbeConfig, T as ToolCall, y as ToolDefinition } from './ir-dDcG8Pvu.mjs';
3
3
  import { ModelProfile, ArchetypeConvention } from './profiles.mjs';
4
4
  export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.mjs';
@@ -250,6 +250,100 @@ interface AttachCacheControlResult {
250
250
  */
251
251
  declare function attachCacheControlToStreamTextInput(result: CompileResult, convertedMessages: AISDKConvertedMessage[]): AttachCacheControlResult;
252
252
 
253
+ /**
254
+ * alpha.52 — official AI-SDK-v6 compile adapter + compile-then-discard guard.
255
+ *
256
+ * Until now each AI-SDK consumer (tt-intel, IC) hand-rolled this adapter in
257
+ * its own `lib/kgauto-v2/index.ts`: `compile()` → reassemble the system param
258
+ * per provider → extract kept tool names per provider → re-derive the history
259
+ * cache-mark index (a copy of the compiler's own `historyCacheMarkIndex`
260
+ * logic — drift-prone). This centralizes that boilerplate and DRYs the two
261
+ * near-identical wrappers.
262
+ *
263
+ * It also closes the compile-then-discard hole. The discard pattern is:
264
+ *
265
+ * const c = compileForAISDKv6(ir); // compile runs
266
+ * const out = await generateText({ // …but a hand-built prompt
267
+ * model: getModel(otherId), prompt }); // + a DIFFERENT model run
268
+ * await record({ handle: c.handle, … }); // brain row attributed to `c`
269
+ *
270
+ * The recorded row's `mutations_applied` / `estimated_tokens_in` /
271
+ * `system_prompt_chars` then describe a compile that never reached the wire.
272
+ * A library-level runtime guard could NOT catch this while the adapter lived
273
+ * in consumer code (the consumer wrapper always reads `compile()`'s result to
274
+ * build its own object, so any getter there is "consumed" every time,
275
+ * regardless of whether the final caller used the wrapper output). With the
276
+ * adapter IN the library, the object the FINAL caller reads is library-owned,
277
+ * so consume-tracking getters on `.system` / `.model` / `.raw` detect non-use
278
+ * and `record()` warns. See `interfaces/kgauto.md` (## Requested:
279
+ * `compiled-output-discarded-guard`).
280
+ *
281
+ * The guard is OPT-IN-BY-USE: only `compileForAISDKv6` arms tracking, so
282
+ * `call()` paths and raw `compile()` users never see a false warning.
283
+ */
284
+
285
+ interface CompileForAISDKv6Result {
286
+ /**
287
+ * Pass to `streamText`/`generateText({ model })` — the caller maps this id
288
+ * to an AI-SDK `LanguageModel`. Reading this marks the compile "consumed"
289
+ * (silences the compile-then-discard guard).
290
+ */
291
+ readonly model: string;
292
+ /**
293
+ * System parameter for `streamText`/`generateText({ system })`. Returns the
294
+ * structured `SystemModelMessage[]` form when the target is Anthropic AND a
295
+ * cacheable section exists (preserves the cache_control marker across the
296
+ * wire); a flat concatenated string otherwise. Reading this marks
297
+ * "consumed". (Same rule as `attachCacheControlToStreamTextInput`.)
298
+ */
299
+ readonly system: string | SystemModelMessage[];
300
+ /**
301
+ * The raw kgauto `CompileResult` — for `attachCacheControlToStreamTextInput(raw, msgs)`
302
+ * and `probeShadow(raw.ir-equivalent, …)` paths. Reading this marks
303
+ * "consumed" (it means you're using the compile output via the raw result).
304
+ */
305
+ readonly raw: CompileResult;
306
+ /** Tool names that survived budget + relevance — filter your SDK tool map to these. */
307
+ keptToolNames: Set<string>;
308
+ /** providerOptions for `streamText` — Anthropic cache_control on the cacheable prefix. Undefined otherwise. */
309
+ providerOptions?: {
310
+ anthropic?: {
311
+ cacheControl?: {
312
+ type: 'ephemeral';
313
+ };
314
+ };
315
+ };
316
+ /**
317
+ * Index (into post-strip history) for the Anthropic history cache marker
318
+ * (alpha.33). Mirror of `result.diagnostics.historyCacheMarkIndex` — no
319
+ * consumer re-derivation needed. Undefined when no marker fires.
320
+ */
321
+ historyCacheMarkIndex?: number;
322
+ /** Compile handle — pass to `record()` after the call. */
323
+ handle: string;
324
+ /** Mutation ids the compiler fired (informational). */
325
+ mutationsApplied: string[];
326
+ /** Best-practice advisories (alpha.6). Empty when none fired. */
327
+ advisories: BestPracticeAdvisory[];
328
+ /** Compiler diagnostics + the three commonly-logged top-level fields. */
329
+ diagnostics: CompileResult['diagnostics'] & {
330
+ targetProvider: string;
331
+ estimatedCostUsd: number;
332
+ fallbackChain: string[];
333
+ };
334
+ /** The compiled IR — pass to `probeShadow(ir, …)` in `onFinish` (alpha.48). */
335
+ ir: PromptIR;
336
+ }
337
+ /**
338
+ * Compile a `PromptIR` and lower it to an AI-SDK-v6 `streamText`/`generateText`
339
+ * bundle. Replaces the hand-rolled per-consumer adapter.
340
+ *
341
+ * Arms the compile-then-discard guard: read `.system` / `.model` / `.raw` to
342
+ * serve the call. If you `record()` the handle without reading any of them,
343
+ * `record()` emits a dev-mode warning that the compile was discarded.
344
+ */
345
+ declare function compileForAISDKv6(ir: PromptIR, opts?: CompileOptions): CompileForAISDKv6Result;
346
+
253
347
  /**
254
348
  * alpha.11 — opt-in nested config for brain-query mode (chains / archetype
255
349
  * perf / pricing / models registry). Enabled by default when endpoint is
@@ -304,16 +398,21 @@ interface BrainConfig {
304
398
  /** alpha.11 — brain-query mode for config tables. Default-on per table
305
399
  * when endpoint is set; opt-out via `false`. See BrainQueryConfig. */
306
400
  brainQuery?: BrainQueryConfig;
401
+ /**
402
+ * alpha.52 — emit a dev-mode `console.warn` when a `compileForAISDKv6()`
403
+ * result is passed to record() but its `.system` / `.model` / `.raw` were
404
+ * never read (the compile-then-discard pattern: the recorded brain row's
405
+ * `mutations_applied` / `estimated_tokens_in` / `system_prompt_chars`
406
+ * describe a compile that did NOT shape the served call). Default: warn
407
+ * when `NODE_ENV !== 'production'`, silent in production. Set `true` to
408
+ * force-on (e.g. a prod audit window) or `false` to silence. No-op for
409
+ * `call()` paths and raw `compile()` users — only `compileForAISDKv6`
410
+ * arms the tracking, so good actors never see a false warning.
411
+ */
412
+ warnOnDiscardedCompile?: boolean;
307
413
  }
308
414
  declare function configureBrain(config: BrainConfig): void;
309
415
  declare function clearBrain(): void;
310
- /**
311
- * Record the outcome of a compiled call. Fire-and-forget by default.
312
- *
313
- * Returns a Promise so callers in `sync` mode can await; in async mode the
314
- * promise resolves immediately (after the request is queued) and any
315
- * network error is swallowed/forwarded to onError.
316
- */
317
416
  declare function record(input: RecordInput): Promise<void>;
318
417
  /**
319
418
  * Wire shape POSTed by `record()` to the brain proxy's `/outcomes` endpoint.
@@ -2272,4 +2371,4 @@ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions):
2272
2371
  */
2273
2372
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2274
2373
 
2275
- 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 };
2374
+ 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 CompileForAISDKv6Result, 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, compileForAISDKv6, 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
@@ -1,4 +1,4 @@
1
- import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, B as BestPracticeAdvisory, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-rUUojj0s.js';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, S as SystemModelMessage, e as CompileResult, B as BestPracticeAdvisory, f as SectionRewrite, R as RecordInput, g as RecordOutcomeInput, O as OutcomeResult, h as OracleScore, i as Adapter, j as PerAxisMetrics, k as Provider, l as ChainEntry, G as Grounding } from './ir-rUUojj0s.js';
2
2
  export { m as CallAttempt, n as CallError, o as ChainModelEntry, p as ChainWithGrounding, q as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, r as MutationApplied, s as NormalizedTokens, t as OutcomeKind, u as PerAxisMetricsByModel, v as PromptSection, w as SectionKind, x as ShadowProbeConfig, T as ToolCall, y as ToolDefinition } from './ir-rUUojj0s.js';
3
3
  import { ModelProfile, ArchetypeConvention } from './profiles.js';
4
4
  export { ALIASES, CacheStrategy, CliffRule, LATENCY_TIER_MS, LatencyTier, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, latencyTierOf, profilesByProvider, tryGetProfile } from './profiles.js';
@@ -250,6 +250,100 @@ interface AttachCacheControlResult {
250
250
  */
251
251
  declare function attachCacheControlToStreamTextInput(result: CompileResult, convertedMessages: AISDKConvertedMessage[]): AttachCacheControlResult;
252
252
 
253
+ /**
254
+ * alpha.52 — official AI-SDK-v6 compile adapter + compile-then-discard guard.
255
+ *
256
+ * Until now each AI-SDK consumer (tt-intel, IC) hand-rolled this adapter in
257
+ * its own `lib/kgauto-v2/index.ts`: `compile()` → reassemble the system param
258
+ * per provider → extract kept tool names per provider → re-derive the history
259
+ * cache-mark index (a copy of the compiler's own `historyCacheMarkIndex`
260
+ * logic — drift-prone). This centralizes that boilerplate and DRYs the two
261
+ * near-identical wrappers.
262
+ *
263
+ * It also closes the compile-then-discard hole. The discard pattern is:
264
+ *
265
+ * const c = compileForAISDKv6(ir); // compile runs
266
+ * const out = await generateText({ // …but a hand-built prompt
267
+ * model: getModel(otherId), prompt }); // + a DIFFERENT model run
268
+ * await record({ handle: c.handle, … }); // brain row attributed to `c`
269
+ *
270
+ * The recorded row's `mutations_applied` / `estimated_tokens_in` /
271
+ * `system_prompt_chars` then describe a compile that never reached the wire.
272
+ * A library-level runtime guard could NOT catch this while the adapter lived
273
+ * in consumer code (the consumer wrapper always reads `compile()`'s result to
274
+ * build its own object, so any getter there is "consumed" every time,
275
+ * regardless of whether the final caller used the wrapper output). With the
276
+ * adapter IN the library, the object the FINAL caller reads is library-owned,
277
+ * so consume-tracking getters on `.system` / `.model` / `.raw` detect non-use
278
+ * and `record()` warns. See `interfaces/kgauto.md` (## Requested:
279
+ * `compiled-output-discarded-guard`).
280
+ *
281
+ * The guard is OPT-IN-BY-USE: only `compileForAISDKv6` arms tracking, so
282
+ * `call()` paths and raw `compile()` users never see a false warning.
283
+ */
284
+
285
+ interface CompileForAISDKv6Result {
286
+ /**
287
+ * Pass to `streamText`/`generateText({ model })` — the caller maps this id
288
+ * to an AI-SDK `LanguageModel`. Reading this marks the compile "consumed"
289
+ * (silences the compile-then-discard guard).
290
+ */
291
+ readonly model: string;
292
+ /**
293
+ * System parameter for `streamText`/`generateText({ system })`. Returns the
294
+ * structured `SystemModelMessage[]` form when the target is Anthropic AND a
295
+ * cacheable section exists (preserves the cache_control marker across the
296
+ * wire); a flat concatenated string otherwise. Reading this marks
297
+ * "consumed". (Same rule as `attachCacheControlToStreamTextInput`.)
298
+ */
299
+ readonly system: string | SystemModelMessage[];
300
+ /**
301
+ * The raw kgauto `CompileResult` — for `attachCacheControlToStreamTextInput(raw, msgs)`
302
+ * and `probeShadow(raw.ir-equivalent, …)` paths. Reading this marks
303
+ * "consumed" (it means you're using the compile output via the raw result).
304
+ */
305
+ readonly raw: CompileResult;
306
+ /** Tool names that survived budget + relevance — filter your SDK tool map to these. */
307
+ keptToolNames: Set<string>;
308
+ /** providerOptions for `streamText` — Anthropic cache_control on the cacheable prefix. Undefined otherwise. */
309
+ providerOptions?: {
310
+ anthropic?: {
311
+ cacheControl?: {
312
+ type: 'ephemeral';
313
+ };
314
+ };
315
+ };
316
+ /**
317
+ * Index (into post-strip history) for the Anthropic history cache marker
318
+ * (alpha.33). Mirror of `result.diagnostics.historyCacheMarkIndex` — no
319
+ * consumer re-derivation needed. Undefined when no marker fires.
320
+ */
321
+ historyCacheMarkIndex?: number;
322
+ /** Compile handle — pass to `record()` after the call. */
323
+ handle: string;
324
+ /** Mutation ids the compiler fired (informational). */
325
+ mutationsApplied: string[];
326
+ /** Best-practice advisories (alpha.6). Empty when none fired. */
327
+ advisories: BestPracticeAdvisory[];
328
+ /** Compiler diagnostics + the three commonly-logged top-level fields. */
329
+ diagnostics: CompileResult['diagnostics'] & {
330
+ targetProvider: string;
331
+ estimatedCostUsd: number;
332
+ fallbackChain: string[];
333
+ };
334
+ /** The compiled IR — pass to `probeShadow(ir, …)` in `onFinish` (alpha.48). */
335
+ ir: PromptIR;
336
+ }
337
+ /**
338
+ * Compile a `PromptIR` and lower it to an AI-SDK-v6 `streamText`/`generateText`
339
+ * bundle. Replaces the hand-rolled per-consumer adapter.
340
+ *
341
+ * Arms the compile-then-discard guard: read `.system` / `.model` / `.raw` to
342
+ * serve the call. If you `record()` the handle without reading any of them,
343
+ * `record()` emits a dev-mode warning that the compile was discarded.
344
+ */
345
+ declare function compileForAISDKv6(ir: PromptIR, opts?: CompileOptions): CompileForAISDKv6Result;
346
+
253
347
  /**
254
348
  * alpha.11 — opt-in nested config for brain-query mode (chains / archetype
255
349
  * perf / pricing / models registry). Enabled by default when endpoint is
@@ -304,16 +398,21 @@ interface BrainConfig {
304
398
  /** alpha.11 — brain-query mode for config tables. Default-on per table
305
399
  * when endpoint is set; opt-out via `false`. See BrainQueryConfig. */
306
400
  brainQuery?: BrainQueryConfig;
401
+ /**
402
+ * alpha.52 — emit a dev-mode `console.warn` when a `compileForAISDKv6()`
403
+ * result is passed to record() but its `.system` / `.model` / `.raw` were
404
+ * never read (the compile-then-discard pattern: the recorded brain row's
405
+ * `mutations_applied` / `estimated_tokens_in` / `system_prompt_chars`
406
+ * describe a compile that did NOT shape the served call). Default: warn
407
+ * when `NODE_ENV !== 'production'`, silent in production. Set `true` to
408
+ * force-on (e.g. a prod audit window) or `false` to silence. No-op for
409
+ * `call()` paths and raw `compile()` users — only `compileForAISDKv6`
410
+ * arms the tracking, so good actors never see a false warning.
411
+ */
412
+ warnOnDiscardedCompile?: boolean;
307
413
  }
308
414
  declare function configureBrain(config: BrainConfig): void;
309
415
  declare function clearBrain(): void;
310
- /**
311
- * Record the outcome of a compiled call. Fire-and-forget by default.
312
- *
313
- * Returns a Promise so callers in `sync` mode can await; in async mode the
314
- * promise resolves immediately (after the request is queued) and any
315
- * network error is swallowed/forwarded to onError.
316
- */
317
416
  declare function record(input: RecordInput): Promise<void>;
318
417
  /**
319
418
  * Wire shape POSTed by `record()` to the brain proxy's `/outcomes` endpoint.
@@ -2272,4 +2371,4 @@ declare function markPromoteReadyHandled(opts: MarkPromoteReadyHandledOptions):
2272
2371
  */
2273
2372
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
2274
2373
 
2275
- 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 };
2374
+ 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 CompileForAISDKv6Result, 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, compileForAISDKv6, 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
@@ -48,6 +48,7 @@ __export(index_exports, {
48
48
  call: () => call,
49
49
  clearBrain: () => clearBrain,
50
50
  compile: () => compile2,
51
+ compileForAISDKv6: () => compileForAISDKv6,
51
52
  configureBrain: () => configureBrain,
52
53
  countTokens: () => countTokens,
53
54
  deriveFamilyFromModelId: () => deriveFamilyFromModelId,
@@ -4464,9 +4465,37 @@ function estimateSystemPromptChars(sections) {
4464
4465
  }
4465
4466
  return total > 0 ? total : void 0;
4466
4467
  }
4468
+ function armCompileConsumeTracking(handle) {
4469
+ const reg = compileRegistry.get(handle);
4470
+ if (!reg) return;
4471
+ reg.consumeTracked = true;
4472
+ reg.systemConsumed = false;
4473
+ reg.modelConsumed = false;
4474
+ reg.rawConsumed = false;
4475
+ }
4476
+ function markCompileConsumed(handle, field) {
4477
+ const reg = compileRegistry.get(handle);
4478
+ if (!reg || !reg.consumeTracked) return;
4479
+ if (field === "system") reg.systemConsumed = true;
4480
+ else if (field === "model") reg.modelConsumed = true;
4481
+ else reg.rawConsumed = true;
4482
+ }
4483
+ function maybeWarnDiscardedCompile(reg, handle) {
4484
+ if (!reg.consumeTracked) return;
4485
+ if (reg.systemConsumed || reg.modelConsumed || reg.rawConsumed) return;
4486
+ const isProd = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
4487
+ const enabled = activeConfig?.warnOnDiscardedCompile ?? !isProd;
4488
+ if (!enabled) return;
4489
+ console.warn(
4490
+ `[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 }).`
4491
+ );
4492
+ }
4467
4493
  async function record(input) {
4468
4494
  const reg = compileRegistry.get(input.handle);
4469
- if (reg) compileRegistry.delete(input.handle);
4495
+ if (reg) {
4496
+ maybeWarnDiscardedCompile(reg, input.handle);
4497
+ compileRegistry.delete(input.handle);
4498
+ }
4470
4499
  if (!activeConfig) {
4471
4500
  return;
4472
4501
  }
@@ -6579,6 +6608,71 @@ function attachCacheControlToStreamTextInput(result, convertedMessages) {
6579
6608
  return { system, messages };
6580
6609
  }
6581
6610
 
6611
+ // src/compile-aisdk.ts
6612
+ function compileForAISDKv6(ir, opts) {
6613
+ const result = compile(ir, opts);
6614
+ registerCompile(ir.appId, ir.intent.archetype, ir, result);
6615
+ armCompileConsumeTracking(result.handle);
6616
+ const systemMessages = result.systemMessages;
6617
+ const hasStructuredSystemCacheControl = result.provider === "anthropic" && systemMessages.some(
6618
+ (m) => m.providerOptions?.anthropic?.cacheControl !== void 0
6619
+ );
6620
+ const systemValue = hasStructuredSystemCacheControl ? systemMessages : systemMessages.map((m) => m.content).join("\n\n");
6621
+ const keptToolNames = extractKeptToolNames(result);
6622
+ const providerOptions = result.provider === "anthropic" && result.diagnostics.cacheableTokens > 0 ? { anthropic: { cacheControl: { type: "ephemeral" } } } : void 0;
6623
+ const handle = result.handle;
6624
+ const diagnostics = {
6625
+ ...result.diagnostics,
6626
+ targetProvider: result.provider,
6627
+ estimatedCostUsd: result.estimatedCostUsd,
6628
+ fallbackChain: result.fallbackChain
6629
+ };
6630
+ return {
6631
+ handle,
6632
+ // Consume-tracking getters: reading any of these flags the compile as
6633
+ // "used", silencing the discard guard at record() time.
6634
+ get model() {
6635
+ markCompileConsumed(handle, "model");
6636
+ return result.target;
6637
+ },
6638
+ get system() {
6639
+ markCompileConsumed(handle, "system");
6640
+ return systemValue;
6641
+ },
6642
+ get raw() {
6643
+ markCompileConsumed(handle, "raw");
6644
+ return result;
6645
+ },
6646
+ keptToolNames,
6647
+ ...providerOptions ? { providerOptions } : {},
6648
+ ...result.diagnostics.historyCacheMarkIndex !== void 0 ? { historyCacheMarkIndex: result.diagnostics.historyCacheMarkIndex } : {},
6649
+ mutationsApplied: result.mutationsApplied.map((m) => m.id),
6650
+ advisories: result.advisories ?? [],
6651
+ diagnostics,
6652
+ ir
6653
+ };
6654
+ }
6655
+ function extractKeptToolNames(result) {
6656
+ const names = /* @__PURE__ */ new Set();
6657
+ const tools = result.request.tools;
6658
+ if (!Array.isArray(tools)) return names;
6659
+ if (result.provider === "google") {
6660
+ for (const td of tools) {
6661
+ for (const fn of td.functionDeclarations ?? []) if (fn.name) names.add(fn.name);
6662
+ }
6663
+ } else if (result.provider === "openai") {
6664
+ for (const t of tools) {
6665
+ const n = t.function?.name;
6666
+ if (n) names.add(n);
6667
+ }
6668
+ } else {
6669
+ for (const t of tools) {
6670
+ if (t.name) names.add(t.name);
6671
+ }
6672
+ }
6673
+ return names;
6674
+ }
6675
+
6582
6676
  // src/oracle.ts
6583
6677
  var DEFAULT_DIMENSIONS = ["correctness", "completeness", "conciseness", "format"];
6584
6678
  var judgeCallTimes = [];
@@ -7035,6 +7129,7 @@ function compile2(ir, opts) {
7035
7129
  call,
7036
7130
  clearBrain,
7037
7131
  compile,
7132
+ compileForAISDKv6,
7038
7133
  configureBrain,
7039
7134
  countTokens,
7040
7135
  deriveFamilyFromModelId,
package/dist/index.mjs CHANGED
@@ -2676,9 +2676,37 @@ function estimateSystemPromptChars(sections) {
2676
2676
  }
2677
2677
  return total > 0 ? total : void 0;
2678
2678
  }
2679
+ function armCompileConsumeTracking(handle) {
2680
+ const reg = compileRegistry.get(handle);
2681
+ if (!reg) return;
2682
+ reg.consumeTracked = true;
2683
+ reg.systemConsumed = false;
2684
+ reg.modelConsumed = false;
2685
+ reg.rawConsumed = false;
2686
+ }
2687
+ function markCompileConsumed(handle, field) {
2688
+ const reg = compileRegistry.get(handle);
2689
+ if (!reg || !reg.consumeTracked) return;
2690
+ if (field === "system") reg.systemConsumed = true;
2691
+ else if (field === "model") reg.modelConsumed = true;
2692
+ else reg.rawConsumed = true;
2693
+ }
2694
+ function maybeWarnDiscardedCompile(reg, handle) {
2695
+ if (!reg.consumeTracked) return;
2696
+ if (reg.systemConsumed || reg.modelConsumed || reg.rawConsumed) return;
2697
+ const isProd = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
2698
+ const enabled = activeConfig?.warnOnDiscardedCompile ?? !isProd;
2699
+ if (!enabled) return;
2700
+ console.warn(
2701
+ `[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 }).`
2702
+ );
2703
+ }
2679
2704
  async function record(input) {
2680
2705
  const reg = compileRegistry.get(input.handle);
2681
- if (reg) compileRegistry.delete(input.handle);
2706
+ if (reg) {
2707
+ maybeWarnDiscardedCompile(reg, input.handle);
2708
+ compileRegistry.delete(input.handle);
2709
+ }
2682
2710
  if (!activeConfig) {
2683
2711
  return;
2684
2712
  }
@@ -4076,6 +4104,71 @@ function attachCacheControlToStreamTextInput(result, convertedMessages) {
4076
4104
  return { system, messages };
4077
4105
  }
4078
4106
 
4107
+ // src/compile-aisdk.ts
4108
+ function compileForAISDKv6(ir, opts) {
4109
+ const result = compile(ir, opts);
4110
+ registerCompile(ir.appId, ir.intent.archetype, ir, result);
4111
+ armCompileConsumeTracking(result.handle);
4112
+ const systemMessages = result.systemMessages;
4113
+ const hasStructuredSystemCacheControl = result.provider === "anthropic" && systemMessages.some(
4114
+ (m) => m.providerOptions?.anthropic?.cacheControl !== void 0
4115
+ );
4116
+ const systemValue = hasStructuredSystemCacheControl ? systemMessages : systemMessages.map((m) => m.content).join("\n\n");
4117
+ const keptToolNames = extractKeptToolNames(result);
4118
+ const providerOptions = result.provider === "anthropic" && result.diagnostics.cacheableTokens > 0 ? { anthropic: { cacheControl: { type: "ephemeral" } } } : void 0;
4119
+ const handle = result.handle;
4120
+ const diagnostics = {
4121
+ ...result.diagnostics,
4122
+ targetProvider: result.provider,
4123
+ estimatedCostUsd: result.estimatedCostUsd,
4124
+ fallbackChain: result.fallbackChain
4125
+ };
4126
+ return {
4127
+ handle,
4128
+ // Consume-tracking getters: reading any of these flags the compile as
4129
+ // "used", silencing the discard guard at record() time.
4130
+ get model() {
4131
+ markCompileConsumed(handle, "model");
4132
+ return result.target;
4133
+ },
4134
+ get system() {
4135
+ markCompileConsumed(handle, "system");
4136
+ return systemValue;
4137
+ },
4138
+ get raw() {
4139
+ markCompileConsumed(handle, "raw");
4140
+ return result;
4141
+ },
4142
+ keptToolNames,
4143
+ ...providerOptions ? { providerOptions } : {},
4144
+ ...result.diagnostics.historyCacheMarkIndex !== void 0 ? { historyCacheMarkIndex: result.diagnostics.historyCacheMarkIndex } : {},
4145
+ mutationsApplied: result.mutationsApplied.map((m) => m.id),
4146
+ advisories: result.advisories ?? [],
4147
+ diagnostics,
4148
+ ir
4149
+ };
4150
+ }
4151
+ function extractKeptToolNames(result) {
4152
+ const names = /* @__PURE__ */ new Set();
4153
+ const tools = result.request.tools;
4154
+ if (!Array.isArray(tools)) return names;
4155
+ if (result.provider === "google") {
4156
+ for (const td of tools) {
4157
+ for (const fn of td.functionDeclarations ?? []) if (fn.name) names.add(fn.name);
4158
+ }
4159
+ } else if (result.provider === "openai") {
4160
+ for (const t of tools) {
4161
+ const n = t.function?.name;
4162
+ if (n) names.add(n);
4163
+ }
4164
+ } else {
4165
+ for (const t of tools) {
4166
+ if (t.name) names.add(t.name);
4167
+ }
4168
+ }
4169
+ return names;
4170
+ }
4171
+
4079
4172
  // src/oracle.ts
4080
4173
  var DEFAULT_DIMENSIONS = ["correctness", "completeness", "conciseness", "format"];
4081
4174
  var judgeCallTimes = [];
@@ -4531,6 +4624,7 @@ export {
4531
4624
  call,
4532
4625
  clearBrain,
4533
4626
  compile2 as compile,
4627
+ compileForAISDKv6,
4534
4628
  configureBrain,
4535
4629
  countTokens,
4536
4630
  deriveFamilyFromModelId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warmdrift/kgauto-compiler",
3
- "version": "2.0.0-alpha.51",
3
+ "version": "2.0.0-alpha.52",
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",