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

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.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,
@@ -1634,6 +1635,63 @@ var PROFILES_RAW = [
1634
1635
  critique: 5
1635
1636
  // +1 vs 2.5-flash — but still below Sonnet/Opus reasoning floor
1636
1637
  }
1638
+ },
1639
+ {
1640
+ // Auto-onboarded 2026-07-01 from `claude-sonnet-4-6`; VERIFIED 2026-07-02
1641
+ // against the claude-api reference (cc-portfolio ratification pass). The
1642
+ // clone got context right (1M) and pricing right at sticker ($3/$15 —
1643
+ // NOTE an introductory $2/$10 per MTok runs through 2026-08-31; sticker
1644
+ // encoded here per the time-bounded-pricing convention, intro belongs in
1645
+ // brain kgauto_pricing if worth capturing). The clone got max output WRONG:
1646
+ // Sonnet 5 is 128k, not 4-6's 64k — corrected. New tokenizer (~30% more
1647
+ // tokens for the same text vs 4-6): byte-budget consumers should re-baseline.
1648
+ // API quirks (claude-api ref): (a) NON-DEFAULT temperature/top_p/top_k
1649
+ // return 400 — moot for kgauto's own call() path (ANTHROPIC_LOWERING_BASE
1650
+ // emits no sampling params) but a REAL hazard for compileForAISDKv6
1651
+ // consumers that pass temperature themselves (tt-intel scoring uses temp:0
1652
+ // for determinism — that 400s on this model; noted to consumers via the
1653
+ // contract). (b) Omitting `thinking` runs ADAPTIVE by default (4-6 ran
1654
+ // thinking-off) — output spend shifts. (c) Supports effort xhigh. status:
1655
+ // 'preview' per the Fable precedent — no brain evidence yet; promotion to
1656
+ // 'current' is an explicit call. (L-049/L-081.)
1657
+ id: "claude-sonnet-5",
1658
+ verifiedAgainstDocs: "2026-07-02",
1659
+ provider: "anthropic",
1660
+ status: "preview",
1661
+ maxContextTokens: 1e6,
1662
+ maxOutputTokens: 128e3,
1663
+ maxTools: 64,
1664
+ parallelToolCalls: true,
1665
+ structuredOutput: "grammar",
1666
+ systemPromptMode: "inline",
1667
+ streaming: true,
1668
+ cliffs: [],
1669
+ costInputPer1m: 3,
1670
+ costOutputPer1m: 15,
1671
+ lowering: ANTHROPIC_LOWERING_BASE,
1672
+ recovery: [
1673
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" },
1674
+ { signal: "model_not_found", action: "escalate", reason: "Deprecated \u2014 escalate (L-061)" }
1675
+ ],
1676
+ strengths: ["quality", "tool_use", "long_context", "cache_friendly", "extended_thinking"],
1677
+ weaknesses: [],
1678
+ notes: "Sonnet 5 (2026-06): near-Opus quality on coding/agentic work at Sonnet cost. Verified 2026-07-02 against the claude-api reference: 1M ctx, 128k out (clone's 64k corrected), $3/$15 sticker (intro $2/$10 through 2026-08-31). New tokenizer ~30% more tokens vs sonnet-4-6. Consumer hazards: non-default temperature/top_p/top_k 400 (temp:0 rejected \u2014 deterministic-scoring consumers must omit); thinking defaults to adaptive when omitted. status:preview \u2014 no brain evidence yet; earns placement via the machinery.",
1679
+ // Master plan §6.2 anchor. Tier 0 for plan/generate/ask/extract/transform
1680
+ // in starter chains; tier 1 cross-provider for hunt/summarize/classify.
1681
+ archetypePerf: {
1682
+ ask: 9,
1683
+ generate: 9,
1684
+ plan: 9,
1685
+ critique: 9,
1686
+ extract: 9,
1687
+ transform: 9,
1688
+ hunt: 7,
1689
+ // strong but Flash beats on parallel tool throughput
1690
+ summarize: 8,
1691
+ // overkill for tolerant archetype
1692
+ classify: 8
1693
+ // overkill
1694
+ }
1637
1695
  }
1638
1696
  ];
1639
1697
  var ALIASES = {
@@ -4464,9 +4522,37 @@ function estimateSystemPromptChars(sections) {
4464
4522
  }
4465
4523
  return total > 0 ? total : void 0;
4466
4524
  }
