@warmdrift/kgauto-compiler 2.0.0-alpha.78 → 2.0.0-alpha.79

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.
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var LIBRARY_VERSION = "2.0.0-alpha.78";
2
+ var LIBRARY_VERSION = "2.0.0-alpha.79";
3
3
 
4
4
  // src/key-health.ts
5
5
  var JSON_HEADERS = { "Content-Type": "application/json" };
package/dist/index.d.mts CHANGED
@@ -1146,7 +1146,7 @@ declare function runStrategyEvalWithAttribution(opts: Omit<GoldenEvalOptions, 'a
1146
1146
  * guard in `tests/version.test.ts` fails the suite (and therefore
1147
1147
  * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
1148
1148
  */
1149
- declare const LIBRARY_VERSION = "2.0.0-alpha.78";
1149
+ declare const LIBRARY_VERSION = "2.0.0-alpha.79";
1150
1150
 
1151
1151
  /**
1152
1152
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -1250,6 +1250,155 @@ declare function resetTokenizer(): void;
1250
1250
  */
1251
1251
  declare function countTokens(text: string): number;
1252
1252
 
1253
+ /**
1254
+ * delegate — Release D, the R2 primitive (delegation-fanout accelerator §5.2,
1255
+ * design contract advisory/kgauto/2026-07-24_delegation-fanout-accelerator-design.md).
1256
+ *
1257
+ * A consumer-mountable TOOL the orchestrating model calls mid-loop:
1258
+ * `{ sub_archetype, input, quality_floor? }`. kgauto selects the executor
1259
+ * from evidence, runs the sub-call through the compiler + call(), returns
1260
+ * the result into the loop, links parent↔child rows (R0), and enforces
1261
+ * `policy.maxCostPerTraceUsd` against the running trace spend — the field
1262
+ * that shipped INERT in Release A precisely so this release could turn it on.
1263
+ *
1264
+ * THE AUTHORITY SPLIT IS THE CONTAINMENT (§3):
1265
+ * - the MODEL decides whether and what to delegate (kgauto never
1266
+ * decomposes uninvited — §10);
1267
+ * - KGAUTO decides only who runs it — and never selects a model absent
1268
+ * from the consumer's declared `ir.models`;
1269
+ * - the CONSUMER consents: default OFF, `KGAUTO_AUTO_PROMOTE` posture
1270
+ * (explicit option beats `KGAUTO_DELEGATE` env; neither ⇒ the handler
1271
+ * refuses observably, never silently).
1272
+ *
1273
+ * Budget refusals and floor refusals are RETURNED to the model as
1274
+ * structured tool results, never thrown — the orchestrator must be able to
1275
+ * compose with what it has (a refusal mid-loop that crashes the loop would
1276
+ * convert a budget into an outage).
1277
+ *
1278
+ * Composition-verification (§7a): every sub-result is 'trusted' until the
1279
+ * orchestrator/consumer reports otherwise via `reportComposition` —
1280
+ * absence-of-report IS the recorded state (migration 052). Rung 3 reads
1281
+ * this to attribute composition failures to stitching, not executor choice.
1282
+ *
1283
+ * Trace-budget honesty (v1 limits, stated where consumers read):
1284
+ * - the in-process ledger sums DELEGATED spend for this trace (parent's
1285
+ * own root-call spend is not visible to a library ledger until a
1286
+ * brain-informed ledger lands; documented on `maxCostPerTraceUsd`);
1287
+ * - enforcement is estimate-ahead: a sub-call whose compile-time estimate
1288
+ * would cross the ceiling is refused BEFORE any spend;
1289
+ * - realized spend is computed from actual tokens × the executor
1290
+ * profile's prices after each sub-call.
1291
+ */
1292
+
1293
+ declare function isDelegateEnabledFromEnv(envSource?: Record<string, string | undefined>): boolean;
1294
+ /** Arguments the ORCHESTRATING MODEL supplies when it calls the tool. */
1295
+ interface DelegateToolArgs {
1296
+ /** The sub-task's archetype — its own learning_key downstream. */
1297
+ sub_archetype: IntentArchetypeName | string;
1298
+ /** Complete, self-contained sub-task input. The model owns fidelity here
1299
+ * (authority split): kgauto runs exactly what it is handed. */
1300
+ input: string;
1301
+ /**
1302
+ * Minimum archetype-perf score (0..10) the executor must carry for this
1303
+ * sub-archetype. Candidates below the floor are excluded BEFORE ranking;
1304
+ * if nothing in the parent's declared pool clears it, the tool refuses
1305
+ * with the scores so the model can lower the floor or do the work itself.
1306
+ */
1307
+ quality_floor?: number;
1308
+ }
1309
+ type DelegateRefusalReason = 'delegate_not_enabled' | 'invalid_sub_archetype' | 'no_qualified_executor' | 'trace_budget_exhausted' | 'call_failed';
1310
+ type DelegateResult = {
1311
+ ok: true;
1312
+ /** The sub-result text (or serialized structured output). */
1313
+ output: string;
1314
+ /** Branch handle — pass to reportComposition; joins the brain row. */
1315
+ subHandle: string;
1316
+ executorModel: string;
1317
+ costUsd: number;
1318
+ latencyMs: number;
1319
+ /** Always 'trusted' at return time — flips only via reportComposition. */
1320
+ verification: 'trusted';
1321
+ } | {
1322
+ ok: false;
1323
+ reason: DelegateRefusalReason;
1324
+ /** Human/model-readable detail — written to be COMPOSABLE (“continue
1325
+ * without this sub-result”), never a stack trace. */
1326
+ detail: string;
1327
+ };
1328
+ /**
1329
+ * Provider-agnostic tool definition. Consumers adapt `inputSchema` to their
1330
+ * SDK's tool shape (AI-SDK `parameters`, Anthropic `input_schema`, …). The
1331
+ * description IS prompt surface — it teaches the model the authority split
1332
+ * and the compose-on-refusal discipline (gates 4/5 of discipline-gates-v1
1333
+ * in tool-description form).
1334
+ */
1335
+ declare const DELEGATE_TOOL_DEFINITION: {
1336
+ readonly name: "delegate";
1337
+ readonly description: string;
1338
+ readonly inputSchema: {
1339
+ readonly type: "object";
1340
+ readonly properties: {
1341
+ readonly sub_archetype: {
1342
+ readonly type: "string";
1343
+ readonly enum: ("ask" | "hunt" | "classify" | "summarize" | "generate" | "extract" | "plan" | "critique" | "transform" | "judge")[];
1344
+ readonly description: "What kind of work the sub-task is (its routing archetype).";
1345
+ };
1346
+ readonly input: {
1347
+ readonly type: "string";
1348
+ readonly description: "Complete, self-contained sub-task input. Include everything the executor needs — it sees nothing else.";
1349
+ };
1350
+ readonly quality_floor: {
1351
+ readonly type: "number";
1352
+ readonly minimum: 0;
1353
+ readonly maximum: 10;
1354
+ readonly description: "Optional minimum executor quality score (0-10) for this archetype. Omit to accept the evidence-ranked default.";
1355
+ };
1356
+ };
1357
+ readonly required: readonly ["sub_archetype", "input"];
1358
+ readonly additionalProperties: false;
1359
+ };
1360
+ };
1361
+ interface CreateDelegateOpts {
1362
+ /** The PARENT call's IR — supplies the declared model pool (the containment
1363
+ * boundary), appId, and dialect context. */
1364
+ parentIr: PromptIR;
1365
+ /** The parent's compile/call handle — R0 linkage root. Branch rows record
1366
+ * `parent_handle=<this>` and inherit `trace_id`. */
1367
+ parentHandle: string;
1368
+ /**
1369
+ * Options forwarded to the sub-`call()` (apiKeys, fetchImpl,
1370
+ * attemptTimeoutMs, policy…). `policy.maxCostPerTraceUsd` here is what the
1371
+ * ledger enforces. `parentHandle` is set by the factory — a value passed
1372
+ * in callOpts is overridden.
1373
+ */
1374
+ callOpts?: CallOptions & {
1375
+ policy?: CompilePolicy;
1376
+ };
1377
+ /** Explicit consent — beats KGAUTO_DELEGATE env (AUTO_PROMOTE posture). */
1378
+ enabled?: boolean;
1379
+ }
1380
+ interface DelegateHandle {
1381
+ toolDefinition: typeof DELEGATE_TOOL_DEFINITION;
1382
+ handler: (args: DelegateToolArgs) => Promise<DelegateResult>;
1383
+ /**
1384
+ * §7a — report what the orchestrator did with a sub-result. Writes a
1385
+ * migration-052 row via the brain-read env trio (RLS-scoped to appId).
1386
+ * Unreported sub-results are 'trusted' by definition — report only
1387
+ * 'verified' and 'discarded'.
1388
+ */
1389
+ reportComposition: (report: {
1390
+ subHandle: string;
1391
+ disposition: 'verified' | 'discarded';
1392
+ note?: string;
1393
+ }) => Promise<{
1394
+ ok: boolean;
1395
+ reason?: string;
1396
+ }>;
1397
+ /** Ledger introspection: delegated spend recorded for this trace so far. */
1398
+ traceSpendUsd: () => number;
1399
+ }
1400
+ declare function createDelegate(opts: CreateDelegateOpts): DelegateHandle;
1401
+
1253
1402
  /**
1254
1403
  * archetype-fits — alpha.43.
1255
1404
  *
@@ -3531,4 +3680,4 @@ declare function planDecomposition(args: PlanDecompositionArgs): DecompositionPl
3531
3680
  */
3532
3681
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
3533
3682
 
3534
- 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, BRAIN_READ_ENV_NAMES, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, COACH_CFG, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DECOMPOSITION_TEMPLATES, DECOMPOSITION_TEMPLATES_VERSION, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, DISCIPLINE_GATES_V1_ALT_HEADER, type DecompositionPlan, type DecompositionStep, type DecompositionTemplate, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type ExecutorCandidate, type FallbackPosture, FallbackReason, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalAxis, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenEvalStrategyId, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_FAILURE_CFG, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type MeasuredFailureRuntime, type MeasuredFailureVerdict, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PlannedStep, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, ROLLBACK_SUPPRESSION_WINDOW_DAYS, RULE_DISCIPLINE_GATES_V1, RULE_DISCIPLINE_GATES_V1_STRUCTURED, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, STRATEGY_AUTHORSHIP_LIMITATION, SectionRewrite, type ShadowProbeRecordInput, type StrategyAttribution, type StrategyAttributionResult, type StrategyOutcome, type SupportedProvider, type SurfaceFailureRow, type SurfaceStats, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, altGatesBlockFor, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, awaitMeasuredFailureReady, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, classifyStrategyOutcome, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configureMeasuredFailureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getMeasuredFailureVerdict, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecentRollback, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isMeasuredFailureBrainActive, isMeasuredFailureGateEnabledFromEnv, isModelReachable, isPromotionsBrainActive, isProviderReachable, judgeMeasuredFailure, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, mapMeasuredFailureRows, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, planDecomposition, prefetchMeasuredFailure, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, runStrategyEvalWithAttribution, setTokenizer, wilsonLowerBound, withAltDisciplineContract, withDisciplineContract };
3683
+ 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, BRAIN_READ_ENV_NAMES, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, COACH_CFG, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, type CreateDelegateOpts, DECOMPOSITION_TEMPLATES, DECOMPOSITION_TEMPLATES_VERSION, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, DELEGATE_TOOL_DEFINITION, DISCIPLINE_GATES_V1_ALT_HEADER, type DecompositionPlan, type DecompositionStep, type DecompositionTemplate, type DelegateHandle, type DelegateRefusalReason, type DelegateResult, type DelegateToolArgs, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type ExecutorCandidate, type FallbackPosture, FallbackReason, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalAxis, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenEvalStrategyId, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_FAILURE_CFG, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type MeasuredFailureRuntime, type MeasuredFailureVerdict, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PlannedStep, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, ROLLBACK_SUPPRESSION_WINDOW_DAYS, RULE_DISCIPLINE_GATES_V1, RULE_DISCIPLINE_GATES_V1_STRUCTURED, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, STRATEGY_AUTHORSHIP_LIMITATION, SectionRewrite, type ShadowProbeRecordInput, type StrategyAttribution, type StrategyAttributionResult, type StrategyOutcome, type SupportedProvider, type SurfaceFailureRow, type SurfaceStats, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, altGatesBlockFor, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, awaitMeasuredFailureReady, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, classifyStrategyOutcome, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configureMeasuredFailureBrain, configurePromotionsBrain, countTokens, createDelegate, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getMeasuredFailureVerdict, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecentRollback, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isDelegateEnabledFromEnv, isExclusionFindingsBrainActive, isMeasuredFailureBrainActive, isMeasuredFailureGateEnabledFromEnv, isModelReachable, isPromotionsBrainActive, isProviderReachable, judgeMeasuredFailure, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, mapMeasuredFailureRows, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, planDecomposition, prefetchMeasuredFailure, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, runStrategyEvalWithAttribution, setTokenizer, wilsonLowerBound, withAltDisciplineContract, withDisciplineContract };
package/dist/index.d.ts CHANGED
@@ -1146,7 +1146,7 @@ declare function runStrategyEvalWithAttribution(opts: Omit<GoldenEvalOptions, 'a
1146
1146
  * guard in `tests/version.test.ts` fails the suite (and therefore
1147
1147
  * `prepublishOnly`) when they diverge — a stale constant cannot reach npm.
1148
1148
  */
1149
- declare const LIBRARY_VERSION = "2.0.0-alpha.78";
1149
+ declare const LIBRARY_VERSION = "2.0.0-alpha.79";
1150
1150
 
1151
1151
  /**
1152
1152
  * Oracle contract — how an app tells the brain whether a response was good.
@@ -1250,6 +1250,155 @@ declare function resetTokenizer(): void;
1250
1250
  */
1251
1251
  declare function countTokens(text: string): number;
1252
1252
 
1253
+ /**
1254
+ * delegate — Release D, the R2 primitive (delegation-fanout accelerator §5.2,
1255
+ * design contract advisory/kgauto/2026-07-24_delegation-fanout-accelerator-design.md).
1256
+ *
1257
+ * A consumer-mountable TOOL the orchestrating model calls mid-loop:
1258
+ * `{ sub_archetype, input, quality_floor? }`. kgauto selects the executor
1259
+ * from evidence, runs the sub-call through the compiler + call(), returns
1260
+ * the result into the loop, links parent↔child rows (R0), and enforces
1261
+ * `policy.maxCostPerTraceUsd` against the running trace spend — the field
1262
+ * that shipped INERT in Release A precisely so this release could turn it on.
1263
+ *
1264
+ * THE AUTHORITY SPLIT IS THE CONTAINMENT (§3):
1265
+ * - the MODEL decides whether and what to delegate (kgauto never
1266
+ * decomposes uninvited — §10);
1267
+ * - KGAUTO decides only who runs it — and never selects a model absent
1268
+ * from the consumer's declared `ir.models`;
1269
+ * - the CONSUMER consents: default OFF, `KGAUTO_AUTO_PROMOTE` posture
1270
+ * (explicit option beats `KGAUTO_DELEGATE` env; neither ⇒ the handler
1271
+ * refuses observably, never silently).
1272
+ *
1273
+ * Budget refusals and floor refusals are RETURNED to the model as
1274
+ * structured tool results, never thrown — the orchestrator must be able to
1275
+ * compose with what it has (a refusal mid-loop that crashes the loop would
1276
+ * convert a budget into an outage).
1277
+ *
1278
+ * Composition-verification (§7a): every sub-result is 'trusted' until the
1279
+ * orchestrator/consumer reports otherwise via `reportComposition` —
1280
+ * absence-of-report IS the recorded state (migration 052). Rung 3 reads
1281
+ * this to attribute composition failures to stitching, not executor choice.
1282
+ *
1283
+ * Trace-budget honesty (v1 limits, stated where consumers read):
1284
+ * - the in-process ledger sums DELEGATED spend for this trace (parent's
1285
+ * own root-call spend is not visible to a library ledger until a
1286
+ * brain-informed ledger lands; documented on `maxCostPerTraceUsd`);
1287
+ * - enforcement is estimate-ahead: a sub-call whose compile-time estimate
1288
+ * would cross the ceiling is refused BEFORE any spend;
1289
+ * - realized spend is computed from actual tokens × the executor
1290
+ * profile's prices after each sub-call.
1291
+ */
1292
+
1293
+ declare function isDelegateEnabledFromEnv(envSource?: Record<string, string | undefined>): boolean;
1294
+ /** Arguments the ORCHESTRATING MODEL supplies when it calls the tool. */
1295
+ interface DelegateToolArgs {
1296
+ /** The sub-task's archetype — its own learning_key downstream. */
1297
+ sub_archetype: IntentArchetypeName | string;
1298
+ /** Complete, self-contained sub-task input. The model owns fidelity here
1299
+ * (authority split): kgauto runs exactly what it is handed. */
1300
+ input: string;
1301
+ /**
1302
+ * Minimum archetype-perf score (0..10) the executor must carry for this
1303
+ * sub-archetype. Candidates below the floor are excluded BEFORE ranking;
1304
+ * if nothing in the parent's declared pool clears it, the tool refuses
1305
+ * with the scores so the model can lower the floor or do the work itself.
1306
+ */
1307
+ quality_floor?: number;
1308
+ }
1309
+ type DelegateRefusalReason = 'delegate_not_enabled' | 'invalid_sub_archetype' | 'no_qualified_executor' | 'trace_budget_exhausted' | 'call_failed';
1310
+ type DelegateResult = {
1311
+ ok: true;
1312
+ /** The sub-result text (or serialized structured output). */
1313
+ output: string;
1314
+ /** Branch handle — pass to reportComposition; joins the brain row. */
1315
+ subHandle: string;
1316
+ executorModel: string;
1317
+ costUsd: number;
1318
+ latencyMs: number;
1319
+ /** Always 'trusted' at return time — flips only via reportComposition. */
1320
+ verification: 'trusted';
1321
+ } | {
1322
+ ok: false;
1323
+ reason: DelegateRefusalReason;
1324
+ /** Human/model-readable detail — written to be COMPOSABLE (“continue
1325
+ * without this sub-result”), never a stack trace. */
1326
+ detail: string;
1327
+ };
1328
+ /**
1329
+ * Provider-agnostic tool definition. Consumers adapt `inputSchema` to their
1330
+ * SDK's tool shape (AI-SDK `parameters`, Anthropic `input_schema`, …). The
1331
+ * description IS prompt surface — it teaches the model the authority split
1332
+ * and the compose-on-refusal discipline (gates 4/5 of discipline-gates-v1
1333
+ * in tool-description form).
1334
+ */
1335
+ declare const DELEGATE_TOOL_DEFINITION: {
1336
+ readonly name: "delegate";
1337
+ readonly description: string;
1338
+ readonly inputSchema: {
1339
+ readonly type: "object";
1340
+ readonly properties: {
1341
+ readonly sub_archetype: {
1342
+ readonly type: "string";
1343
+ readonly enum: ("ask" | "hunt" | "classify" | "summarize" | "generate" | "extract" | "plan" | "critique" | "transform" | "judge")[];
1344
+ readonly description: "What kind of work the sub-task is (its routing archetype).";
1345
+ };
1346
+ readonly input: {
1347
+ readonly type: "string";
1348
+ readonly description: "Complete, self-contained sub-task input. Include everything the executor needs — it sees nothing else.";
1349
+ };
1350
+ readonly quality_floor: {
1351
+ readonly type: "number";
1352
+ readonly minimum: 0;
1353
+ readonly maximum: 10;
1354
+ readonly description: "Optional minimum executor quality score (0-10) for this archetype. Omit to accept the evidence-ranked default.";
1355
+ };
1356
+ };
1357
+ readonly required: readonly ["sub_archetype", "input"];
1358
+ readonly additionalProperties: false;
1359
+ };
1360
+ };
1361
+ interface CreateDelegateOpts {
1362
+ /** The PARENT call's IR — supplies the declared model pool (the containment
1363
+ * boundary), appId, and dialect context. */
1364
+ parentIr: PromptIR;
1365
+ /** The parent's compile/call handle — R0 linkage root. Branch rows record
1366
+ * `parent_handle=<this>` and inherit `trace_id`. */
1367
+ parentHandle: string;
1368
+ /**
1369
+ * Options forwarded to the sub-`call()` (apiKeys, fetchImpl,
1370
+ * attemptTimeoutMs, policy…). `policy.maxCostPerTraceUsd` here is what the
1371
+ * ledger enforces. `parentHandle` is set by the factory — a value passed
1372
+ * in callOpts is overridden.
1373
+ */
1374
+ callOpts?: CallOptions & {
1375
+ policy?: CompilePolicy;
1376
+ };
1377
+ /** Explicit consent — beats KGAUTO_DELEGATE env (AUTO_PROMOTE posture). */
1378
+ enabled?: boolean;
1379
+ }
1380
+ interface DelegateHandle {
1381
+ toolDefinition: typeof DELEGATE_TOOL_DEFINITION;
1382
+ handler: (args: DelegateToolArgs) => Promise<DelegateResult>;
1383
+ /**
1384
+ * §7a — report what the orchestrator did with a sub-result. Writes a
1385
+ * migration-052 row via the brain-read env trio (RLS-scoped to appId).
1386
+ * Unreported sub-results are 'trusted' by definition — report only
1387
+ * 'verified' and 'discarded'.
1388
+ */
1389
+ reportComposition: (report: {
1390
+ subHandle: string;
1391
+ disposition: 'verified' | 'discarded';
1392
+ note?: string;
1393
+ }) => Promise<{
1394
+ ok: boolean;
1395
+ reason?: string;
1396
+ }>;
1397
+ /** Ledger introspection: delegated spend recorded for this trace so far. */
1398
+ traceSpendUsd: () => number;
1399
+ }
1400
+ declare function createDelegate(opts: CreateDelegateOpts): DelegateHandle;
1401
+
1253
1402
  /**
1254
1403
  * archetype-fits — alpha.43.
1255
1404
  *
@@ -3531,4 +3680,4 @@ declare function planDecomposition(args: PlanDecompositionArgs): DecompositionPl
3531
3680
  */
3532
3681
  declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
3533
3682
 
3534
- 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, BRAIN_READ_ENV_NAMES, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, COACH_CFG, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, DECOMPOSITION_TEMPLATES, DECOMPOSITION_TEMPLATES_VERSION, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, DISCIPLINE_GATES_V1_ALT_HEADER, type DecompositionPlan, type DecompositionStep, type DecompositionTemplate, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type ExecutorCandidate, type FallbackPosture, FallbackReason, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalAxis, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenEvalStrategyId, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_FAILURE_CFG, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type MeasuredFailureRuntime, type MeasuredFailureVerdict, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PlannedStep, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, ROLLBACK_SUPPRESSION_WINDOW_DAYS, RULE_DISCIPLINE_GATES_V1, RULE_DISCIPLINE_GATES_V1_STRUCTURED, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, STRATEGY_AUTHORSHIP_LIMITATION, SectionRewrite, type ShadowProbeRecordInput, type StrategyAttribution, type StrategyAttributionResult, type StrategyOutcome, type SupportedProvider, type SurfaceFailureRow, type SurfaceStats, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, altGatesBlockFor, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, awaitMeasuredFailureReady, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, classifyStrategyOutcome, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configureMeasuredFailureBrain, configurePromotionsBrain, countTokens, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getMeasuredFailureVerdict, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecentRollback, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isExclusionFindingsBrainActive, isMeasuredFailureBrainActive, isMeasuredFailureGateEnabledFromEnv, isModelReachable, isPromotionsBrainActive, isProviderReachable, judgeMeasuredFailure, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, mapMeasuredFailureRows, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, planDecomposition, prefetchMeasuredFailure, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, runStrategyEvalWithAttribution, setTokenizer, wilsonLowerBound, withAltDisciplineContract, withDisciplineContract };
3683
+ 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, BRAIN_READ_ENV_NAMES, BestPracticeAdvisory, type BrainConfig, type BrainDeadLetterEntry, type BrainHealthSnapshot, type BrainQueryConfig, type BrainReadEnv, COACH_CFG, CallOptions, CallResult, ChainEntry, type CompatibilityIntent, type CompileForAISDKv6Result, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, type CreateDelegateOpts, DECOMPOSITION_TEMPLATES, DECOMPOSITION_TEMPLATES_VERSION, DEFAULT_FINDINGS_ENDPOINT, DEFAULT_MEASURED_FAILURE_ENDPOINT, DEFAULT_PROMOTIONS_ENDPOINT, DELEGATE_TOOL_DEFINITION, DISCIPLINE_GATES_V1_ALT_HEADER, type DecompositionPlan, type DecompositionStep, type DecompositionTemplate, type DelegateHandle, type DelegateRefusalReason, type DelegateResult, type DelegateToolArgs, type ExclusionFindingRow, type ExclusionResolutionSource, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type ExecutorCandidate, type FallbackPosture, FallbackReason, FamilyResolutionError, type GetActionableAdvisoriesOptions, type GetApplicablePromotionOpts, type GetDefaultFallbackChainOpts, type GetMeasuredFailureOpts, type GetPerAxisMetricsOpts, type GetRecommendedPrimaryOptions, type GoldenEvalAxis, type GoldenEvalCase, type GoldenEvalOptions, type GoldenEvalRunResult, type GoldenEvalStrategyId, type GoldenIrRecordInput, Grounding, IntentArchetypeName, JUDGE_RUBRICS, LIBRARY_VERSION, type LLMJudgeOptions, MEASURED_FAILURE_CFG, MEASURED_GROUNDING_MIN_N, type MarkAdvisoryResolvedOptions, type MarkExclusionFindingHandledOptions, type MarkPromoteReadyHandledOptions, type MeasuredFailureRuntime, type MeasuredFailureVerdict, type ModelBrainRow, type ModelCompatibility, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, type OutcomePayload, OutcomeResult, OutputMode, PRODUCER_OWNED_RULE_CODES, PROVIDER_ENV_KEYS, PerAxisMetrics, type PlannedStep, type PricingRow, type ProbeShadowOptions, type ProbeShadowServed, type ProfileToRowOptions, type PromoteReadyFindingRow, type PromoteReadyResolution, type PromotionRow, type PromotionsRuntime, PromptIR, Provider, ProviderOverrides, type ProviderReachability, ROLLBACK_SUPPRESSION_WINDOW_DAYS, RULE_DISCIPLINE_GATES_V1, RULE_DISCIPLINE_GATES_V1_STRUCTURED, RULE_SEQUENTIAL_TOOL_CLIFF, type ReachabilityOpts, RecordInput, RecordOutcomeInput, type RunAdvisorPhase2Context, STRATEGY_AUTHORSHIP_LIMITATION, SectionRewrite, type ShadowProbeRecordInput, type StrategyAttribution, type StrategyAttributionResult, type StrategyOutcome, type SupportedProvider, type SurfaceFailureRow, type SurfaceStats, SystemModelMessage, TRANSLATOR_FLOOR, _testResetMeasuredFailure, _testResetPromotions, _testWaitForMeasuredFailureRefresh, _testWaitForPromotionsRefresh, altGatesBlockFor, applyArchetypeConvention, applySectionRewrites, attachCacheControlToStreamTextInput, awaitMeasuredFailureReady, brainHealth, buildGoldenIrRow, buildLLMJudge, buildPairwiseJudgePrompt, buildShadowProbeRow, call, classifyStrategyOutcome, clearBrain, combineOrderSwappedVerdicts, compile, compileForAISDKv6, configureBrain, configureMeasuredFailureBrain, configurePromotionsBrain, countTokens, createDelegate, deriveFamilyFromModelId, deriveOwnership, execute, findBetterFit, flushBrainDeadLetter, getActionableAdvisories, getAllStarterChains, getAllStarterChainsWithGrounding, getApplicablePromotion, getArchetypePerfScore, getDefaultFallbackChain, getDefaultFallbackChainWithGrounding, getMeasuredFailureVerdict, getModelCompatibility, getPerAxisMetrics, getReachabilityDiagnostic, getRecentRollback, getRecommendedPrimary, getSequentialStarterChain, getSequentialStarterChainWithGrounding, getStaleExclusionFindings, getStarterChain, getStarterChainWithGrounding, isAutoPromoteEnabledFromEnv, isBrainQueryActiveFor, isBrainSync, isDelegateEnabledFromEnv, isExclusionFindingsBrainActive, isMeasuredFailureBrainActive, isMeasuredFailureGateEnabledFromEnv, isModelReachable, isPromotionsBrainActive, isProviderReachable, judgeMeasuredFailure, loadAliasesFromBrain, loadArchetypePerfFromBrain, loadArchetypePerfNFromBrain, loadChainsFromBrain, loadModelsFromBrain, loadPricingFromBrain, mapMeasuredFailureRows, markAdvisoryResolved, markExclusionFindingHandled, markPromoteReadyHandled, parseJudgeVerdict, peekBrainDeadLetter, planDecomposition, prefetchMeasuredFailure, probeShadow, profileToRow, readBrainReadEnv, record, recordGoldenIr, recordOutcome, recordShadowProbe, renderIrForJudge, resetTokenizer, resolveConventionsForProfile, resolvePricingAt, resolveProviderKey, rubricFor, runAdvisor, runGoldenEval, runStrategyEvalWithAttribution, setTokenizer, wilsonLowerBound, withAltDisciplineContract, withDisciplineContract };
package/dist/index.js CHANGED
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  DEFAULT_FINDINGS_ENDPOINT: () => DEFAULT_FINDINGS_ENDPOINT,
34
34
  DEFAULT_MEASURED_FAILURE_ENDPOINT: () => DEFAULT_MEASURED_FAILURE_ENDPOINT,
