hiveagents-runtime 0.1.0-beta.1 → 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 (62) hide show
  1. package/README.md +9 -5
  2. package/dist/adapter-kit.d.ts +4 -4
  3. package/dist/adapter-kit.js +2 -1
  4. package/dist/{agent-D0HS38G3.d.ts → agent-Bj5YPrO7.d.ts} +2 -2
  5. package/dist/{agent-OLSXNGNN.js → agent-D6OXR7UF.js} +9 -8
  6. package/dist/{agent-readiness-V36OJME4.js → agent-readiness-KSGNKTGK.js} +3 -3
  7. package/dist/chunk-2RK74GCA.js +2397 -0
  8. package/dist/chunk-2RK74GCA.js.map +1 -0
  9. package/dist/chunk-6FIXXWNM.js +1 -0
  10. package/dist/{chunk-ALLOMOUN.js → chunk-DAXPAV2L.js} +2 -2
  11. package/dist/{chunk-3B3JW4U3.js → chunk-DQEMIGKC.js} +5 -5
  12. package/dist/{chunk-SRJUZJKV.js → chunk-G6JV7WV6.js} +2 -2
  13. package/dist/{chunk-SRJUZJKV.js.map → chunk-G6JV7WV6.js.map} +1 -1
  14. package/dist/{chunk-TIZKGD4R.js → chunk-RH5A5U7G.js} +2 -2
  15. package/dist/{chunk-DBFXFWQZ.js → chunk-RX3XZENU.js} +93 -93
  16. package/dist/chunk-RX3XZENU.js.map +1 -0
  17. package/dist/{chunk-2RUEC63U.js → chunk-TWGEYWMO.js} +2 -2
  18. package/dist/{chunk-GJ4FTDBJ.js → chunk-UZPDDQVJ.js} +6 -6
  19. package/dist/{chunk-COKYQUTK.js → chunk-WVT5SEKC.js} +2 -2
  20. package/dist/cli.js +9 -8
  21. package/dist/cli.js.map +1 -1
  22. package/dist/{errors-DgehLwqI.d.ts → errors-BNHvvjn9.d.ts} +1 -1
  23. package/dist/{execution-halt-CW0Oi9s9.d.ts → execution-halt-B8G0fOKS.d.ts} +1 -1
  24. package/dist/{execution-types-UJ6gAF48.d.ts → execution-types-ClYYqPQP.d.ts} +1 -1
  25. package/dist/hosted-runtime.d.ts +3 -3
  26. package/dist/hosted-runtime.js +5 -4
  27. package/dist/hosted-runtime.js.map +1 -1
  28. package/dist/index.d.ts +25 -8
  29. package/dist/index.js +16 -9
  30. package/dist/index.js.map +1 -1
  31. package/dist/orchestration/dynamic.d.ts +3 -3
  32. package/dist/orchestration/dynamic.js +4 -4
  33. package/dist/orchestration/index.d.ts +7 -7
  34. package/dist/orchestration/index.js +19 -13
  35. package/dist/orchestration/index.js.map +1 -1
  36. package/dist/orchestration/log.d.ts +4 -4
  37. package/dist/{provider-XCpWjJ6a.d.ts → provider-DX5Mf0uq.d.ts} +1 -1
  38. package/dist/routing/index.d.ts +6 -6
  39. package/dist/routing/index.js +9 -8
  40. package/dist/routing/index.js.map +1 -1
  41. package/dist/routing/learning/index.d.ts +5 -5
  42. package/dist/routing/learning/index.js +9 -8
  43. package/dist/routing/learning/index.js.map +1 -1
  44. package/dist/{runtime-C6Cu2fvw.d.ts → runtime-BSjrnxeF.d.ts} +2 -2
  45. package/dist/{runtime-Y72XJFFO.js → runtime-OISPXS4I.js} +6 -5
  46. package/dist/runtime-OISPXS4I.js.map +1 -0
  47. package/dist/{types-BBRKjIc7.d.ts → types-CIqkKXix.d.ts} +1 -1
  48. package/docs/releases/0.1.0-beta.3.md +13 -0
  49. package/package.json +3 -3
  50. package/dist/chunk-C2DN6KL4.js +0 -853
  51. package/dist/chunk-C2DN6KL4.js.map +0 -1
  52. package/dist/chunk-DBFXFWQZ.js.map +0 -1
  53. package/docs/releases/0.1.0-beta.1.md +0 -13
  54. /package/dist/{agent-OLSXNGNN.js.map → agent-D6OXR7UF.js.map} +0 -0
  55. /package/dist/{agent-readiness-V36OJME4.js.map → agent-readiness-KSGNKTGK.js.map} +0 -0
  56. /package/dist/{runtime-Y72XJFFO.js.map → chunk-6FIXXWNM.js.map} +0 -0
  57. /package/dist/{chunk-ALLOMOUN.js.map → chunk-DAXPAV2L.js.map} +0 -0
  58. /package/dist/{chunk-3B3JW4U3.js.map → chunk-DQEMIGKC.js.map} +0 -0
  59. /package/dist/{chunk-TIZKGD4R.js.map → chunk-RH5A5U7G.js.map} +0 -0
  60. /package/dist/{chunk-2RUEC63U.js.map → chunk-TWGEYWMO.js.map} +0 -0
  61. /package/dist/{chunk-GJ4FTDBJ.js.map → chunk-UZPDDQVJ.js.map} +0 -0
  62. /package/dist/{chunk-COKYQUTK.js.map → chunk-WVT5SEKC.js.map} +0 -0