4525
+ function armCompileConsumeTracking(handle) {
4526
+ const reg = compileRegistry.get(handle);
4527
+ if (!reg) return;
4528
+ reg.consumeTracked = true;
4529
+ reg.systemConsumed = false;
4530
+ reg.modelConsumed = false;
4531
+ reg.rawConsumed = false;
4532
+ }
4533
+ function markCompileConsumed(handle, field) {
4534
+ const reg = compileRegistry.get(handle);
4535
+ if (!reg || !reg.consumeTracked) return;
4536
+ if (field === "system") reg.systemConsumed = true;
4537
+ else if (field === "model") reg.modelConsumed = true;
4538
+ else reg.rawConsumed = true;
4539
+ }
4540
+ function maybeWarnDiscardedCompile(reg, handle) {
4541
+ if (!reg.consumeTracked) return;
4542
+ if (reg.systemConsumed || reg.modelConsumed || reg.rawConsumed) return;
4543
+ const isProd = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
4544
+ const enabled = activeConfig?.warnOnDiscardedCompile ?? !isProd;
4545
+ if (!enabled) return;
4546
+ console.warn(
4547
+ `[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 }).`
4548
+ );
4549
+ }
4467
4550
  async function record(input) {
4468
4551
  const reg = compileRegistry.get(input.handle);
4469
- if (reg) compileRegistry.delete(input.handle);
4552
+ if (reg) {
4553
+ maybeWarnDiscardedCompile(reg, input.handle);
4554
+ compileRegistry.delete(input.handle);
4555
+ }
4470
4556
  if (!activeConfig) {
4471
4557
  return;
4472
4558
  }
@@ -4496,7 +4582,7 @@ async function record(input) {
4496
4582
  });
4497
4583
  if (!res.ok) {
4498
4584
  const text = await res.text().catch(() => "<no body>");
4499
- throw new Error(`brain ${res.status}: ${text}`);
4585
+ throw new Error(describeBrainWriteFailure(res.status, "outcomes", text));
4500
4586
  }
4501
4587
  outcomeId = await tryExtractOutcomeId(res);