35
35
  DEFAULT_PROMOTIONS_ENDPOINT: () => DEFAULT_PROMOTIONS_ENDPOINT,
36
+ DELEGATE_TOOL_DEFINITION: () => DELEGATE_TOOL_DEFINITION,
36
37
  DIALECT_VERSION: () => DIALECT_VERSION,
37
38
  DISCIPLINE_GATES_V1_ALT_HEADER: () => DISCIPLINE_GATES_V1_ALT_HEADER,
38
39
  FamilyResolutionError: () => FamilyResolutionError,
@@ -80,6 +81,7 @@ __export(index_exports, {
80
81
  configurePromotionsBrain: () => configurePromotionsBrain,
81
82
  countTokens: () => countTokens,
82
83
  createBrainForwardRoutes: () => createBrainForwardRoutes,
84
+ createDelegate: () => createDelegate,
83
85
  createKeyHealthRoute: () => createKeyHealthRoute,
84
86
  deriveFamilyFromModelId: () => deriveFamilyFromModelId,
85
87
  deriveOwnership: () => deriveOwnership,
@@ -111,6 +113,7 @@ __export(index_exports, {
111
113
  isAutoPromoteEnabledFromEnv: () => isAutoPromoteEnabledFromEnv,
112
114
  isBrainQueryActiveFor: () => isBrainQueryActiveFor,
113
115
  isBrainSync: () => isBrainSync,
116
+ isDelegateEnabledFromEnv: () => isDelegateEnabledFromEnv,
114
117
  isExclusionFindingsBrainActive: () => isExclusionFindingsBrainActive,
115
118
  isMeasuredFailureBrainActive: () => isMeasuredFailureBrainActive,
116
119
  isMeasuredFailureGateEnabledFromEnv: () => isMeasuredFailureGateEnabledFromEnv,
@@ -9312,7 +9315,7 @@ function createBrainForwardRoutes(config) {
9312
9315
  }
9313
9316
 
9314
9317
  // src/version.ts
9315
- var LIBRARY_VERSION = "2.0.0-alpha.78";
9318
+ var LIBRARY_VERSION = "2.0.0-alpha.79";
9316
9319
 
9317
9320
  // src/key-health.ts
9318
9321
  var JSON_HEADERS2 = { "Content-Type": "application/json" };
@@ -9598,6 +9601,171 @@ function clamp(n) {
9598
9601
  return Math.max(0, Math.min(1, n));
9599
9602
  }
9600
9603
 
9604
+ // src/delegate.ts
9605
+ function isDelegateEnabledFromEnv(envSource) {
9606
+ const env = envSource ?? (typeof process !== "undefined" && process.env ? process.env : {});
9607
+ const raw = (env.KGAUTO_DELEGATE ?? "").trim().toLowerCase();
9608
+ return raw === "1" || raw === "true";
9609
+ }
9610
+ var DELEGATE_TOOL_DEFINITION = {
9611
+ name: "delegate",
9612
+ description: "Delegate a self-contained sub-task to a cheaper executor model chosen by kgauto from measured evidence. YOU decide what to delegate and supply a complete input; kgauto decides which model runs it (never outside the declared pool). The call may be refused (budget exhausted, no qualified executor) \u2014 on refusal, continue and compose with what you have. Verify sub-results before composing them into your answer; do not present unverified delegated content as checked.",
9613
+ inputSchema: {
9614
+ type: "object",
9615
+ properties: {
9616
+ sub_archetype: {
9617
+ type: "string",
9618
+ enum: ALL_ARCHETYPES,
9619
+ description: "What kind of work the sub-task is (its routing archetype)."
9620
+ },
9621
+ input: {
9622
+ type: "string",
9623
+ description: "Complete, self-contained sub-task input. Include everything the executor needs \u2014 it sees nothing else."
9624
+ },
9625
+ quality_floor: {
9626
+ type: "number",
9627
+ minimum: 0,
9628
+ maximum: 10,
9629
+ description: "Optional minimum executor quality score (0-10) for this archetype. Omit to accept the evidence-ranked default."
9630
+ }
9631
+ },
9632
+ required: ["sub_archetype", "input"],
9633
+ additionalProperties: false
9634
+ }
9635
+ };
9636
+ function createDelegate(opts) {
9637
+ const { parentIr, parentHandle } = opts;
9638
+ const enabled = opts.enabled ?? isDelegateEnabledFromEnv();
9639
+ const budget = opts.callOpts?.policy?.maxCostPerTraceUsd;
9640
+ let spentUsd = 0;
9641
+ async function handler(args) {
9642
+ if (!enabled) {
9643
+ return {
9644
+ ok: false,
9645
+ reason: "delegate_not_enabled",
9646
+ detail: "Delegation is not enabled for this consumer (KGAUTO_DELEGATE / CreateDelegateOpts.enabled). Do the sub-task yourself."
9647
+ };
9648
+ }
9649
+ const archetype = args.sub_archetype;
9650
+ if (!ALL_ARCHETYPES.includes(archetype)) {
9651
+ return {
9652
+ ok: false,
9653
+ reason: "invalid_sub_archetype",
9654
+ detail: `Unknown sub_archetype '${String(args.sub_archetype)}'. Valid: ${ALL_ARCHETYPES.join(", ")}. Re-classify or do the sub-task yourself.`
9655
+ };
9656
+ }
9657
+ const pool = parentIr.models;
9658
+ const concreteIds = pool.filter((m) => typeof m === "string");
9659
+ let blockedByFloor = [];
9660
+ if (typeof args.quality_floor === "number") {
9661
+ blockedByFloor = concreteIds.filter(
9662
+ (m) => getArchetypePerfScore(m, archetype).score < args.quality_floor
9663
+ );
9664
+ if (blockedByFloor.length === pool.length) {
9665
+ const scores = concreteIds.map((m) => `${m}=${getArchetypePerfScore(m, archetype).score}`).join(", ");
9666
+ return {
9667
+ ok: false,
9668
+ reason: "no_qualified_executor",
9669
+ detail: `No model in the declared pool clears quality_floor=${args.quality_floor} for '${archetype}' (${scores}). Lower the floor or do the sub-task yourself.`
9670
+ };
9671
+ }
9672
+ }
9673
+ const subIr = {
9674
+ appId: parentIr.appId,
9675
+ intent: { name: `delegate:${archetype}`, archetype },
9676
+ sections: [{ id: "delegated-task", text: args.input }],
9677
+ currentTurn: { role: "user", content: args.input },
9678
+ models: pool
9679
+ };
9680
+ const mergedPolicy = {
9681
+ ...opts.callOpts?.policy ?? {},
9682
+ blockedModels: [
9683
+ ...opts.callOpts?.policy?.blockedModels ?? [],
9684
+ ...blockedByFloor
9685
+ ]
9686
+ };
9687
+ if (typeof budget === "number" && budget > 0) {
9688
+ let estimate = 0;
9689
+ try {
9690
+ estimate = compile(subIr, { policy: mergedPolicy }).estimatedCostUsd;
9691
+ } catch {
9692
+ estimate = 0;
9693
+ }
9694
+ if (spentUsd + estimate > budget) {
9695
+ return {
9696
+ ok: false,
9697
+ reason: "trace_budget_exhausted",
9698
+ detail: `Trace budget $${budget.toFixed(4)} would be exceeded (spent $${spentUsd.toFixed(4)} + estimated $${estimate.toFixed(4)}). Compose your answer from the sub-results you already have.`
9699
+ };
9700
+ }
9701
+ }
9702
+ let result;
9703
+ try {
9704
+ result = await call(subIr, {
9705
+ ...opts.callOpts ?? {},
9706
+ policy: mergedPolicy,
9707
+ parentHandle
9708
+ // R0 linkage — branch row, trace_id = parent
9709
+ });
9710
+ } catch (err) {
9711
+ const detail = err instanceof CallError ? `Sub-call failed after ${err.attempts.length} attempt(s): ${err.attempts.map((a) => a.errorCode).join(" \u2192 ")}.` : String(err);
9712
+ return {
9713
+ ok: false,
9714
+ reason: "call_failed",
9715
+ detail: `${detail} Compose without this sub-result or retry with different input.`
9716
+ };
9717
+ }
9718
+ const profile = tryGetProfile(result.actualModel);
9719
+ const costUsd2 = profile ? result.response.tokens.input / 1e6 * profile.costInputPer1m + result.response.tokens.output / 1e6 * profile.costOutputPer1m : 0;
9720
+ spentUsd += costUsd2;
9721
+ return {
9722
+ ok: true,
9723
+ output: result.response.structuredOutput !== null ? JSON.stringify(result.response.structuredOutput) : result.response.text,
9724
+ subHandle: result.handle,
9725
+ executorModel: result.actualModel,
9726
+ costUsd: costUsd2,
9727
+ latencyMs: result.latencyMs,
9728
+ verification: "trusted"
9729
+ };
9730
+ }
9731
+ async function reportComposition(report) {
9732
+ const env = readBrainReadEnv();
9733
+ if (!env.endpoint || !env.jwt || !env.anonKey) {
9734
+ return { ok: false, reason: `brain_read_not_configured:${env.missingEnv.join(",")}` };
9735
+ }
9736
+ try {
9737
+ const res = await fetch(
9738
+ `${env.endpoint.replace(/\/$/, "")}/rest/v1/kgauto_composition_reports`,
9739
+ {
9740
+ method: "POST",
9741
+ headers: {
9742
+ Authorization: `Bearer ${env.jwt}`,
9743
+ apikey: env.anonKey,
9744
+ "Content-Type": "application/json",
9745
+ Prefer: "return=minimal"
9746
+ },
9747
+ body: JSON.stringify({
9748
+ app_id: parentIr.appId,
9749
+ sub_handle: report.subHandle,
9750
+ disposition: report.disposition,
9751
+ ...report.note ? { note: report.note } : {}
9752
+ })
9753
+ }
9754
+ );
9755
+ if (!res.ok) return { ok: false, reason: `write_failed:${res.status}` };
9756
+ return { ok: true };
9757
+ } catch (err) {
9758
+ return { ok: false, reason: `network_error:${err instanceof Error ? err.message : String(err)}` };
9759
+ }
9760
+ }
9761
+ return {
9762
+ toolDefinition: DELEGATE_TOOL_DEFINITION,
9763
+ handler,
9764
+ reportComposition,
9765
+ traceSpendUsd: () => spentUsd
9766
+ };
9767
+ }
9768
+
9601
9769
  // src/advisories-api.ts
9602
9770
  var SEVERITY_SET = /* @__PURE__ */ new Set(["info", "warn", "critical"]);
9603
9771
  var STATUS_SET = /* @__PURE__ */ new Set(["open", "snoozed", "resolved"]);
@@ -10197,6 +10365,7 @@ function compile2(ir, opts) {
10197
10365
  DEFAULT_FINDINGS_ENDPOINT,
10198
10366
  DEFAULT_MEASURED_FAILURE_ENDPOINT,
10199
10367
  DEFAULT_PROMOTIONS_ENDPOINT,
10368
+ DELEGATE_TOOL_DEFINITION,
10200
10369
  DIALECT_VERSION,
10201
10370
  DISCIPLINE_GATES_V1_ALT_HEADER,
10202
10371
  FamilyResolutionError,
@@ -10244,6 +10413,7 @@ function compile2(ir, opts) {
10244
10413
  configurePromotionsBrain,
10245
10414
  countTokens,
10246
10415
  createBrainForwardRoutes,
10416
+ createDelegate,
10247
10417
  createKeyHealthRoute,
10248
10418
  deriveFamilyFromModelId,
10249
10419
  deriveOwnership,
@@ -10275,6 +10445,7 @@ function compile2(ir, opts) {
10275
10445
  isAutoPromoteEnabledFromEnv,
10276
10446
  isBrainQueryActiveFor,
10277
10447
  isBrainSync,
10448
+ isDelegateEnabledFromEnv,
10278
10449
  isExclusionFindingsBrainActive,
10279
10450
  isMeasuredFailureBrainActive,
10280
10451
  isMeasuredFailureGateEnabledFromEnv,
package/dist/index.mjs CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  import {
17
17
  LIBRARY_VERSION,
18
18
  createKeyHealthRoute
19
- } from "./chunk-QVD2QWST.mjs";
19
+ } from "./chunk-DRYCOR6G.mjs";
20
20
  import {
21
21
  ABSOLUTE_FLOOR,
22
22
  ARCHETYPE_FLOOR_DEFAULT,
@@ -6343,6 +6343,171 @@ function clamp(n) {
6343
6343
  return Math.max(0, Math.min(1, n));
6344
6344
  }
6345
6345
 
6346
+ // src/delegate.ts
6347
+ function isDelegateEnabledFromEnv(envSource) {
6348
+ const env = envSource ?? (typeof process !== "undefined" && process.env ? process.env : {});
6349
+ const raw = (env.KGAUTO_DELEGATE ?? "").trim().toLowerCase();
6350
+ return raw === "1" || raw === "true";
6351
+ }
6352
+ var DELEGATE_TOOL_DEFINITION = {
6353
+ name: "delegate",
6354
+ description: "Delegate a self-contained sub-task to a cheaper executor model chosen by kgauto from measured evidence. YOU decide what to delegate and supply a complete input; kgauto decides which model runs it (never outside the declared pool). The call may be refused (budget exhausted, no qualified executor) \u2014 on refusal, continue and compose with what you have. Verify sub-results before composing them into your answer; do not present unverified delegated content as checked.",
6355
+ inputSchema: {
6356
+ type: "object",
6357
+ properties: {
6358
+ sub_archetype: {
6359
+ type: "string",
6360
+ enum: ALL_ARCHETYPES,
6361
+ description: "What kind of work the sub-task is (its routing archetype)."
6362
+ },
6363
+ input: {
6364
+ type: "string",
6365
+ description: "Complete, self-contained sub-task input. Include everything the executor needs \u2014 it sees nothing else."
6366
+ },
6367
+ quality_floor: {
6368
+ type: "number",
6369
+ minimum: 0,
6370
+ maximum: 10,
6371
+ description: "Optional minimum executor quality score (0-10) for this archetype. Omit to accept the evidence-ranked default."
6372
+ }
6373
+ },
6374
+ required: ["sub_archetype", "input"],
6375
+ additionalProperties: false
6376
+ }
6377
+ };
6378
+ function createDelegate(opts) {
6379
+ const { parentIr, parentHandle } = opts;
6380
+ const enabled = opts.enabled ?? isDelegateEnabledFromEnv();
6381
+ const budget = opts.callOpts?.policy?.maxCostPerTraceUsd;
6382
+ let spentUsd = 0;
6383
+ async function handler(args) {
6384
+ if (!enabled) {
6385
+ return {
6386
+ ok: false,
6387
+ reason: "delegate_not_enabled",
6388
+ detail: "Delegation is not enabled for this consumer (KGAUTO_DELEGATE / CreateDelegateOpts.enabled). Do the sub-task yourself."
6389
+ };
6390
+ }
6391
+ const archetype = args.sub_archetype;
6392
+ if (!ALL_ARCHETYPES.includes(archetype)) {
6393
+ return {
6394
+ ok: false,
6395
+ reason: "invalid_sub_archetype",
6396
+ detail: `Unknown sub_archetype '${String(args.sub_archetype)}'. Valid: ${ALL_ARCHETYPES.join(", ")}. Re-classify or do the sub-task yourself.`
6397
+ };
6398
+ }
6399
+ const pool = parentIr.models;
6400
+ const concreteIds = pool.filter((m) => typeof m === "string");
6401
+ let blockedByFloor = [];
6402
+ if (typeof args.quality_floor === "number") {
6403
+ blockedByFloor = concreteIds.filter(
6404
+ (m) => getArchetypePerfScore(m, archetype).score < args.quality_floor
6405
+ );
6406
+ if (blockedByFloor.length === pool.length) {
6407
+ const scores = concreteIds.map((m) => `${m}=${getArchetypePerfScore(m, archetype).score}`).join(", ");
6408
+ return {
6409
+ ok: false,
6410
+ reason: "no_qualified_executor",
6411
+ detail: `No model in the declared pool clears quality_floor=${args.quality_floor} for '${archetype}' (${scores}). Lower the floor or do the sub-task yourself.`
6412
+ };
6413
+ }
6414
+ }
6415
+ const subIr = {
6416
+ appId: parentIr.appId,
6417
+ intent: { name: `delegate:${archetype}`, archetype },
6418
+ sections: [{ id: "delegated-task", text: args.input }],
6419
+ currentTurn: { role: "user", content: args.input },
6420
+ models: pool
6421
+ };
6422
+ const mergedPolicy = {
6423
+ ...opts.callOpts?.policy ?? {},
6424
+ blockedModels: [
6425
+ ...opts.callOpts?.policy?.blockedModels ?? [],
6426
+ ...blockedByFloor
6427
+ ]
6428
+ };
6429
+ if (typeof budget === "number" && budget > 0) {
6430
+ let estimate = 0;
6431
+ try {
6432
+ estimate = compile(subIr, { policy: mergedPolicy }).estimatedCostUsd;
6433
+ } catch {
6434
+ estimate = 0;
6435
+ }
6436
+ if (spentUsd + estimate > budget) {
6437
+ return {
6438
+ ok: false,
6439
+ reason: "trace_budget_exhausted",
6440
+ detail: `Trace budget $${budget.toFixed(4)} would be exceeded (spent $${spentUsd.toFixed(4)} + estimated $${estimate.toFixed(4)}). Compose your answer from the sub-results you already have.`
6441
+ };
6442
+ }
6443
+ }
6444
+ let result;
6445
+ try {
6446
+ result = await call(subIr, {
6447
+ ...opts.callOpts ?? {},
6448
+ policy: mergedPolicy,
6449
+ parentHandle
6450
+ // R0 linkage — branch row, trace_id = parent
6451
+ });
6452
+ } catch (err) {
6453
+ const detail = err instanceof CallError ? `Sub-call failed after ${err.attempts.length} attempt(s): ${err.attempts.map((a) => a.errorCode).join(" \u2192 ")}.` : String(err);
6454
+ return {
6455
+ ok: false,
6456
+ reason: "call_failed",
6457
+ detail: `${detail} Compose without this sub-result or retry with different input.`
6458
+ };
6459
+ }
6460
+ const profile = tryGetProfile(result.actualModel);
6461
+ const costUsd2 = profile ? result.response.tokens.input / 1e6 * profile.costInputPer1m + result.response.tokens.output / 1e6 * profile.costOutputPer1m : 0;
6462
+ spentUsd += costUsd2;
6463
+ return {
6464
+ ok: true,
6465
+ output: result.response.structuredOutput !== null ? JSON.stringify(result.response.structuredOutput) : result.response.text,
6466
+ subHandle: result.handle,
6467
+ executorModel: result.actualModel,
6468
+ costUsd: costUsd2,
6469
+ latencyMs: result.latencyMs,
6470
+ verification: "trusted"
6471
+ };
6472
+ }
6473
+ async function reportComposition(report) {
6474
+ const env = readBrainReadEnv();
6475
+ if (!env.endpoint || !env.jwt || !env.anonKey) {
6476
+ return { ok: false, reason: `brain_read_not_configured:${env.missingEnv.join(",")}` };
6477
+ }
6478
+ try {
6479
+ const res = await fetch(
6480
+ `${env.endpoint.replace(/\/$/, "")}/rest/v1/kgauto_composition_reports`,
6481
+ {
6482
+ method: "POST",
6483
+ headers: {
6484
+ Authorization: `Bearer ${env.jwt}`,
6485
+ apikey: env.anonKey,
6486
+ "Content-Type": "application/json",
6487
+ Prefer: "return=minimal"
6488
+ },
6489
+ body: JSON.stringify({
6490
+ app_id: parentIr.appId,
6491
+ sub_handle: report.subHandle,
6492
+ disposition: report.disposition,
6493
+ ...report.note ? { note: report.note } : {}
6494
+ })
6495
+ }
6496
+ );
6497
+ if (!res.ok) return { ok: false, reason: `write_failed:${res.status}` };
6498
+ return { ok: true };
6499
+ } catch (err) {
6500
+ return { ok: false, reason: `network_error:${err instanceof Error ? err.message : String(err)}` };
6501
+ }
6502
+ }
6503
+ return {
6504
+ toolDefinition: DELEGATE_TOOL_DEFINITION,
6505
+ handler,
6506
+ reportComposition,
6507
+ traceSpendUsd: () => spentUsd
6508
+ };
6509
+ }
6510
+
6346
6511
  // src/advisories-api.ts
6347
6512
  var SEVERITY_SET = /* @__PURE__ */ new Set(["info", "warn", "critical"]);
6348
6513
  var STATUS_SET = /* @__PURE__ */ new Set(["open", "snoozed", "resolved"]);
@@ -6941,6 +7106,7 @@ export {
6941
7106
  DEFAULT_FINDINGS_ENDPOINT,
6942
7107
  DEFAULT_MEASURED_FAILURE_ENDPOINT,
6943
7108
  DEFAULT_PROMOTIONS_ENDPOINT,
7109
+ DELEGATE_TOOL_DEFINITION,
6944
7110
  DIALECT_VERSION,
6945
7111
  DISCIPLINE_GATES_V1_ALT_HEADER,
6946
7112
  FamilyResolutionError,
@@ -6988,6 +7154,7 @@ export {
6988
7154
  configurePromotionsBrain,
6989
7155
  countTokens,
6990
7156
  createBrainForwardRoutes,
7157
+ createDelegate,
6991
7158
  createKeyHealthRoute,
6992
7159
  deriveFamilyFromModelId,
6993
7160
  deriveOwnership,
@@ -7019,6 +7186,7 @@ export {
7019
7186
  isAutoPromoteEnabledFromEnv,
7020
7187
  isBrainQueryActiveFor,
7021
7188
  isBrainSync,
7189
+ isDelegateEnabledFromEnv,
7022
7190
  isExclusionFindingsBrainActive,
7023
7191
  isMeasuredFailureBrainActive,
7024
7192
  isMeasuredFailureGateEnabledFromEnv,
@@ -25,7 +25,7 @@ __export(key_health_exports, {
25
25
  module.exports = __toCommonJS(key_health_exports);
26
26
 
27
27
  // src/version.ts
28
- var LIBRARY_VERSION = "2.0.0-alpha.78";
28
+ var LIBRARY_VERSION = "2.0.0-alpha.79";
29
29
 
30
30
  // src/key-health.ts
31
31
  var JSON_HEADERS = { "Content-Type": "application/json" };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createKeyHealthRoute
3
- } from "./chunk-QVD2QWST.mjs";
3
+ } from "./chunk-DRYCOR6G.mjs";
4
4
  export {
5
5
  createKeyHealthRoute
6
6
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warmdrift/kgauto-compiler",
3
- "version": "2.0.0-alpha.78",
3
+ "version": "2.0.0-alpha.79",
4
4
  "description": "Prompt compiler with executable provider knowledge for multi-model AI apps: normalized multi-provider transport with fallback chains, compile-time cliff guards, a curated model registry, and a telemetry flight recorder. Swap models without rewriting prompts.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",