@@ -3,13 +3,13 @@ export { e as LogEntry, f as LogPayloadVerifier, g as LogStoreError, h as LogSto
3
3
  import { c as LogCommit, b as LogReceipt, R as RunIdentity, L as LogPosition } from '../types-BB7KqceP.js';
4
4
  export { a as LogDraft, d as LogJsonValue, P as PayloadReference } from '../types-BB7KqceP.js';
5
5
  import { DatabaseSync } from 'node:sqlite';
6
- import { L as LogExecutionDatabaseOptions, E as ExecutionOwnership, S as StandaloneStoppedAcknowledgement, D as DecisionBinding, C as CapturedEffectAssociation, a as DecisionRecord, b as DecisionStore, M as ManagedEffectAssociation, c as DecisionLease, T as TraceEventInput } from '../execution-types-UJ6gAF48.js';
7
- export { d as ExecutionArtifactStore, e as LogArtifactBinding, f as LogArtifactOptions, g as LogArtifactReadOptions, h as LogArtifactVerification, i as LogArtifactWriteOptions, j as LogExecutionError, k as LogExecutionFailure, l as createLogArtifactStore } from '../execution-types-UJ6gAF48.js';
6
+ import { L as LogExecutionDatabaseOptions, E as ExecutionOwnership, S as StandaloneStoppedAcknowledgement, D as DecisionBinding, C as CapturedEffectAssociation, a as DecisionRecord, b as DecisionStore, M as ManagedEffectAssociation, c as DecisionLease, T as TraceEventInput } from '../execution-types-ClYYqPQP.js';
7
+ export { d as ExecutionArtifactStore, e as LogArtifactBinding, f as LogArtifactOptions, g as LogArtifactReadOptions, h as LogArtifactVerification, i as LogArtifactWriteOptions, j as LogExecutionError, k as LogExecutionFailure, l as createLogArtifactStore } from '../execution-types-ClYYqPQP.js';
8
8
  import { J as JsonValue, W as WorkflowStore, a as WorkflowDefinition, b as WorkflowLease } from '../types-DYex3p7_.js';
9
9
  export { a as RequiredLogCapture, b as RequiredLogCaptureOptions, R as RuntimeCaptureOptions, c as createRequiredLogCapture } from '../capture-runtime-GP6NZ2ee.js';
10
10
  import { U as Usage } from '../types-DTFc1qO6.js';
11
- import '../execution-halt-CW0Oi9s9.js';
12
- import '../errors-DgehLwqI.js';
11
+ import '../execution-halt-B8G0fOKS.js';
12
+ import '../errors-BNHvvjn9.js';
13
13
 
14
14
  /** Exclusive standalone connection. SQLite locking and transactions own durability, not this queue. */
15
15
  declare class SqliteRunLogStore {
@@ -1,5 +1,5 @@
1
1
  import { P as ProviderId, b as TransportKind, C as CapabilitySupport, e as ProviderInstallation, c as AuthStatus, M as ModelInfo, U as Usage, A as AgentEvent } from './types-DTFc1qO6.js';
2
- import { A as AgentRuntimeError, F as FailureClassification } from './errors-DgehLwqI.js';
2
+ import { A as AgentRuntimeError, F as FailureClassification } from './errors-BNHvvjn9.js';
3
3
 
4
4
  interface CompatibilityEntry {
5
5
  provider: ProviderId;
@@ -1,13 +1,13 @@
1
- import { A as Agent } from '../agent-D0HS38G3.js';
2
- import { R as RoutingAgentDefinition, C as CreateAgentContext, a as RoutingReceipt, b as RoutingReceiptStore } from '../types-BBRKjIc7.js';
3
- export { A as AutoModelSelection, c as RoutingCandidate, d as RoutingCandidateCode, e as RoutingRule, f as RoutingSelected, g as RoutingSelectionError, h as RoutingTask } from '../types-BBRKjIc7.js';
1
+ import { A as Agent } from '../agent-Bj5YPrO7.js';
2
+ import { R as RoutingAgentDefinition, C as CreateAgentContext, a as RoutingReceipt, b as RoutingReceiptStore } from '../types-CIqkKXix.js';
3
+ export { A as AutoModelSelection, c as RoutingCandidate, d as RoutingCandidateCode, e as RoutingRule, f as RoutingSelected, g as RoutingSelectionError, h as RoutingTask } from '../types-CIqkKXix.js';
4
4
  import { W as WorkflowStore } from '../types-DYex3p7_.js';
5
5
  import '../types-BB7KqceP.js';
6
- import '../runtime-C6Cu2fvw.js';
6
+ import '../runtime-BSjrnxeF.js';
7
7
  import '../capture-runtime-GP6NZ2ee.js';
8
8
  import '../types-DTFc1qO6.js';
9
- import '../provider-XCpWjJ6a.js';
10
- import '../errors-DgehLwqI.js';
9
+ import '../provider-DX5Mf0uq.js';
10
+ import '../errors-BNHvvjn9.js';
11
11
 
12
12
  /** Resolve once locally. Never creates a session, dispatches a prompt, or retries execution. */
13
13
  declare function createAgent(definition: RoutingAgentDefinition, context: CreateAgentContext): Promise<{
@@ -1,28 +1,29 @@
1
1
  import {
2
2
  normalize
3
- } from "../chunk-TIZKGD4R.js";
3
+ } from "../chunk-RH5A5U7G.js";
4
4
  import {
5
5
  Agent
6
- } from "../chunk-GJ4FTDBJ.js";
6
+ } from "../chunk-UZPDDQVJ.js";
7
7
  import "../chunk-HZFZX5A3.js";
8
- import "../chunk-COKYQUTK.js";
8
+ import "../chunk-WVT5SEKC.js";
9
9
  import "../chunk-3TIYA3K5.js";
10
10
  import {
11
11
  Runtime
12
- } from "../chunk-C2DN6KL4.js";
12
+ } from "../chunk-2RK74GCA.js";
13
13
  import "../chunk-J7VAYJKM.js";
14
14
  import {
15
15
  OperationScope,
16
16
  authenticationState
17
- } from "../chunk-SRJUZJKV.js";
17
+ } from "../chunk-G6JV7WV6.js";
18
+ import "../chunk-6FIXXWNM.js";
18
19
  import {
19
20
  identity,
20
21
  validateCheckpoint
21
22
  } from "../chunk-CPN4DOXH.js";
