hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3

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.
Files changed (115) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +89 -2
  3. package/dist/adapter-kit.d.ts +37 -0
  4. package/dist/adapter-kit.js +34 -0
  5. package/dist/adapter-kit.js.map +1 -0
  6. package/dist/agent-Bj5YPrO7.d.ts +169 -0
  7. package/dist/agent-D6OXR7UF.js +24 -0
  8. package/dist/agent-D6OXR7UF.js.map +1 -0
  9. package/dist/agent-readiness-KSGNKTGK.js +19 -0
  10. package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
  11. package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
  12. package/dist/chunk-2RK74GCA.js +2397 -0
  13. package/dist/chunk-2RK74GCA.js.map +1 -0
  14. package/dist/chunk-3TIYA3K5.js +55 -0
  15. package/dist/chunk-3TIYA3K5.js.map +1 -0
  16. package/dist/chunk-6FIXXWNM.js +1 -0
  17. package/dist/chunk-6FIXXWNM.js.map +1 -0
  18. package/dist/chunk-6XIJW65Q.js +52 -0
  19. package/dist/chunk-6XIJW65Q.js.map +1 -0
  20. package/dist/chunk-7LDQKJKI.js +248 -0
  21. package/dist/chunk-7LDQKJKI.js.map +1 -0
  22. package/dist/chunk-CPN4DOXH.js +115 -0
  23. package/dist/chunk-CPN4DOXH.js.map +1 -0
  24. package/dist/chunk-DAXPAV2L.js +810 -0
  25. package/dist/chunk-DAXPAV2L.js.map +1 -0
  26. package/dist/chunk-DQEMIGKC.js +291 -0
  27. package/dist/chunk-DQEMIGKC.js.map +1 -0
  28. package/dist/chunk-DZFFGUIA.js +81 -0
  29. package/dist/chunk-DZFFGUIA.js.map +1 -0
  30. package/dist/chunk-EEUYQFCP.js +106 -0
  31. package/dist/chunk-EEUYQFCP.js.map +1 -0
  32. package/dist/chunk-G6JV7WV6.js +521 -0
  33. package/dist/chunk-G6JV7WV6.js.map +1 -0
  34. package/dist/chunk-GFVYNPLS.js +118 -0
  35. package/dist/chunk-GFVYNPLS.js.map +1 -0
  36. package/dist/chunk-GS5U3KUN.js +201 -0
  37. package/dist/chunk-GS5U3KUN.js.map +1 -0
  38. package/dist/chunk-HB7FBSH2.js +960 -0
  39. package/dist/chunk-HB7FBSH2.js.map +1 -0
  40. package/dist/chunk-HZFZX5A3.js +21 -0
  41. package/dist/chunk-HZFZX5A3.js.map +1 -0
  42. package/dist/chunk-J7VAYJKM.js +595 -0
  43. package/dist/chunk-J7VAYJKM.js.map +1 -0
  44. package/dist/chunk-NCNSHOF7.js +52 -0
  45. package/dist/chunk-NCNSHOF7.js.map +1 -0
  46. package/dist/chunk-RH5A5U7G.js +202 -0
  47. package/dist/chunk-RH5A5U7G.js.map +1 -0
  48. package/dist/chunk-RX3XZENU.js +385 -0
  49. package/dist/chunk-RX3XZENU.js.map +1 -0
  50. package/dist/chunk-RXU2Q2HF.js +49 -0
  51. package/dist/chunk-RXU2Q2HF.js.map +1 -0
  52. package/dist/chunk-TG7NTMTR.js +208 -0
  53. package/dist/chunk-TG7NTMTR.js.map +1 -0
  54. package/dist/chunk-TWGEYWMO.js +1217 -0
  55. package/dist/chunk-TWGEYWMO.js.map +1 -0
  56. package/dist/chunk-UZPDDQVJ.js +2910 -0
  57. package/dist/chunk-UZPDDQVJ.js.map +1 -0
  58. package/dist/chunk-WMKO5XOE.js +601 -0
  59. package/dist/chunk-WMKO5XOE.js.map +1 -0
  60. package/dist/chunk-WOQBVJH5.js +175 -0
  61. package/dist/chunk-WOQBVJH5.js.map +1 -0
  62. package/dist/chunk-WVT5SEKC.js +581 -0
  63. package/dist/chunk-WVT5SEKC.js.map +1 -0
  64. package/dist/cli.d.ts +1 -0
  65. package/dist/cli.js +26 -0
  66. package/dist/cli.js.map +1 -0
  67. package/dist/errors-BNHvvjn9.d.ts +98 -0
  68. package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
  69. package/dist/execution-types-ClYYqPQP.d.ts +239 -0
  70. package/dist/host-ledger-VPRWVVOS.js +25 -0
  71. package/dist/host-ledger-VPRWVVOS.js.map +1 -0
  72. package/dist/hosted-runtime.d.ts +168 -0
  73. package/dist/hosted-runtime.js +858 -0
  74. package/dist/hosted-runtime.js.map +1 -0
  75. package/dist/index-B86C6VAD.d.ts +41 -0
  76. package/dist/index.d.ts +344 -0
  77. package/dist/index.js +8825 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/memory-items-BSTC0_R0.d.ts +28 -0
  80. package/dist/memory-tools.d.ts +222 -0
  81. package/dist/memory-tools.js +923 -0
  82. package/dist/memory-tools.js.map +1 -0
  83. package/dist/orchestration/dynamic.d.ts +854 -0
  84. package/dist/orchestration/dynamic.js +3150 -0
  85. package/dist/orchestration/dynamic.js.map +1 -0
  86. package/dist/orchestration/graph.d.ts +11 -0
  87. package/dist/orchestration/graph.js +9 -0
  88. package/dist/orchestration/graph.js.map +1 -0
  89. package/dist/orchestration/index.d.ts +2385 -0
  90. package/dist/orchestration/index.js +6409 -0
  91. package/dist/orchestration/index.js.map +1 -0
  92. package/dist/orchestration/log.d.ts +301 -0
  93. package/dist/orchestration/log.js +3058 -0
  94. package/dist/orchestration/log.js.map +1 -0
  95. package/dist/orchestration/memory.d.ts +711 -0
  96. package/dist/orchestration/memory.js +27 -0
  97. package/dist/orchestration/memory.js.map +1 -0
  98. package/dist/provider-DX5Mf0uq.d.ts +151 -0
  99. package/dist/routing/index.d.ts +29 -0
  100. package/dist/routing/index.js +386 -0
  101. package/dist/routing/index.js.map +1 -0
  102. package/dist/routing/learning/index.d.ts +433 -0
  103. package/dist/routing/learning/index.js +2502 -0
  104. package/dist/routing/learning/index.js.map +1 -0
  105. package/dist/runtime-BSjrnxeF.d.ts +283 -0
  106. package/dist/runtime-OISPXS4I.js +19 -0
  107. package/dist/runtime-OISPXS4I.js.map +1 -0
  108. package/dist/store-types-2YdceOMy.d.ts +78 -0
  109. package/dist/types-BB7KqceP.d.ts +52 -0
  110. package/dist/types-CIqkKXix.d.ts +86 -0
  111. package/dist/types-DTFc1qO6.d.ts +1065 -0
  112. package/dist/types-DYex3p7_.d.ts +88 -0
  113. package/docs/licenses/ruflo-memory-MIT.txt +21 -0
  114. package/docs/releases/0.1.0-beta.3.md +13 -0
  115. package/package.json +114 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/routing/selector.ts","../../src/routing/receipt.ts","../../src/routing/types.ts","../../src/routing/workflow-store.ts"],"sourcesContent":["import { rethrowExecutionHalt } from '../public/execution-halt.js';\nimport { types } from 'node:util';\nimport { randomUUID } from 'node:crypto';\nimport { Agent } from '../public/agent.js';\nimport { TimeoutError } from '../public/errors.js';\nimport type { ModelInfo } from '../public/types.js';\nimport { Runtime } from '../core/runtime.js';\nimport { authenticationState } from '../core/auth-evidence.js';\nimport { OperationScope } from '../control/operation-scope.js';\nimport { normalize } from './config.js';\nimport { digest, hash, identifier, method, ownObject } from '../shared/json.js';\nimport { sealReceipt } from './receipt.js';\nimport { RoutingSelectionError, type CreateAgentContext, type RoutingAgentDefinition, type RoutingCandidate, type RoutingCandidateCode, type RoutingReceipt, type RoutingReceiptStore, type RoutingSelected } from './types.js';\n\nfunction failureCode(error: unknown): RoutingCandidateCode {\n // Adapter failures are untrusted: never evaluate accessors, inherited values or proxy traps.\n if (error === null || (typeof error !== 'object' && typeof error !== 'function') || types.isProxy(error)) return 'PROBE_FAILED';\n const descriptor = Object.getOwnPropertyDescriptor(error, 'code');\n const code = descriptor && Object.hasOwn(descriptor, 'value') ? descriptor.value : undefined;\n switch (code) {\n case 'CLI_NOT_INSTALLED': return 'CLI_MISSING';\n case 'NOT_AUTHENTICATED': return 'AUTH_REQUIRED';\n case 'UNEXPECTED_AUTH_SOURCE': return 'SUBSCRIPTION_REQUIRED';\n case 'UNSUPPORTED_CLI_VERSION': return 'CLI_UNSUPPORTED';\n case 'UNSUPPORTED_CAPABILITY':\n case 'REQUIRED_TRANSPORT_UNAVAILABLE': return 'POLICY_UNSUPPORTED';\n default: return 'PROBE_FAILED';\n }\n}\nfunction modelMatches(actual: ModelInfo, expected: ModelInfo): boolean {\n return actual.provider === expected.provider && actual.id === expected.id\n && actual.availability === expected.availability;\n}\n\n/** Resolve once locally. Never creates a session, dispatches a prompt, or retries execution. */\nexport async function createAgent(definition: RoutingAgentDefinition, context: CreateAgentContext): Promise<{ agent: Agent; receipt: RoutingReceipt }> {\n const startedAt = performance.now();\n context = ownObject(context, ['runtime', 'receipts', 'id', 'task', 'sourceDigest', 'signal', 'timeoutMs']);\n if (!context.runtime || types.isProxy(context.runtime) || !(context.runtime instanceof Runtime)) throw new TypeError('A Runtime is required');\n if (!context.receipts || typeof context.receipts !== 'object') throw new TypeError('A receipt store is required');\n const save = method<RoutingReceiptStore['save']>(context.receipts, 'save');\n method<RoutingReceiptStore['load']>(context.receipts, 'load');\n const id = context.id === undefined ? randomUUID() : context.id;\n identifier(id);\n const sourceDigest = context.sourceDigest;\n if (sourceDigest !== undefined) hash(sourceDigest);\n const timeoutMs = context.timeoutMs === undefined ? 30000 : context.timeoutMs;\n if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2147483647) throw new RangeError('Invalid selection timeoutMs');\n const signal = context.signal;\n if (signal !== undefined && (types.isProxy(signal) || !(signal instanceof AbortSignal))) throw new TypeError('Invalid AbortSignal');\n const expires = startedAt + timeoutMs;\n const scope = new OperationScope({ timeoutMs: Math.max(1, Math.floor(expires - performance.now())), ...(signal === undefined ? {} : { signal }) });\n const cancellationCode = (): 'ABORTED' | 'TIMEOUT' | undefined => {\n if (scope.signal.aborted) return (scope.signal.reason as { code?: string }).code === 'TIMEOUT' ? 'TIMEOUT' : 'ABORTED';\n if (performance.now() >= expires || scope.remainingMs() < 1) return 'TIMEOUT';\n return undefined;\n };\n const assertActive = (): void => {\n if (scope.signal.aborted) throw scope.signal.reason;\n if (cancellationCode()) throw new TimeoutError({ retryable: true }, 'Selection deadline exceeded');\n };\n const check = () => scope.race(assertActive);\n try {\n const runtime = context.runtime;\n // The deadline already exists while provider resolution and schema validation run.\n const config = normalize(definition, runtime, context.task);\n const candidates: RoutingCandidate[] = config.models.map(model => ({\n model: `${model.provider}/${model.id}`, provider: model.provider, modelId: model.id,\n status: 'not-evaluated',\n code: config.primary.includes(`${model.provider}/${model.id}`) || config.fallback === `${model.provider}/${model.id}` ? 'NOT_NEEDED' : 'NOT_IN_RULE',\n }));\n const excluded = (candidate: RoutingCandidate, code: RoutingCandidateCode) => { candidate.status = 'excluded'; candidate.code = code; };\n // Static hard filters cover the entire closed universe, even candidates never probed.\n candidates.forEach((candidate, index) => {\n const model = config.models[index]!;\n if (config.auto?.providers && !config.auto.providers.includes(candidate.provider)) excluded(candidate, 'PROVIDER_NOT_ALLOWED');\n else if (model.availability === 'unavailable') excluded(candidate, 'MODEL_UNAVAILABLE');\n else if (config.auto && model.availability === 'unverified' && !config.auto.allowUnverifiedModels) excluded(candidate, 'MODEL_UNVERIFIED');\n });\n let selected: RoutingSelected | undefined;\n let agent: Agent | undefined;\n let reason: RoutingReceipt['reason'] = candidates.length === 0 ? 'NO_CANDIDATES'\n : config.auto?.rules && !config.ruleId && !config.fallback ? 'NO_MATCHING_RULE' : 'NO_ELIGIBLE_CANDIDATE';\n let fatal: 'ABORTED' | 'TIMEOUT' | undefined;\n const cancelProposal = (code: 'ABORTED' | 'TIMEOUT') => {\n fatal = code; reason = code; selected = undefined; agent = undefined;\n for (const candidate of candidates) if (candidate.status === 'eligible') excluded(candidate, code);\n };\n try {\n await check();\n for (const name of [...config.primary, ...(config.fallback === undefined ? [] : [config.fallback])]) {\n await check();\n const index = candidates.findIndex(entry => entry.model === name);\n const candidate = candidates[index]!;\n const expected = config.models[index]!;\n if (candidate.status === 'excluded') continue;\n try {\n assertActive();\n const prepared = new Agent({ ...config.options, model: name }, runtime);\n if (!modelMatches(prepared.model, expected)) { excluded(candidate, 'PROBE_FAILED'); continue; }\n assertActive();\n // Await raw readiness: ownership lasts until actual preparation settles.\n const ready = await prepared.ready({ signal: scope.signal, timeoutMs: Math.max(1, Math.min(scope.remainingMs(), Math.floor(expires - performance.now()))), awaitSettlement: true });\n await check();\n if (!modelMatches(prepared.model, expected) || !modelMatches(ready.model, expected) || ready.provider !== candidate.provider) {\n excluded(candidate, 'PROBE_FAILED'); continue;\n }\n candidate.authState = authenticationState(ready.auth); candidate.authSource = ready.auth.source;\n candidate.transport = ready.plan.transport; candidate.fingerprintDigest = digest(ready.plan);\n if (ready.capabilities.unsupported.length) { excluded(candidate, 'POLICY_UNSUPPORTED'); continue; }\n if (candidate.authState === 'not-authenticated') { excluded(candidate, 'AUTH_REQUIRED'); continue; }\n if (config.auto && candidate.authState === 'unknown' && !config.auto.allowUnknownAuth) { excluded(candidate, 'AUTH_UNKNOWN'); continue; }\n if (!ready.ready || !ready.installation.installed) { excluded(candidate, 'CLI_MISSING'); continue; }\n candidate.status = 'eligible'; candidate.code = 'READY'; agent = prepared;\n selected = { model: name, provider: candidate.provider, modelId: candidate.modelId, transport: candidate.transport, fingerprintDigest: candidate.fingerprintDigest };\n reason = !config.auto ? 'FIXED' : name === config.fallback ? 'FALLBACK' : config.ruleId ? 'RULE' : 'PRIORITY';\n break;\n } catch (error) {\n rethrowExecutionHalt(error);\n const cancelled = cancellationCode();\n if (cancelled) { excluded(candidate, cancelled); throw error; }\n excluded(candidate, failureCode(error));\n }\n }\n await check();\n } catch (error) {\n rethrowExecutionHalt(error);\n const cancelled = cancellationCode();\n if (!cancelled) throw error;\n cancelProposal(cancelled);\n }\n await scope.drain();\n const beforeSave = cancellationCode();\n if (beforeSave) cancelProposal(beforeSave);\n const makeReceipt = () => sealReceipt({\n format: 1, purpose: 'selection-proposal', id, createdAt: Date.now(), configDigest: config.configDigest, taskDigest: config.taskDigest,\n ...(sourceDigest === undefined ? {} : { sourceDigest }),\n policy: { mode: config.auto ? 'auto' : 'fixed', version: 'priority-v1', ...(config.ruleId === undefined ? {} : { ruleId: config.ruleId }) },\n decision: selected ? 'selected' : 'abstained', reason, candidates, nativeDispatches: 0, ...(selected === undefined ? {} : { selected }),\n });\n let receipt = makeReceipt();\n const afterSeal = cancellationCode();\n if (!fatal && afterSeal) { cancelProposal(afterSeal); receipt = makeReceipt(); }\n // Never race immutable IO: raw rejection wins over later cancellation.\n await save(receipt);\n if (!fatal) {\n try { await check(); } catch { fatal = cancellationCode() ?? 'ABORTED'; }\n }\n await scope.drain();\n const identityMatches = agent && selected && modelMatches(agent.model, config.models[candidates.findIndex(candidate => candidate.model === selected!.model)]!);\n // This synchronous gate follows the LAST await. Cleanup and return cannot yield.\n const atReturn = cancellationCode();\n if (atReturn) fatal = atReturn;\n if (fatal) throw new RoutingSelectionError(fatal, receipt);\n if (!agent || !identityMatches) throw new RoutingSelectionError('NO_ROUTE', receipt);\n scope.dispose();\n return { agent, receipt };\n } finally { scope.dispose(); }\n}\n","import { canonical, digest, freeze, hash, identifier, jsonClone, method, object } from '../shared/json.js';\nimport type { RoutingCandidate, RoutingReceipt, RoutingReceiptStore } from './types.js';\nconst codes = ['READY', 'NOT_NEEDED', 'NOT_IN_RULE', 'PROVIDER_NOT_ALLOWED', 'MODEL_UNAVAILABLE', 'MODEL_UNVERIFIED', 'CLI_MISSING', 'AUTH_REQUIRED', 'AUTH_UNKNOWN', 'SUBSCRIPTION_REQUIRED', 'CLI_UNSUPPORTED', 'POLICY_UNSUPPORTED', 'PROBE_FAILED', 'ABORTED', 'TIMEOUT'];\nconst reasons = ['FIXED', 'PRIORITY', 'RULE', 'FALLBACK', 'NO_CANDIDATES', 'NO_ELIGIBLE_CANDIDATE', 'NO_MATCHING_RULE', 'ABORTED', 'TIMEOUT'];\nfunction member(value: unknown, values: readonly unknown[]): void { if (!values.includes(value)) throw new TypeError('Invalid receipt enum'); }\nfunction model(value: Record<string, unknown>): void {\n if (typeof value.provider !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(value.provider)\n || ['constructor', 'prototype', '__proto__'].includes(value.provider)\n || typeof value.modelId !== 'string' || !value.modelId.trim() || value.model !== `${value.provider}/${value.modelId}`\n || (value.model as string).length > 512) throw new TypeError('Invalid receipt model');\n}\n/** Strict clone, semantic validation and canonical checksum; returned proposals are deeply immutable. */\nexport function validateRoutingReceipt(value: unknown): RoutingReceipt {\n const copy: unknown = jsonClone(value);\n if (Buffer.byteLength(canonical(copy)) > 1048576) throw new TypeError('Receipt exceeds 1MiB');\n object(copy, ['format', 'purpose', 'id', 'createdAt', 'configDigest', 'taskDigest', 'sourceDigest', 'policy', 'decision', 'reason', 'candidates', 'nativeDispatches', 'selected', 'digest']);\n if (copy.format !== 1 || copy.purpose !== 'selection-proposal' || copy.nativeDispatches !== 0\n || !Number.isSafeInteger(copy.createdAt) || (copy.createdAt as number) < 0) throw new TypeError('Invalid receipt format');\n identifier(copy.id); hash(copy.configDigest); hash(copy.taskDigest); hash(copy.digest);\n if ('sourceDigest' in copy) hash(copy.sourceDigest);\n object(copy.policy, ['mode', 'version', 'ruleId']); member(copy.policy.mode, ['fixed', 'auto']);\n if (copy.policy.version !== 'priority-v1') throw new TypeError('Invalid policy version');\n if ('ruleId' in copy.policy) { identifier(copy.policy.ruleId); if (copy.policy.mode !== 'auto') throw new TypeError('Fixed rule'); }\n member(copy.decision, ['selected', 'abstained']); member(copy.reason, reasons);\n if (!Array.isArray(copy.candidates) || copy.candidates.length > 64) throw new TypeError('Invalid candidates');\n const seen = new Set<string>();\n for (const candidate of copy.candidates) {\n object(candidate, ['model', 'provider', 'modelId', 'status', 'code', 'transport', 'fingerprintDigest', 'authState', 'authSource']); model(candidate);\n if (seen.has(candidate.model as string)) throw new TypeError('Duplicate receipt candidate'); seen.add(candidate.model as string);\n member(candidate.status, ['eligible', 'excluded', 'not-evaluated']); member(candidate.code, codes);\n if ('transport' in candidate) member(candidate.transport, ['exec', 'control']);\n if ('fingerprintDigest' in candidate) hash(candidate.fingerprintDigest);\n if ('authState' in candidate) member(candidate.authState, ['authenticated', 'not-authenticated', 'unknown']);\n if ('authSource' in candidate) member(candidate.authSource, ['subscription', 'api-key', 'cloud-provider', 'oauth', 'oss', 'unknown']);\n if (candidate.status === 'eligible' && candidate.authState === 'not-authenticated') throw new TypeError('Eligible authentication is negative');\n if (candidate.status === 'eligible' ? candidate.code !== 'READY' || !candidate.transport || !candidate.fingerprintDigest\n : candidate.status === 'not-evaluated' ? !['NOT_NEEDED', 'NOT_IN_RULE'].includes(candidate.code as string)\n : ['READY', 'NOT_NEEDED', 'NOT_IN_RULE'].includes(candidate.code as string)) throw new TypeError('Inconsistent candidate status');\n }\n if ((copy.decision === 'selected') !== ('selected' in copy)) throw new TypeError('Inconsistent selection');\n const eligible = (copy.candidates as RoutingCandidate[]).filter(entry => entry.status === 'eligible');\n if (copy.decision === 'selected') {\n object(copy.selected, ['model', 'provider', 'modelId', 'transport', 'fingerprintDigest']); model(copy.selected);\n member(copy.selected.transport, ['exec', 'control']); hash(copy.selected.fingerprintDigest);\n if (eligible.length !== 1 || Object.keys(copy.selected).length !== 5\n || Object.entries(copy.selected).some(([key, entry]) => entry !== (eligible[0] as unknown as Record<string, unknown>)[key])) throw new TypeError('Selected candidate mismatch');\n if (!['FIXED', 'PRIORITY', 'RULE', 'FALLBACK'].includes(copy.reason as string)) throw new TypeError('Inconsistent selected reason');\n if (copy.policy.mode === 'fixed' ? copy.reason !== 'FIXED' || copy.candidates.length !== 1 : copy.reason === 'FIXED') throw new TypeError('Inconsistent policy reason');\n if (copy.reason === 'RULE' && !copy.policy.ruleId) throw new TypeError('Missing matching rule');\n if (copy.reason === 'PRIORITY' && copy.policy.ruleId) throw new TypeError('Matched rules require RULE or FALLBACK');\n } else if (eligible.length || ['FIXED', 'PRIORITY', 'RULE', 'FALLBACK'].includes(copy.reason as string)) throw new TypeError('Inconsistent abstention');\n if (copy.policy.mode === 'fixed' && (copy.candidates.length !== 1 || ['NO_CANDIDATES', 'NO_MATCHING_RULE'].includes(copy.reason as string))) throw new TypeError('Invalid fixed abstention');\n if (copy.reason === 'NO_MATCHING_RULE' && (copy.policy.mode !== 'auto' || copy.policy.ruleId || copy.candidates.length === 0)) throw new TypeError('Invalid no-rule abstention');\n if (copy.candidates.length === 0 && (copy.policy.ruleId || !['NO_CANDIDATES', 'ABORTED', 'TIMEOUT'].includes(copy.reason as string))) throw new TypeError('Invalid empty universe reason');\n if (['NO_ELIGIBLE_CANDIDATE', 'NO_MATCHING_RULE'].includes(copy.reason as string) && (copy.candidates as RoutingCandidate[]).some(candidate => candidate.code === 'NOT_NEEDED')) throw new TypeError('Unfinished candidate evaluation');\n if (copy.reason === 'NO_MATCHING_RULE' && (copy.candidates as RoutingCandidate[]).some(candidate => !['NOT_IN_RULE', 'PROVIDER_NOT_ALLOWED', 'MODEL_UNAVAILABLE', 'MODEL_UNVERIFIED'].includes(candidate.code))) throw new TypeError('Unmatched rules cannot probe candidates');\n if (copy.policy.mode === 'fixed' && (copy.candidates as RoutingCandidate[]).some(candidate => ['NOT_IN_RULE', 'PROVIDER_NOT_ALLOWED', 'MODEL_UNVERIFIED', 'AUTH_UNKNOWN'].includes(candidate.code))) throw new TypeError('Fixed candidate has an automatic-only exclusion');\n if (copy.reason === 'NO_CANDIDATES' && copy.candidates.length !== 0) throw new TypeError('Inconsistent empty universe');\n const { digest: expected, ...body } = copy;\n if (digest(body) !== expected) throw new TypeError('Receipt digest mismatch');\n return freeze(copy as unknown as RoutingReceipt);\n}\nexport function sealReceipt(value: Omit<RoutingReceipt, 'digest'>): RoutingReceipt { return validateRoutingReceipt({ ...value, digest: digest(value) }); }\nexport async function readRoutingReceipt(store: RoutingReceiptStore, id: string): Promise<RoutingReceipt | undefined> {\n identifier(id); const load = method<RoutingReceiptStore['load']>(store, 'load'); const result = await load(id);\n if (result === undefined) return undefined;\n const receipt = validateRoutingReceipt(result);\n if (receipt.id !== id) throw new TypeError('Receipt ID mismatch'); return receipt;\n}\n","import type { AgentOptions, AuthStatus, TransportKind } from '../public/types.js';\nimport type { Runtime } from '../core/runtime.js';\nexport interface RoutingTask { id: string; version: string; inputDigest: string; tags?: readonly string[] }\nexport interface RoutingRule { id: string; allTags: readonly string[]; models: readonly string[] }\nexport interface AutoModelSelection {\n mode: 'auto'; candidates?: readonly string[]; providers?: readonly string[];\n allowUnverifiedModels?: boolean; allowUnknownAuth?: boolean;\n rules?: readonly RoutingRule[]; fallback?: string;\n}\nexport type RoutingAgentDefinition = Omit<AgentOptions, 'model'> & { model: string | AutoModelSelection };\nexport interface CreateAgentContext {\n runtime: Runtime; receipts: RoutingReceiptStore; id?: string; task?: RoutingTask;\n sourceDigest?: string; signal?: AbortSignal; timeoutMs?: number;\n}\nexport type RoutingCandidateCode = 'READY' | 'NOT_NEEDED' | 'NOT_IN_RULE' | 'PROVIDER_NOT_ALLOWED' |\n 'MODEL_UNAVAILABLE' | 'MODEL_UNVERIFIED' | 'CLI_MISSING' | 'AUTH_REQUIRED' | 'AUTH_UNKNOWN' |\n 'SUBSCRIPTION_REQUIRED' | 'CLI_UNSUPPORTED' | 'POLICY_UNSUPPORTED' | 'PROBE_FAILED' | 'ABORTED' | 'TIMEOUT';\nexport interface RoutingCandidate {\n model: string; provider: string; modelId: string; status: 'eligible' | 'excluded' | 'not-evaluated'; code: RoutingCandidateCode;\n transport?: TransportKind; fingerprintDigest?: string; authState?: 'authenticated' | 'not-authenticated' | 'unknown'; authSource?: AuthStatus['source'];\n}\nexport interface RoutingSelected { model: string; provider: string; modelId: string; transport: TransportKind; fingerprintDigest: string }\nexport interface RoutingReceipt {\n format: 1; purpose: 'selection-proposal'; id: string; createdAt: number; configDigest: string; taskDigest: string;\n sourceDigest?: string; policy: { mode: 'fixed' | 'auto'; version: 'priority-v1'; ruleId?: string };\n decision: 'selected' | 'abstained'; reason: 'FIXED' | 'PRIORITY' | 'RULE' | 'FALLBACK' | 'NO_CANDIDATES' |\n 'NO_ELIGIBLE_CANDIDATE' | 'NO_MATCHING_RULE' | 'ABORTED' | 'TIMEOUT';\n candidates: readonly RoutingCandidate[]; nativeDispatches: 0; selected?: RoutingSelected; digest: string;\n}\n/** Implementations must atomically reject every existing ID, including identical proposals. */\nexport interface RoutingReceiptStore { save(receipt: RoutingReceipt): Promise<void>; load(id: string): Promise<RoutingReceipt | undefined> }\nexport class RoutingSelectionError extends Error {\n constructor(readonly code: 'NO_ROUTE' | 'ABORTED' | 'TIMEOUT', readonly receipt: RoutingReceipt) {\n super(`Routing selection ${code}`); this.name = 'RoutingSelectionError';\n }\n}\n","import { identity, validateCheckpoint } from '../orchestration/workflow/checkpoint.js';\nimport type { JsonValue, WorkflowDefinition, WorkflowStore } from '../orchestration/workflow/types.js';\nimport { identifier, jsonClone, method, object } from '../shared/json.js';\nimport { validateRoutingReceipt } from './receipt.js';\nimport type { RoutingReceipt, RoutingReceiptStore } from './types.js';\nconst envelope: WorkflowDefinition = { id: 'routing-receipt', version: '1', steps: [{ id: 'record', execute: () => null }] };\nexport class WorkflowRoutingReceiptStore implements RoutingReceiptStore {\n readonly #acquire: WorkflowStore['acquire'];\n constructor(store: WorkflowStore) { this.#acquire = method(store, 'acquire'); }\n async save(value: RoutingReceipt): Promise<void> {\n const receipt = validateRoutingReceipt(value); const runId = `routing:${receipt.id}`;\n const lease = await this.#acquire(runId);\n try {\n if (await lease.load() !== undefined) throw new Error('Routing receipt ID already exists');\n await lease.save({ format: 1, runId, workflow: identity(envelope), status: 'completed', steps: {\n record: { status: 'completed', attempts: 1, output: receipt as unknown as JsonValue },\n } });\n } finally { await lease.release(); }\n }\n async load(id: string): Promise<RoutingReceipt | undefined> {\n identifier(id); const runId = `routing:${id}`; const lease = await this.#acquire(runId);\n try {\n const loaded = await lease.load(); if (loaded === undefined) return undefined;\n const value = jsonClone(loaded);\n object(value, ['format', 'runId', 'workflow', 'status', 'steps']);\n object(value.workflow, ['id', 'version', 'fingerprint']); object(value.steps, ['record']);\n object(value.steps.record, ['status', 'attempts', 'output']);\n const checkpoint = validateCheckpoint(value, envelope, runId);\n if (checkpoint.status !== 'completed') throw new TypeError('Invalid routing envelope');\n const receipt = validateRoutingReceipt(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0 +1,433 @@
1
+ import { A as Agent } from '../../agent-Bj5YPrO7.js';
2
+ import { U as Usage, d as AgentOptions, a as Turn } from '../../types-DTFc1qO6.js';
3
+ import { R as Runtime } from '../../runtime-BSjrnxeF.js';
4
+ import { O as ObservedTaskBudget } from '../../index-B86C6VAD.js';
5
+ import { d as RoutingCandidateCode } from '../../types-CIqkKXix.js';
6
+ import '../../types-BB7KqceP.js';
7
+ import '../../provider-DX5Mf0uq.js';
8
+ import '../../errors-BNHvvjn9.js';
9
+ import '../../capture-runtime-GP6NZ2ee.js';
10
+
11
+ type PolicyRef = string | null;
12
+ type LearningSplit = 'train' | 'fixed' | 'fresh';
13
+ interface LearningFeatures {
14
+ schema: string;
15
+ values: readonly number[];
16
+ }
17
+ interface LearningTask {
18
+ id: string;
19
+ version: string;
20
+ inputDigest: string;
21
+ text: string;
22
+ features?: LearningFeatures;
23
+ }
24
+ type LearningEvidenceScope = 'model' | 'requested-system';
25
+ interface LearningArm {
26
+ evidenceScope?: LearningEvidenceScope;
27
+ id: string;
28
+ model: string;
29
+ effort?: string;
30
+ }
31
+ interface LearningDomain {
32
+ id: string;
33
+ sourceDigest: string;
34
+ scorerDigest: string;
35
+ protocolDigest: string;
36
+ }
37
+ interface LearningAction {
38
+ evidenceScope: LearningEvidenceScope;
39
+ id: string;
40
+ model: string;
41
+ provider: string;
42
+ modelId: string;
43
+ optionsDigest: string;
44
+ executionDigest: string;
45
+ key: string;
46
+ }
47
+ type LearningQuality = {
48
+ state: 'verified';
49
+ value: number;
50
+ passed: boolean;
51
+ } | {
52
+ state: 'unknown';
53
+ reason: string;
54
+ };
55
+ type LearningLatency = {
56
+ state: 'observed' | 'right-censored';
57
+ durationMs: number;
58
+ } | {
59
+ state: 'unknown';
60
+ };
61
+ interface LearningObservation {
62
+ format: 1;
63
+ id: string;
64
+ domain: string;
65
+ attemptId: string;
66
+ decisionId: string;
67
+ decisionDigest: string;
68
+ action: LearningAction;
69
+ taskDigest: string;
70
+ features: LearningFeatures;
71
+ split: LearningSplit;
72
+ episodeId?: string;
73
+ repetition?: number;
74
+ outcome: 'completed' | 'refused' | 'failed' | 'aborted' | 'timeout' | 'verifier-error' | 'identity-drift';
75
+ quality: LearningQuality;
76
+ latency: LearningLatency;
77
+ usage?: Usage;
78
+ observedModels?: readonly string[];
79
+ identityAfter?: string;
80
+ createdAt: number;
81
+ digest: string;
82
+ }
83
+ interface SequencedObservation {
84
+ sequence: number;
85
+ observation: LearningObservation;
86
+ }
87
+ interface LearningPolicyConfig {
88
+ objective: 'quality' | 'latency' | 'cost';
89
+ minDistinctTasks: number;
90
+ minSimilarity: number;
91
+ maxAgeMs: number;
92
+ halfLifeMs: number;
93
+ qualityFloor: number;
94
+ maxRows: number;
95
+ alpha: number;
96
+ minImprovement: number;
97
+ minFreshTasks: number;
98
+ }
99
+ interface LearningPolicyBinding {
100
+ definitionDigest: string;
101
+ actions: readonly LearningAction[];
102
+ fallbackId?: string;
103
+ features: {
104
+ schema: string;
105
+ dimensions: number;
106
+ };
107
+ }
108
+ interface LearningSnapshot {
109
+ binding?: LearningPolicyBinding;
110
+ format: 1;
111
+ domain: string;
112
+ config: LearningPolicyConfig;
113
+ through: number;
114
+ rows: readonly SequencedObservation[];
115
+ createdAt: number;
116
+ digest: string;
117
+ }
118
+ interface LearningPrediction {
119
+ actionKey: string;
120
+ support: number;
121
+ effectiveSupport: number;
122
+ meanQuality?: number;
123
+ lowerQuality?: number;
124
+ upperQuality?: number;
125
+ latencyMs?: number;
126
+ costUsd?: number;
127
+ costMeaning?: string;
128
+ reason: 'supported' | 'cold-start' | 'out-of-distribution' | 'stale' | 'unknown-metric';
129
+ }
130
+ interface LearningPointer {
131
+ generation: number;
132
+ active: PolicyRef;
133
+ previous: PolicyRef;
134
+ }
135
+ interface LearningCandidate {
136
+ id: string;
137
+ model: string;
138
+ provider: string;
139
+ modelId: string;
140
+ status: 'eligible' | 'excluded' | 'not-evaluated';
141
+ code: RoutingCandidateCode;
142
+ action?: LearningAction;
143
+ }
144
+ interface LearningDecision {
145
+ format: 1;
146
+ id: string;
147
+ domain: string;
148
+ createdAt: number;
149
+ taskDigest: string;
150
+ featuresDigest: string;
151
+ definitionDigest: string;
152
+ policy: PolicyRef;
153
+ mode: 'fixed' | 'auto' | 'matrix';
154
+ reason: 'FIXED' | 'INCUMBENT' | 'LEARNED' | 'MATRIX' | 'FALLBACK' | 'NO_ROUTE' | 'ABORTED' | 'TIMEOUT';
155
+ candidates: readonly LearningCandidate[];
156
+ predictions: readonly LearningPrediction[];
157
+ selected?: LearningAction;
158
+ nativeDispatches: 0;
159
+ digest: string;
160
+ }
161
+ interface LearningAttempt {
162
+ observationId: string;
163
+ format: 1;
164
+ id: string;
165
+ domain: string;
166
+ decisionId: string;
167
+ decisionDigest: string;
168
+ action: LearningAction;
169
+ taskDigest: string;
170
+ features: LearningFeatures;
171
+ split: LearningSplit;
172
+ episodeId?: string;
173
+ repetition?: number;
174
+ startedAt: number;
175
+ digest: string;
176
+ }
177
+ interface LearningEpisode {
178
+ format: 1;
179
+ id: string;
180
+ domain: string;
181
+ kind: 'fixed' | 'fresh';
182
+ createdAt: number;
183
+ definitionDigest: string;
184
+ protocolDigest: string;
185
+ afterSequence: number;
186
+ arms: readonly LearningAction[];
187
+ fallbackId?: string;
188
+ tasks: readonly {
189
+ taskDigest: string;
190
+ features: LearningFeatures;
191
+ }[];
192
+ repetitions: number;
193
+ cells: readonly {
194
+ taskDigest: string;
195
+ actionKey: string;
196
+ repetition: number;
197
+ attemptId: string;
198
+ observationId: string;
199
+ }[];
200
+ comparison?: {
201
+ expectedGeneration: number;
202
+ from: PolicyRef;
203
+ to: PolicyRef;
204
+ operation: 'promote' | 'rollback';
205
+ fixedEpisodeId: string;
206
+ config: LearningPolicyConfig;
207
+ configDigest: string;
208
+ };
209
+ digest: string;
210
+ }
211
+ interface LearningPairedTask {
212
+ taskDigest: string;
213
+ fromAction: string;
214
+ toAction: string;
215
+ qualityDelta?: number;
216
+ passRateDelta?: number;
217
+ objectiveGain?: number;
218
+ }
219
+ interface LearningAssessment {
220
+ episodeId: string;
221
+ episodeDigest: string;
222
+ observationDigests: readonly string[];
223
+ expectedCells: number;
224
+ verifiedCells: number;
225
+ tasks: readonly LearningPairedTask[];
226
+ wins: number;
227
+ losses: number;
228
+ ties: number;
229
+ pValue?: number;
230
+ meanGain?: number;
231
+ }
232
+ interface LearningGate {
233
+ format: 1;
234
+ id: string;
235
+ domain: string;
236
+ createdAt: number;
237
+ mode: 'promote' | 'rollback';
238
+ expectedGeneration: number;
239
+ from: PolicyRef;
240
+ to: PolicyRef;
241
+ definitionDigest: string;
242
+ configDigest: string;
243
+ outcome: 'keep' | 'promote' | 'rollback';
244
+ reason: 'SUPPORTED' | 'INCOMPLETE' | 'REGRESSION' | 'INSUFFICIENT' | 'INCOMPARABLE';
245
+ fixed: LearningAssessment;
246
+ fresh: LearningAssessment;
247
+ digest: string;
248
+ }
249
+ interface LearningGateCommit {
250
+ format: 1;
251
+ id: string;
252
+ domain: string;
253
+ gateDigest: string;
254
+ status: 'kept' | 'promoted' | 'rolled-back' | 'stale';
255
+ before: LearningPointer;
256
+ after: LearningPointer;
257
+ createdAt: number;
258
+ digest: string;
259
+ }
260
+ interface EvidenceMap {
261
+ decision: LearningDecision;
262
+ attempt: LearningAttempt;
263
+ snapshot: LearningSnapshot;
264
+ episode: LearningEpisode;
265
+ observation: LearningObservation;
266
+ gate: LearningGate;
267
+ 'gate-commit': LearningGateCommit;
268
+ }
269
+ type PutKind = 'decision' | 'attempt' | 'snapshot' | 'episode';
270
+ interface LearningStore {
271
+ put<K extends PutKind>(kind: K, id: string, row: EvidenceMap[K]): Promise<void>;
272
+ get<K extends keyof EvidenceMap>(kind: K, id: string): Promise<EvidenceMap[K] | undefined>;
273
+ highWater(domain: string): Promise<number>;
274
+ observations(domain: string, options?: {
275
+ through?: number;
276
+ split?: LearningSplit;
277
+ limit?: number;
278
+ verifiedOnly?: boolean;
279
+ schema?: string;
280
+ dimensions?: number;
281
+ actionKeys?: readonly string[];
282
+ observationIds?: readonly string[];
283
+ }): Promise<readonly SequencedObservation[]>;
284
+ appendObservation(value: LearningObservation): Promise<SequencedObservation>;
285
+ pointer(domain: string): Promise<LearningPointer>;
286
+ commitGate(value: LearningGate): Promise<LearningGateCommit>;
287
+ pending(domain: string): Promise<readonly LearningAttempt[]>;
288
+ close(): void;
289
+ }
290
+ type LearningDefinition = Omit<AgentOptions, 'model'> & {
291
+ model: string | {
292
+ mode: 'auto';
293
+ candidates: readonly LearningArm[];
294
+ fallback?: string;
295
+ providers?: readonly string[];
296
+ allowUnverifiedModels?: boolean;
297
+ allowUnknownAuth?: boolean;
298
+ };
299
+ };
300
+ interface LearningContext {
301
+ runtime: Runtime;
302
+ task: LearningTask;
303
+ id?: string;
304
+ signal?: AbortSignal;
305
+ timeoutMs?: number;
306
+ evaluationArmId?: string;
307
+ }
308
+ interface LearningRunContext extends LearningContext {
309
+ /** Optional exact execution universe; checked after admission/preparation, before durable start. */
310
+ expectedBinding?: LearningPolicyBinding;
311
+ input: string;
312
+ verify: (turn: Turn) => Promise<{
313
+ value: number;
314
+ passed: boolean;
315
+ }> | {
316
+ value: number;
317
+ passed: boolean;
318
+ };
319
+ split?: LearningSplit;
320
+ episodeId?: string;
321
+ repetition?: number;
322
+ attemptId?: string;
323
+ observationId?: string;
324
+ budget: ObservedTaskBudget;
325
+ maintenanceTimeoutMs?: number;
326
+ maintenance?: (context: {
327
+ signal: AbortSignal;
328
+ }) => Promise<void>;
329
+ }
330
+ interface LearningRunResult {
331
+ turn: Turn;
332
+ receipt: LearningDecision;
333
+ observation: LearningObservation;
334
+ shadow: LearningSnapshot;
335
+ maintenance: {
336
+ status: 'not-requested' | 'completed' | 'failed';
337
+ code?: string;
338
+ };
339
+ }
340
+ interface LearningGateOptions {
341
+ id: string;
342
+ freshEpisodeId: string;
343
+ }
344
+ interface LearningPreflight {
345
+ domain: string;
346
+ definitionDigest: string;
347
+ actions: readonly LearningAction[];
348
+ candidates: readonly LearningCandidate[];
349
+ fallbackId?: string;
350
+ }
351
+
352
+ /** Optional local evidence router. Its ledger never grants execution authority. */
353
+ declare class LearningRouter {
354
+ #private;
355
+ constructor(options: {
356
+ store: LearningStore;
357
+ domain: LearningDomain;
358
+ policy?: Partial<LearningPolicyConfig>;
359
+ });
360
+ preflight(definition: LearningDefinition, context: LearningContext): Promise<LearningPreflight>;
361
+ createAgent(definition: LearningDefinition, context: LearningContext): Promise<{
362
+ agent: Agent;
363
+ receipt: LearningDecision;
364
+ }>;
365
+ run(definition: LearningDefinition, context: LearningRunContext): Promise<LearningRunResult>;
366
+ shadow(definition: LearningDefinition, context: LearningContext): Promise<LearningSnapshot>;
367
+ improve(options: LearningGateOptions): Promise<LearningGateCommit>;
368
+ inspect(): Promise<{
369
+ generation: number;
370
+ active: string | null;
371
+ previous: string | null;
372
+ }>;
373
+ }
374
+
375
+ /** Durable local evidence. Every transaction is synchronous: no callback/await crosses a SQLite lock. */
376
+ declare class SqliteLearningStore implements LearningStore {
377
+ #private;
378
+ constructor(path: string, options?: {
379
+ busyTimeoutMs?: number;
380
+ });
381
+ put<K extends PutKind>(kind: K, id: string, value: EvidenceMap[K]): Promise<void>;
382
+ get<K extends keyof EvidenceMap>(kind: K, id: string): Promise<EvidenceMap[K] | undefined>;
383
+ highWater(domain: string): Promise<number>;
384
+ observations(domain: string, options?: {
385
+ through?: number;
386
+ split?: LearningSplit;
387
+ limit?: number;
388
+ verifiedOnly?: boolean;
389
+ schema?: string;
390
+ dimensions?: number;
391
+ actionKeys?: readonly string[];
392
+ observationIds?: readonly string[];
393
+ }): Promise<readonly SequencedObservation[]>;
394
+ appendObservation(value: LearningObservation): Promise<SequencedObservation>;
395
+ pointer(domain: string): Promise<LearningPointer>;
396
+ pending(domain: string): Promise<readonly LearningAttempt[]>;
397
+ commitGate(value: LearningGate): Promise<LearningGateCommit>;
398
+ close(): void;
399
+ }
400
+
401
+ /** Exact executable UTF-8 identity; normalization is only used for contextual features. */
402
+ declare function inputDigest(text: string): string;
403
+ /** Transparent signed hashing of local word and character ngrams, never task IDs. */
404
+ declare function hashTaskFeatures(text: string): LearningFeatures;
405
+
406
+ declare const DEFAULT_LEARNING_POLICY: Readonly<LearningPolicyConfig>;
407
+ declare function buildSnapshot(domain: string, config: LearningPolicyConfig, through: number, rows: readonly SequencedObservation[], createdAt: number, binding?: LearningPolicyBinding): LearningSnapshot;
408
+ declare function predict(snapshot: LearningSnapshot, features: LearningFeatures, actions: readonly LearningAction[], asOf: number): readonly LearningPrediction[];
409
+ /** Preserve the public action-only selector; both APIs share one ranking/fallback determination. */
410
+ declare function selectPolicy(snapshot: LearningSnapshot | undefined, orderedActions: readonly LearningAction[], features: LearningFeatures, asOf: number, fallbackId?: string): LearningAction | undefined;
411
+
412
+ declare function learningDomainDigest(value: LearningDomain): string;
413
+ declare function validateFeatures(value: unknown): LearningFeatures;
414
+ declare function validatePolicyConfig(value: unknown): LearningPolicyConfig;
415
+ /** Only exact immutable objects produced here are trusted on subsequent reads. External frozen values still validate fully. */
416
+ declare function validateLearningRecord<K extends keyof EvidenceMap>(kind: K, value: unknown): EvidenceMap[K];
417
+ declare function sealLearningRecord<K extends keyof EvidenceMap>(kind: K, body: Omit<EvidenceMap[K], 'digest'>): EvidenceMap[K];
418
+
419
+ interface GateEvidenceInput {
420
+ id: string;
421
+ createdAt: number;
422
+ domain: string;
423
+ fresh: LearningEpisode;
424
+ fixed: LearningEpisode;
425
+ fromSnapshot?: LearningSnapshot;
426
+ toSnapshot?: LearningSnapshot;
427
+ observations: readonly SequencedObservation[];
428
+ }
429
+ declare function assessGateEvidence(value: GateEvidenceInput): LearningGate;
430
+
431
+ declare function digest(value: unknown): string;
432
+
433
+ export { DEFAULT_LEARNING_POLICY, type EvidenceMap, type LearningAction, type LearningArm, type LearningAssessment, type LearningAttempt, type LearningCandidate, type LearningContext, type LearningDecision, type LearningDefinition, type LearningDomain, type LearningEpisode, type LearningEvidenceScope, type LearningFeatures, type LearningGate, type LearningGateCommit, type LearningGateOptions, type LearningLatency, type LearningObservation, type LearningPairedTask, type LearningPointer, type LearningPolicyBinding, type LearningPolicyConfig, type LearningPrediction, type LearningPreflight, type LearningQuality, LearningRouter, type LearningRunContext, type LearningRunResult, type LearningSnapshot, type LearningSplit, type LearningStore, type LearningTask, type PolicyRef, type PutKind, type SequencedObservation, SqliteLearningStore, assessGateEvidence, buildSnapshot, hashTaskFeatures, inputDigest, digest as learningDigest, learningDomainDigest, predict, sealLearningRecord, selectPolicy, validateFeatures, validateLearningRecord, validatePolicyConfig };