4502
4588
  } catch (err) {
@@ -4534,6 +4620,11 @@ async function record(input) {
4534
4620
  function defaultOnError5(err) {
4535
4621
  console.warn("[kgauto] brain record failed:", err);
4536
4622
  }
4623
+ function describeBrainWriteFailure(status, route, body) {
4624
+ const base = `brain ${route} ${status}: ${body}`;
4625
+ if (status !== 404 && status !== 405) return base;
4626
+ return `${base} \u2014 likely cause: the brain proxy at your KGAUTO_V2_BRAIN_URL is missing the /${route} forward route. Self-proxying consumers must implement ALL THREE sibling routes (/outcomes, /probe_outcomes, /compile_outcome_quality) \u2014 see interfaces/kgauto.md "Consumer adoption checklist" route-completeness (L-142).`;
4627
+ }
4537
4628
  function buildPayload(input, reg) {
4538
4629
  const compileTarget = reg?.model;
4539
4630
  const actual = input.actualModel ?? compileTarget;
@@ -4662,7 +4753,9 @@ async function recordOutcome(input) {
4662
4753
  });
4663
4754
  if (!res.ok) {
4664
4755
  const text = await res.text().catch(() => "<no body>");
4665
- const err = new Error(`brain ${res.status}: ${text}`);
4756
+ const err = new Error(
4757
+ describeBrainWriteFailure(res.status, "compile_outcome_quality", text)
4758
+ );
4666
4759
  (config.onError ?? defaultOnError5)(err);
4667
4760
  return { ok: false, reason: "persistence_failed" };
4668
4761
  }
@@ -4704,8 +4797,12 @@ function buildShadowProbeRow(input) {
4704
4797
  prompt_fidelity: 1,
4705
4798
  replay_source: "inline-full-ir",
4706
4799
  // alpha — migration 029. 'completed' is the default completed-probe shape;
4707
- // diagnostic rows (aborted/skipped) pass the explicit class.
4708
- outcome: input.outcome ?? "completed"
4800
+ // diagnostic rows (aborted/skipped/errored) pass the explicit class.
4801
+ outcome: input.outcome ?? "completed",
4802
+ // alpha.53 — migration 032. Populated only on candidate_error rows.
4803
+ // Self-proxying consumers must whitelist `error_class` (and `outcome`,
4804
+ // per the alpha.51 PB finding) or diagnostic rows degrade silently.
4805
+ error_class: input.errorClass ?? null
4709
4806
  };
4710
4807
  }
4711
4808
  async function recordShadowProbe(input) {
@@ -4726,7 +4823,7 @@ async function recordShadowProbe(input) {
4726
4823
  });
4727
4824
  if (!res.ok) {
4728
4825
  const text = await res.text().catch(() => "<no body>");
4729
- throw new Error(`brain probe_outcomes ${res.status}: ${text}`);
4826
+ throw new Error(describeBrainWriteFailure(res.status, "probe_outcomes", text));
4730
4827
  }
4731
4828
  } catch (err) {
4732
4829
  (config.onError ?? defaultOnError5)(err);
@@ -6331,7 +6428,7 @@ async function runProbeCandidates(args) {
6331
6428
  const budgetMs = args.cfg.maxLatencyMs ?? DEFAULT_PROBE_MAX_LATENCY_MS;
6332
6429
  const deadline = args.sync ? Date.now() + budgetMs : Number.POSITIVE_INFINITY;
6333
6430
  const skipSlow = args.sync && (args.cfg.skipSlowTierInSync ?? true);
6334
- const recordDiagnostic = async (candidate, outcome) => {
6431
+ const recordDiagnostic = async (candidate, outcome, detail) => {
6335
6432
  await recordShadowProbe({
6336
6433
  appId: args.ir.appId,
6337
6434
  archetype: args.ir.intent.archetype,
@@ -6344,7 +6441,9 @@ async function runProbeCandidates(args) {
6344
6441
  tokensCurrentIn: args.servedResponse.tokens.input,
6345
6442
  tokensCurrentOut: args.servedResponse.tokens.output,
6346
6443
  latencyCurrentMs: args.servedLatencyMs,
6347
- outcome
6444
+ outcome,
6445
+ ...detail?.errorClass ? { errorClass: detail.errorClass } : {},
6446
+ ...detail?.latencyCandidateMs !== void 0 ? { latencyCandidateMs: detail.latencyCandidateMs } : {}
6348
6447
  });
6349
6448
  };
6350
6449
  for (const candidate of candidates) {
@@ -6399,10 +6498,28 @@ async function runProbeCandidates(args) {
6399
6498
  }
6400
6499
  break;
6401
6500
  }
6402
- if (raced.kind === "failed") continue;
6501
+ if (raced.kind === "failed") {
6502
+ try {
6503
+ await recordDiagnostic(candidate, "candidate_error", {
6504
+ errorClass: "execute_rejected",
6505
+ latencyCandidateMs: Date.now() - candStart
6506
+ });
6507
+ } catch {
6508
+ }
6509
+ continue;
6510
+ }
6403
6511
  const exec = raced.exec;
6404
6512
  const candidateLatencyMs = Date.now() - candStart;
6405
- if (!exec.ok) continue;
6513
+ if (!exec.ok) {
6514
+ try {
6515
+ await recordDiagnostic(candidate, "candidate_error", {
6516
+ errorClass: exec.errorCode,
6517
+ latencyCandidateMs: candidateLatencyMs
6518
+ });
6519
+ } catch {
6520
+ }
6521
+ continue;
6522
+ }
6406
6523
  await recordShadowProbe({
6407
6524
  appId: args.ir.appId,
6408
6525
  archetype: args.ir.intent.archetype,
@@ -6579,6 +6696,71 @@ function attachCacheControlToStreamTextInput(result, convertedMessages) {
6579
6696
  return { system, messages };
6580
6697
  }
6581
6698
 
6699
+ // src/compile-aisdk.ts
6700
+ function compileForAISDKv6(ir, opts) {
6701
+ const result = compile(ir, opts);
6702
+ registerCompile(ir.appId, ir.intent.archetype, ir, result);
6703
+ armCompileConsumeTracking(result.handle);
6704
+ const systemMessages = result.systemMessages;
6705
+ const hasStructuredSystemCacheControl = result.provider === "anthropic" && systemMessages.some(
6706
+ (m) => m.providerOptions?.anthropic?.cacheControl !== void 0
6707
+ );
6708
+ const systemValue = hasStructuredSystemCacheControl ? systemMessages : systemMessages.map((m) => m.content).join("\n\n");
6709
+ const keptToolNames = extractKeptToolNames(result);
6710
+ const providerOptions = result.provider === "anthropic" && result.diagnostics.cacheableTokens > 0 ? { anthropic: { cacheControl: { type: "ephemeral" } } } : void 0;
6711
+ const handle = result.handle;
6712
+ const diagnostics = {
6713
+ ...result.diagnostics,
6714
+ targetProvider: result.provider,
6715
+ estimatedCostUsd: result.estimatedCostUsd,
6716
+ fallbackChain: result.fallbackChain
6717
+ };
6718
+ return {
6719
+ handle,
6720
+ // Consume-tracking getters: reading any of these flags the compile as
6721
+ // "used", silencing the discard guard at record() time.
6722
+ get model() {
6723
+ markCompileConsumed(handle, "model");
6724
+ return result.target;
6725
+ },
6726
+ get system() {
6727
+ markCompileConsumed(handle, "system");
6728
+ return systemValue;
6729
+ },
6730
+ get raw() {
6731
+ markCompileConsumed(handle, "raw");
6732
+ return result;
6733
+ },
6734
+ keptToolNames,
6735
+ ...providerOptions ? { providerOptions } : {},
6736
+ ...result.diagnostics.historyCacheMarkIndex !== void 0 ? { historyCacheMarkIndex: result.diagnostics.historyCacheMarkIndex } : {},
6737
+ mutationsApplied: result.mutationsApplied.map((m) => m.id),
6738
+ advisories: result.advisories ?? [],
6739
+ diagnostics,
6740
+ ir
6741
+ };
6742
+ }
6743
+ function extractKeptToolNames(result) {
6744
+ const names = /* @__PURE__ */ new Set();
6745
+ const tools = result.request.tools;
6746
+ if (!Array.isArray(tools)) return names;
6747
+ if (result.provider === "google") {
6748
+ for (const td of tools) {
6749
+ for (const fn of td.functionDeclarations ?? []) if (fn.name) names.add(fn.name);
6750
+ }
6751
+ } else if (result.provider === "openai") {
6752
+ for (const t of tools) {
6753
+ const n = t.function?.name;
6754
+ if (n) names.add(n);
6755
+ }
6756
+ } else {
6757
+ for (const t of tools) {
6758
+ if (t.name) names.add(t.name);
6759
+ }
6760
+ }
6761
+ return names;
6762
+ }
6763
+
6582
6764
  // src/oracle.ts
6583
6765
  var DEFAULT_DIMENSIONS = ["correctness", "completeness", "conciseness", "format"];
6584
6766
  var judgeCallTimes = [];
@@ -7035,6 +7217,7 @@ function compile2(ir, opts) {
7035
7217
  call,
7036
7218
  clearBrain,
7037
7219
  compile,
7220
+ compileForAISDKv6,
7038
7221
  configureBrain,
7039
7222
  countTokens,
7040
7223
  deriveFamilyFromModelId,
package/dist/index.mjs CHANGED
@@ -33,7 +33,7 @@ import {
33
33
  loadChainsFromBrain,
34
34
  readBrainReadEnv,
35
35
  resolveProviderKey
36
- } from "./chunk-HHWBB46W.mjs";
36
+ } from "./chunk-IIMPJZNH.mjs";
37
37
  import {
38
38
  ALIASES,
39
39
  LATENCY_TIER_MS,
@@ -44,7 +44,7 @@ import {
44
44
  latencyTierOf,
45
45
  profilesByProvider,
46
46
  tryGetProfile
47
- } from "./chunk-CXH7KC4D.mjs";
47
+ } from "./chunk-QKXTMVCT.mjs";
48
48
  import {
49
49
  emitAdvisoryFired,
50
50
  emitCompileDone,
@@ -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
  }
@@ -2708,7 +2736,7 @@ async function record(input) {
2708
2736
  });
2709
2737
  if (!res.ok) {
2710
2738
  const text = await res.text().catch(() => "<no body>");
2711
- throw new Error(`brain ${res.status}: ${text}`);
2739
+ throw new Error(describeBrainWriteFailure(res.status, "outcomes", text));
2712
2740
  }
2713
2741
  outcomeId = await tryExtractOutcomeId(res);
2714
2742
  } catch (err) {
@@ -2746,6 +2774,11 @@ async function record(input) {
2746
2774
  function defaultOnError4(err) {
2747
2775
  console.warn("[kgauto] brain record failed:", err);
2748
2776
  }
2777
+ function describeBrainWriteFailure(status, route, body) {
2778
+ const base = `brain ${route} ${status}: ${body}`;
2779
+ if (status !== 404 && status !== 405) return base;
2780
+ return `${base} \u2014 likely cause: the brain proxy at your KGAUTO_V2_BRAIN_URL is missing the /${route} forward route. Self-proxying consumers must implement ALL THREE sibling routes (/outcomes, /probe_outcomes, /compile_outcome_quality) \u2014 see interfaces/kgauto.md "Consumer adoption checklist" route-completeness (L-142).`;
2781
+ }
2749
2782
  function buildPayload(input, reg) {
2750
2783
  const compileTarget = reg?.model;
2751
2784
  const actual = input.actualModel ?? compileTarget;
@@ -2874,7 +2907,9 @@ async function recordOutcome(input) {
2874
2907
  });
2875
2908
  if (!res.ok) {
2876
2909
  const text = await res.text().catch(() => "<no body>");
2877
- const err = new Error(`brain ${res.status}: ${text}`);
2910
+ const err = new Error(
2911
+ describeBrainWriteFailure(res.status, "compile_outcome_quality", text)
2912
+ );
2878
2913
  (config.onError ?? defaultOnError4)(err);
2879
2914
  return { ok: false, reason: "persistence_failed" };
2880
2915
  }
@@ -2916,8 +2951,12 @@ function buildShadowProbeRow(input) {
2916
2951
  prompt_fidelity: 1,
2917
2952
  replay_source: "inline-full-ir",
2918
2953
  // alpha — migration 029. 'completed' is the default completed-probe shape;
2919
- // diagnostic rows (aborted/skipped) pass the explicit class.
2920
- outcome: input.outcome ?? "completed"
2954
+ // diagnostic rows (aborted/skipped/errored) pass the explicit class.
2955
+ outcome: input.outcome ?? "completed",
2956
+ // alpha.53 — migration 032. Populated only on candidate_error rows.
2957
+ // Self-proxying consumers must whitelist `error_class` (and `outcome`,
2958
+ // per the alpha.51 PB finding) or diagnostic rows degrade silently.
2959
+ error_class: input.errorClass ?? null
2921
2960
  };
2922
2961
  }
2923
2962
  async function recordShadowProbe(input) {
@@ -2938,7 +2977,7 @@ async function recordShadowProbe(input) {
2938
2977
  });
2939
2978
  if (!res.ok) {
2940
2979
  const text = await res.text().catch(() => "<no body>");
2941
- throw new Error(`brain probe_outcomes ${res.status}: ${text}`);
2980
+ throw new Error(describeBrainWriteFailure(res.status, "probe_outcomes", text));
2942
2981
  }
2943
2982
  } catch (err) {
2944
2983
  (config.onError ?? defaultOnError4)(err);
@@ -3828,7 +3867,7 @@ async function runProbeCandidates(args) {
3828
3867
  const budgetMs = args.cfg.maxLatencyMs ?? DEFAULT_PROBE_MAX_LATENCY_MS;
3829
3868
  const deadline = args.sync ? Date.now() + budgetMs : Number.POSITIVE_INFINITY;
3830
3869
  const skipSlow = args.sync && (args.cfg.skipSlowTierInSync ?? true);
3831
- const recordDiagnostic = async (candidate, outcome) => {
3870
+ const recordDiagnostic = async (candidate, outcome, detail) => {
3832
3871
  await recordShadowProbe({
3833
3872
  appId: args.ir.appId,
3834
3873
  archetype: args.ir.intent.archetype,
@@ -3841,7 +3880,9 @@ async function runProbeCandidates(args) {
3841
3880
  tokensCurrentIn: args.servedResponse.tokens.input,
3842
3881
  tokensCurrentOut: args.servedResponse.tokens.output,
3843
3882
  latencyCurrentMs: args.servedLatencyMs,
3844
- outcome
3883
+ outcome,
3884
+ ...detail?.errorClass ? { errorClass: detail.errorClass } : {},
3885
+ ...detail?.latencyCandidateMs !== void 0 ? { latencyCandidateMs: detail.latencyCandidateMs } : {}
3845
3886
  });
3846
3887
  };
3847
3888
  for (const candidate of candidates) {
@@ -3896,10 +3937,28 @@ async function runProbeCandidates(args) {
3896
3937
  }
3897
3938
  break;
3898
3939
  }
3899
- if (raced.kind === "failed") continue;
3940
+ if (raced.kind === "failed") {
3941
+ try {
3942
+ await recordDiagnostic(candidate, "candidate_error", {
3943
+ errorClass: "execute_rejected",
3944
+ latencyCandidateMs: Date.now() - candStart
3945
+ });
3946
+ } catch {
3947
+ }
3948
+ continue;
3949
+ }
3900
3950
  const exec = raced.exec;
3901
3951
  const candidateLatencyMs = Date.now() - candStart;
3902
- if (!exec.ok) continue;
3952
+ if (!exec.ok) {
3953
+ try {
3954
+ await recordDiagnostic(candidate, "candidate_error", {
3955
+ errorClass: exec.errorCode,
3956
+ latencyCandidateMs: candidateLatencyMs
3957
+ });
3958
+ } catch {
3959
+ }
3960
+ continue;
3961
+ }
3903
3962
  await recordShadowProbe({
3904
3963
  appId: args.ir.appId,
3905
3964
  archetype: args.ir.intent.archetype,
@@ -4076,6 +4135,71 @@ function attachCacheControlToStreamTextInput(result, convertedMessages) {
4076
4135
  return { system, messages };
4077
4136
  }
4078
4137
 
4138
+ // src/compile-aisdk.ts
4139
+ function compileForAISDKv6(ir, opts) {
4140
+ const result = compile(ir, opts);
4141
+ registerCompile(ir.appId, ir.intent.archetype, ir, result);
4142
+ armCompileConsumeTracking(result.handle);
4143
+ const systemMessages = result.systemMessages;
4144
+ const hasStructuredSystemCacheControl = result.provider === "anthropic" && systemMessages.some(
4145
+ (m) => m.providerOptions?.anthropic?.cacheControl !== void 0
4146
+ );
4147
+ const systemValue = hasStructuredSystemCacheControl ? systemMessages : systemMessages.map((m) => m.content).join("\n\n");
4148
+ const keptToolNames = extractKeptToolNames(result);
4149
+ const providerOptions = result.provider === "anthropic" && result.diagnostics.cacheableTokens > 0 ? { anthropic: { cacheControl: { type: "ephemeral" } } } : void 0;
4150
+ const handle = result.handle;
4151
+ const diagnostics = {
4152
+ ...result.diagnostics,
4153
+ targetProvider: result.provider,
4154
+ estimatedCostUsd: result.estimatedCostUsd,
4155
+ fallbackChain: result.fallbackChain
4156
+ };
4157
+ return {
4158
+ handle,
4159
+ // Consume-tracking getters: reading any of these flags the compile as
4160
+ // "used", silencing the discard guard at record() time.
4161
+ get model() {
4162
+ markCompileConsumed(handle, "model");
4163
+ return result.target;
4164
+ },
4165
+ get system() {
4166
+ markCompileConsumed(handle, "system");
4167
+ return systemValue;
4168
+ },
4169
+ get raw() {
4170
+ markCompileConsumed(handle, "raw");
4171
+ return result;
4172
+ },
4173
+ keptToolNames,
4174
+ ...providerOptions ? { providerOptions } : {},
4175
+ ...result.diagnostics.historyCacheMarkIndex !== void 0 ? { historyCacheMarkIndex: result.diagnostics.historyCacheMarkIndex } : {},
4176
+ mutationsApplied: result.mutationsApplied.map((m) => m.id),
4177
+ advisories: result.advisories ?? [],
4178
+ diagnostics,
4179
+ ir
4180
+ };
4181
+ }
4182
+ function extractKeptToolNames(result) {
4183
+ const names = /* @__PURE__ */ new Set();
4184
+ const tools = result.request.tools;
4185
+ if (!Array.isArray(tools)) return names;
4186
+ if (result.provider === "google") {
4187
+ for (const td of tools) {
4188
+ for (const fn of td.functionDeclarations ?? []) if (fn.name) names.add(fn.name);
4189
+ }
4190
+ } else if (result.provider === "openai") {
4191
+ for (const t of tools) {
4192
+ const n = t.function?.name;
4193
+ if (n) names.add(n);
4194
+ }
4195
+ } else {
4196
+ for (const t of tools) {
4197
+ if (t.name) names.add(t.name);
4198
+ }
4199
+ }
4200
+ return names;
4201
+ }
4202
+
4079
4203
  // src/oracle.ts
4080
4204
  var DEFAULT_DIMENSIONS = ["correctness", "completeness", "conciseness", "format"];
4081
4205
  var judgeCallTimes = [];
@@ -4531,6 +4655,7 @@ export {
4531
4655
  call,
4532
4656
  clearBrain,
4533
4657
  compile2 as compile,
4658
+ compileForAISDKv6,
4534
4659
  configureBrain,
4535
4660
  countTokens,
4536
4661
  deriveFamilyFromModelId,
@@ -1216,7 +1216,16 @@ type OutcomeKind = 'approved' | 'rejected' | 'partial' | 'engaged' | 'abandoned'
1216
1216
  * outcomes accumulate.
1217
1217
  */
1218
1218
  interface RecordOutcomeInput {
1219
- /** Joins to compile_outcomes.id. Returned by compile() via CompileResult.outcomeId. */
1219
+ /**
1220
+ * Joins to compile_outcomes.id. Pass the compile `handle` string
1221
+ * (CompileResult.handle / CallResult.handle) — consumer proxies resolve
1222
+ * handle → compile_outcomes.id via the `compile_outcomes.handle` column
1223
+ * (reference implementations: PB `api/kgauto-v2/compile_outcome_quality.js`,
1224
+ * tt-intel/IC `app/api/kgauto/v2/compile_outcome_quality/route.ts`). A
1225
+ * numeric compile_outcomes.id also works if the caller already has it.
1226
+ * (There is no `CompileResult.outcomeId` field — the brain assigns the row
1227
+ * id at insert; `handle` is the consumer-visible correlator.)
1228
+ */
1220
1229
  outcomeId: number | string;
1221
1230
  /** What did the user / system do with this output? */
1222
1231
  outcome: OutcomeKind;
@@ -1216,7 +1216,16 @@ type OutcomeKind = 'approved' | 'rejected' | 'partial' | 'engaged' | 'abandoned'
1216
1216
  * outcomes accumulate.
1217
1217
  */
1218
1218
  interface RecordOutcomeInput {
1219
- /** Joins to compile_outcomes.id. Returned by compile() via CompileResult.outcomeId. */
1219
+ /**
1220
+ * Joins to compile_outcomes.id. Pass the compile `handle` string
1221
+ * (CompileResult.handle / CallResult.handle) — consumer proxies resolve
1222
+ * handle → compile_outcomes.id via the `compile_outcomes.handle` column
1223
+ * (reference implementations: PB `api/kgauto-v2/compile_outcome_quality.js`,
1224
+ * tt-intel/IC `app/api/kgauto/v2/compile_outcome_quality/route.ts`). A
1225
+ * numeric compile_outcomes.id also works if the caller already has it.
1226
+ * (There is no `CompileResult.outcomeId` field — the brain assigns the row
1227
+ * id at insert; `handle` is the consumer-visible correlator.)
1228
+ */
1220
1229
  outcomeId: number | string;
1221
1230
  /** What did the user / system do with this output? */
1222
1231
  outcome: OutcomeKind;
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-dDcG8Pvu.mjs';
1
+ import { k as Provider } from './ir-CAlLBu5d.mjs';
2
2
  import { IntentArchetypeName } from './dialect.mjs';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { k as Provider } from './ir-rUUojj0s.js';
1
+ import { k as Provider } from './ir-BiXAMyji.js';
2
2
  import { IntentArchetypeName } from './dialect.js';
3
3
 
4
4
  /**
package/dist/profiles.js CHANGED
@@ -1388,6 +1388,63 @@ var PROFILES_RAW = [
1388
1388
  critique: 5
1389
1389
  // +1 vs 2.5-flash — but still below Sonnet/Opus reasoning floor
1390
1390
  }
1391
+ },
1392
+ {
1393
+ // Auto-onboarded 2026-07-01 from `claude-sonnet-4-6`; VERIFIED 2026-07-02
1394
+ // against the claude-api reference (cc-portfolio ratification pass). The
1395
+ // clone got context right (1M) and pricing right at sticker ($3/$15 —
1396
+ // NOTE an introductory $2/$10 per MTok runs through 2026-08-31; sticker
1397
+ // encoded here per the time-bounded-pricing convention, intro belongs in
1398
+ // brain kgauto_pricing if worth capturing). The clone got max output WRONG:
1399
+ // Sonnet 5 is 128k, not 4-6's 64k — corrected. New tokenizer (~30% more
1400
+ // tokens for the same text vs 4-6): byte-budget consumers should re-baseline.
1401
+ // API quirks (claude-api ref): (a) NON-DEFAULT temperature/top_p/top_k
1402
+ // return 400 — moot for kgauto's own call() path (ANTHROPIC_LOWERING_BASE
1403
+ // emits no sampling params) but a REAL hazard for compileForAISDKv6
1404
+ // consumers that pass temperature themselves (tt-intel scoring uses temp:0
1405
+ // for determinism — that 400s on this model; noted to consumers via the
1406
+ // contract). (b) Omitting `thinking` runs ADAPTIVE by default (4-6 ran
1407
+ // thinking-off) — output spend shifts. (c) Supports effort xhigh. status:
1408
+ // 'preview' per the Fable precedent — no brain evidence yet; promotion to
1409
+ // 'current' is an explicit call. (L-049/L-081.)
1410
+ id: "claude-sonnet-5",
1411
+ verifiedAgainstDocs: "2026-07-02",
1412
+ provider: "anthropic",
1413
+ status: "preview",
1414
+ maxContextTokens: 1e6,
1415
+ maxOutputTokens: 128e3,
1416
+ maxTools: 64,
1417
+ parallelToolCalls: true,
1418
+ structuredOutput: "grammar",
1419
+ systemPromptMode: "inline",
1420
+ streaming: true,
1421
+ cliffs: [],
1422
+ costInputPer1m: 3,
1423
+ costOutputPer1m: 15,
1424
+ lowering: ANTHROPIC_LOWERING_BASE,
1425
+ recovery: [
1426
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" },
1427
+ { signal: "model_not_found", action: "escalate", reason: "Deprecated \u2014 escalate (L-061)" }
1428
+ ],
1429
+ strengths: ["quality", "tool_use", "long_context", "cache_friendly", "extended_thinking"],
1430
+ weaknesses: [],
1431
+ notes: "Sonnet 5 (2026-06): near-Opus quality on coding/agentic work at Sonnet cost. Verified 2026-07-02 against the claude-api reference: 1M ctx, 128k out (clone's 64k corrected), $3/$15 sticker (intro $2/$10 through 2026-08-31). New tokenizer ~30% more tokens vs sonnet-4-6. Consumer hazards: non-default temperature/top_p/top_k 400 (temp:0 rejected \u2014 deterministic-scoring consumers must omit); thinking defaults to adaptive when omitted. status:preview \u2014 no brain evidence yet; earns placement via the machinery.",
1432
+ // Master plan §6.2 anchor. Tier 0 for plan/generate/ask/extract/transform
1433
+ // in starter chains; tier 1 cross-provider for hunt/summarize/classify.
1434
+ archetypePerf: {
1435
+ ask: 9,
1436
+ generate: 9,
1437
+ plan: 9,
1438
+ critique: 9,
1439
+ extract: 9,
1440
+ transform: 9,
1441
+ hunt: 7,
1442
+ // strong but Flash beats on parallel tool throughput
1443
+ summarize: 8,
1444
+ // overkill for tolerant archetype
1445
+ classify: 8
1446
+ // overkill
1447
+ }
1391
1448
  }
1392
1449
  ];
1393
1450
  var ALIASES = {
package/dist/profiles.mjs CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  latencyTierOf,
9
9
  profilesByProvider,
10
10
  tryGetProfile
11
- } from "./chunk-CXH7KC4D.mjs";
11
+ } from "./chunk-QKXTMVCT.mjs";
12
12
  export {
13
13
  ALIASES,
14
14
  LATENCY_TIER_MS,
@@ -1,4 +1,4 @@
1
- import { r as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-dDcG8Pvu.mjs';
1
+ import { r as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-CAlLBu5d.mjs';
2
2
 
3
3
  /**
4
4
  * Glass-Box observability types (alpha.17).
@@ -1,4 +1,4 @@
1
- import { i as Adapter, w as SectionKind } from './ir-dDcG8Pvu.mjs';
1
+ import { i as Adapter, w as SectionKind } from './ir-CAlLBu5d.mjs';
2
2
 
3
3
  /**
4
4
  * Internal config + hook types for createGlassboxRoutes().