22
- import "../chunk-ALLOMOUN.js";
23
+ import "../chunk-DAXPAV2L.js";
23
24
  import "../chunk-6XIJW65Q.js";
24
25
  import "../chunk-RXU2Q2HF.js";
25
- import "../chunk-2RUEC63U.js";
26
+ import "../chunk-TWGEYWMO.js";
26
27
  import "../chunk-GS5U3KUN.js";
27
28
  import {
28
29
  canonical,
@@ -35,7 +36,7 @@ import {
35
36
  object,
36
37
  ownObject
37
38
  } from "../chunk-EEUYQFCP.js";
38
- import "../chunk-DBFXFWQZ.js";
39
+ import "../chunk-RX3XZENU.js";
39
40
  import "../chunk-7LDQKJKI.js";
40
41
  import {
41
42
  rethrowExecutionHalt
@@ -1 +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(checkpoint.steps.record!.output);\n if (receipt.id !== id) throw new TypeError('Receipt ID mismatch'); return receipt;\n } finally { await lease.release(); }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;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KAAK;AACvC,QAAI;AACF,UAAI,MAAM,MAAM,KAAK,MAAM,OAAW,OAAM,IAAI,MAAM,mCAAmC;AACzF,YAAM,MAAM,KAAK,EAAE,QAAQ,GAAG,OAAO,UAAU,SAAS,QAAQ,GAAG,QAAQ,aAAa,OAAO;AAAA,QAC7F,QAAQ,EAAE,QAAQ,aAAa,UAAU,GAAG,QAAQ,QAAgC;AAAA,MACtF,EAAE,CAAC;AAAA,IACL,UAAE;AAAU,YAAM,MAAM,QAAQ;AAAA,IAAG;AAAA,EACrC;AAAA,EACA,MAAM,KAAK,IAAiD;AAC1D,eAAW,EAAE;AAAG,UAAM,QAAQ,WAAW,EAAE;AAAI,UAAM,QAAQ,MAAM,KAAK,SAAS,KAAK;AACtF,QAAI;AACF,YAAM,SAAS,MAAM,MAAM,KAAK;AAAG,UAAI,WAAW,OAAW,QAAO;AACpE,YAAM,QAAQ,UAAU,MAAM;AAC9B,aAAO,OAAO,CAAC,UAAU,SAAS,YAAY,UAAU,OAAO,CAAC;AAChE,aAAO,MAAM,UAAU,CAAC,MAAM,WAAW,aAAa,CAAC;AAAG,aAAO,MAAM,OAAO,CAAC,QAAQ,CAAC;AACxF,aAAO,MAAM,MAAM,QAAQ,CAAC,UAAU,YAAY,QAAQ,CAAC;AAC3D,YAAM,aAAa,mBAAmB,OAAO,UAAU,KAAK;AAC5D,UAAI,WAAW,WAAW,YAAa,OAAM,IAAI,UAAU,0BAA0B;AACrF,YAAM,UAAU,uBAAuB,WAAW,MAAM,OAAQ,MAAM;AACtE,UAAI,QAAQ,OAAO,GAAI,OAAM,IAAI,UAAU,qBAAqB;AAAG,aAAO;AAAA,IAC5E,UAAE;AAAU,YAAM,MAAM,QAAQ;AAAA,IAAG;AAAA,EACrC;AACF;","names":["model"]}
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(checkpoint.steps.record!.output);\n if (receipt.id !== id) throw new TypeError('Receipt ID mismatch'); return receipt;\n } finally { await lease.release(); }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,aAAa;AACtB,SAAS,kBAAkB;;;ACA3B,IAAM,QAAQ,CAAC,SAAS,cAAc,eAAe,wBAAwB,qBAAqB,oBAAoB,eAAe,iBAAiB,gBAAgB,yBAAyB,mBAAmB,sBAAsB,gBAAgB,WAAW,SAAS;AAC5Q,IAAM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AAU,GAAG,QAAQ,QAAgC;AAAA,MACtF,EAAE,CAAC;AAAA,IACL,UAAE;AAAU,YAAM,MAAM,QAAQ;AAAA,IAAG;AAAA,EACrC;AAAA,EACA,MAAM,KAAK,IAAiD;AAC1D,eAAW,EAAE;AAAG,UAAM,QAAQ,WAAW,EAAE;AAAI,UAAM,QAAQ,MAAM,KAAK,SAAS,KAAK;AACtF,QAAI;AACF,YAAM,SAAS,MAAM,MAAM,KAAK;AAAG,UAAI,WAAW,OAAW,QAAO;AACpE,YAAM,QAAQ,UAAU,MAAM;AAC9B,aAAO,OAAO,CAAC,UAAU,SAAS,YAAY,UAAU,OAAO,CAAC;AAChE,aAAO,MAAM,UAAU,CAAC,MAAM,WAAW,aAAa,CAAC;AAAG,aAAO,MAAM,OAAO,CAAC,QAAQ,CAAC;AACxF,aAAO,MAAM,MAAM,QAAQ,CAAC,UAAU,YAAY,QAAQ,CAAC;AAC3D,YAAM,aAAa,mBAAmB,OAAO,UAAU,KAAK;AAC5D,UAAI,WAAW,WAAW,YAAa,OAAM,IAAI,UAAU,0BAA0B;AACrF,YAAM,UAAU,uBAAuB,WAAW,MAAM,OAAQ,MAAM;AACtE,UAAI,QAAQ,OAAO,GAAI,OAAM,IAAI,UAAU,qBAAqB;AAAG,aAAO;AAAA,IAC5E,UAAE;AAAU,YAAM,MAAM,QAAQ;AAAA,IAAG;AAAA,EACrC;AACF;","names":["model"]}
@@ -1,11 +1,11 @@
1
- import { A as Agent } from '../../agent-D0HS38G3.js';
1
+ import { A as Agent } from '../../agent-Bj5YPrO7.js';
2
2
  import { U as Usage, d as AgentOptions, a as Turn } from '../../types-DTFc1qO6.js';
3
- import { R as Runtime } from '../../runtime-C6Cu2fvw.js';
3
+ import { R as Runtime } from '../../runtime-BSjrnxeF.js';
4
4
  import { O as ObservedTaskBudget } from '../../index-B86C6VAD.js';
5
- import { d as RoutingCandidateCode } from '../../types-BBRKjIc7.js';
5
+ import { d as RoutingCandidateCode } from '../../types-CIqkKXix.js';
6
6
  import '../../types-BB7KqceP.js';
7
- import '../../provider-XCpWjJ6a.js';
8
- import '../../errors-DgehLwqI.js';
7
+ import '../../provider-DX5Mf0uq.js';
8
+ import '../../errors-BNHvvjn9.js';
9
9
  import '../../capture-runtime-GP6NZ2ee.js';
10
10
 
11
11
  type PolicyRef = string | null;
@@ -1,25 +1,26 @@
1
1
  import {
2
2
  normalize
3
- } from "../../chunk-TIZKGD4R.js";
3
+ } from "../../chunk-RH5A5U7G.js";
4
4
  import {
5
5
  Agent
6
- } from "../../chunk-GJ4FTDBJ.js";
6
+ } from "../../chunk-UZPDDQVJ.js";
7
7
  import "../../chunk-HZFZX5A3.js";
8
- import "../../chunk-COKYQUTK.js";
8
+ import "../../chunk-WVT5SEKC.js";
9
9
  import "../../chunk-3TIYA3K5.js";
10
- import "../../chunk-C2DN6KL4.js";
10
+ import "../../chunk-2RK74GCA.js";
11
11
  import "../../chunk-J7VAYJKM.js";
12
12
  import {
13
13
  OperationScope,
14
14
  authenticationState
15
- } from "../../chunk-SRJUZJKV.js";
15
+ } from "../../chunk-G6JV7WV6.js";
16
+ import "../../chunk-6FIXXWNM.js";
16
17
  import {
17
18
  runObservedTask
18
19
  } from "../../chunk-GFVYNPLS.js";
19
- import "../../chunk-ALLOMOUN.js";
20
+ import "../../chunk-DAXPAV2L.js";
20
21
  import "../../chunk-6XIJW65Q.js";
21
22
  import "../../chunk-RXU2Q2HF.js";
22
- import "../../chunk-2RUEC63U.js";
23
+ import "../../chunk-TWGEYWMO.js";
23
24
  import "../../chunk-GS5U3KUN.js";
24
25
  import {
25
26
  canonical,
@@ -34,7 +35,7 @@ import {
34
35
  snapshot,
35
36
  strings
36
37
  } from "../../chunk-EEUYQFCP.js";
37
- import "../../chunk-DBFXFWQZ.js";
38
+ import "../../chunk-RX3XZENU.js";
38
39
  import "../../chunk-7LDQKJKI.js";
39
40
  import {
40
41
  isExecutionHalted,