@opengeni/subscriptions 2.0.1 → 2.0.2-canary.38789554071001

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/quota.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ModelId, SubscriptionConnection, SubscriptionQuota } from "./types.js";
1
+ import type { ModelId, QuotaBlockClaim, SubscriptionConnection, SubscriptionQuota } from "./types.js";
2
2
  /**
3
3
  * What the shared quota model says about a connection's capacity now
4
4
  * (design 2.2). `unknown` is never treated as available or exhausted
@@ -30,6 +30,23 @@ export type QuotaCapacity = {
30
30
  export declare function quotaCapacity(quota: SubscriptionQuota | null, now: number, staleAfterMs?: number): QuotaCapacity;
31
31
  /** End of a model-specific cooldown that is still running, else null. */
32
32
  export declare function modelCooldownUntil(quota: SubscriptionQuota | null, modelId: ModelId, now: number): number | null;
33
+ /** One stored block a usage reading may end: a model cooldown, or (model null) the exhaustion deadline. */
34
+ export type SubscriptionQuotaBlock = {
35
+ modelId: ModelId | null;
36
+ until: number;
37
+ /** Its claim, only while it still explains this exact deadline. */
38
+ claim: QuotaBlockClaim | null;
39
+ };
40
+ /**
41
+ * The claim of a stored block (a model's cooldown, or with `modelId` null
42
+ * the exhaustion deadline), only while it is tied to the block's current
43
+ * deadline; null otherwise (fail closed).
44
+ */
45
+ export declare function quotaBlockClaim(quota: Pick<SubscriptionQuota, "modelCooldowns" | "modelCooldownClaims" | "exhaustedUntil" | "exhaustedClaim">, modelId: ModelId | null): QuotaBlockClaim | null;
46
+ /** The quota document a store writes: claims only while they explain a block. */
47
+ export type StoredQuotaDocument = Pick<SubscriptionQuota, "windows" | "modelCooldowns" | "modelCooldownClaims" | "exhaustedUntil" | "exhaustedKind" | "exhaustedClaim" | "source">;
48
+ /** The stored document of one quota (a claim that no longer explains its block is dropped). */
49
+ export declare function storedQuotaDocument(quota: SubscriptionQuota): StoredQuotaDocument;
33
50
  /**
34
51
  * A quota observation applies only to the credential generation it was made
35
52
  * with, so a refusal seen before a refresh cannot quarantine the renewed
@@ -147,7 +147,7 @@ export type World = {
147
147
  cacheTtlMs: Record<ProviderId, number>;
148
148
  };
149
149
  export type SwitchKind = "initial" | "sticky" | "pinned" | "reselected_cold" | "failover_same_provider" | "failover_cross_provider" | "return_to_preferred";
150
- export type WaitReason = "pinned_account_unavailable"
150
+ export type WaitReason = "pinned_account_unavailable" | "pinned_account_disabled"
151
151
  /** The explicit choice can never serve this work until a person changes something (D-24). */
152
152
  | "pinned_account_ineligible" | "no_eligible_capacity" | "model_not_allowed"
153
153
  /** Decided before placement (an unusable accepted authority); never produced here. */
package/dist/reference.js CHANGED
@@ -221,6 +221,14 @@ function pinnedNeverServes(world, session, pinned) {
221
221
  }
222
222
  return !isAuthorized(world, session, { ...pinned, healthy: true, allocatorEnabled: true });
223
223
  }
224
+ function pinnedAllocationDisabled(world, session, pinned) {
225
+ if (!pinned.allocatorEnabled) return true;
226
+ if (pinned.assignmentPolicies === void 0) return false;
227
+ const source = effectiveSettings(world.settings, session.workspaceId).values.inferenceSource?.[pinned.provider] ?? "automatic";
228
+ return !pinned.assignmentPolicies.some(
229
+ (policy) => policy.workspaceId === session.workspaceId && (source === "automatic" || policy.inferencePool === source) && policy.allocatorEnabled
230
+ );
231
+ }
224
232
  function futureResetTimes(world, now) {
225
233
  const times = /* @__PURE__ */ new Set();
226
234
  for (const connection of world.connections) {
@@ -270,6 +278,9 @@ function decide(world, sessionId, now) {
270
278
  if (pinnedNeverServes(world, session, pinned)) {
271
279
  return { kind: "wait", reason: "pinned_account_ineligible", earliestResetAt: null };
272
280
  }
281
+ if (pinned && pinnedAllocationDisabled(world, session, pinned)) {
282
+ return { kind: "wait", reason: "pinned_account_disabled", earliestResetAt: null };
283
+ }
273
284
  return {
274
285
  kind: "wait",
275
286
  reason: "pinned_account_unavailable",
@@ -422,7 +433,7 @@ function checkDecision(world, sessionId, now, decision) {
422
433
  }
423
434
  const allowedModels = models.filter((modelId) => modelAllowed(world, session, modelId));
424
435
  const never = !!session.pinnedConnectionId && pinnedNeverServes(world, session, pinned);
425
- const expectedReason = allowedModels.length === 0 ? "model_not_allowed" : session.pinnedConnectionId ? never ? "pinned_account_ineligible" : "pinned_account_unavailable" : "no_eligible_capacity";
436
+ const expectedReason = allowedModels.length === 0 ? "model_not_allowed" : session.pinnedConnectionId ? never ? "pinned_account_ineligible" : pinned && pinnedAllocationDisabled(world, session, pinned) ? "pinned_account_disabled" : "pinned_account_unavailable" : "no_eligible_capacity";
426
437
  if (decision.reason !== expectedReason) {
427
438
  fail(
428
439
  never && decision.reason === "pinned_account_unavailable" ? "SUB-ACCESS-06" : "SUB-WAIT-02",
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/reference-model.ts","../src/reference-bridge.ts"],"sourcesContent":["/**\n * Independent executable reference model of the subscription account contract\n * (docs/subscription-accounts.md). It is written from the contract, not from\n * the production selection code, so conformance tests can compare production\n * decisions against it. Everything here is pure and deterministic: no clock,\n * database or randomness.\n *\n * It ships in `@opengeni/subscriptions` only so the worker's shadow comparison\n * can run `checkDecision` in production; it is published through the separate\n * `@opengeni/subscriptions/reference` entry point, and the placement modules of\n * this package never import it (a test enforces both directions).\n *\n * The model answers one question: given the world and a session that wants to\n * run a turn now, which account and model must it run on, or why must it wait?\n */\n\nexport type ProviderId = string;\nexport type ModelId = string;\n\nexport type Rotation =\n | { mode: \"primary_first\"; primaryConnectionId: string | null }\n | { mode: \"spread\" };\n\nexport type SubscriptionSettings = {\n /** Per provider; a provider without an entry spreads work. */\n rotation: Record<ProviderId, Rotation>;\n /** `automatic` admits both classified shared pools; missing entries retain legacy behavior. */\n inferenceSource?: Record<ProviderId, \"automatic\" | \"workspace\" | \"organization\">;\n crossProviderFailover: boolean;\n /** Ordered fallback models for a preferred model, possibly on other providers. */\n fallbackOrder: Record<ModelId, ModelId[]>;\n personalConnectionsAllowed: boolean;\n personalFallbackAllowed: boolean;\n};\nexport type SettingKey = keyof SubscriptionSettings;\n\nexport type SettingsPolicy = {\n organization: SubscriptionSettings;\n locked: readonly SettingKey[];\n workspaceOverrides: Record<string, Partial<SubscriptionSettings>>;\n};\n\nexport type ConnectionScope =\n | { kind: \"organization\" }\n | { kind: \"workspaces\"; workspaceIds: readonly string[]; personalWorkspaces: boolean }\n | { kind: \"people\"; personIds: readonly string[] };\n\nexport type Quota =\n | { kind: \"available\" }\n | { kind: \"unknown\" }\n | { kind: \"exhausted\"; resetsAt: number | null };\n\nexport type Connection = {\n id: string;\n provider: ProviderId;\n ownership: { kind: \"shared\"; scope: ConnectionScope } | { kind: \"personal\"; ownerId: string };\n healthy: boolean;\n allocatorEnabled: boolean;\n entitledModels: readonly ModelId[];\n /** Administrator access policy on the connection; null or absent allows every entitled model. */\n allowedModelIds?: readonly ModelId[] | null;\n assignmentPolicies?: readonly {\n workspaceId: string;\n inferencePool: \"workspace\" | \"organization\";\n allowedModelIds: readonly ModelId[] | null;\n excludedModelIds?: readonly ModelId[];\n allocatorEnabled: boolean;\n managedByWorkspaceId?: string | null;\n }[];\n /** Per-model cooldowns (some providers report model-specific limits). */\n modelCooldowns?: Readonly<Record<ModelId, number>>;\n quota: Quota;\n /** Explicit consent to spend credits after the included allowance (extra-credits providers only). */\n extraCreditsEnabled?: boolean;\n /** A provider refusal blocks even paid credits until this deadline. */\n refusalUntil?: number | null;\n};\n\nexport type Workspace = {\n id: string;\n kind: \"shared\" | \"personal\";\n /** Owner of a Personal workspace. */\n ownerId: string | null;\n /** Workspace model restriction; null allows every model. */\n allowedModels: readonly ModelId[] | null;\n};\n\nexport type Person = { id: string; active: boolean; personalFallbackOptIn: boolean };\n\n/** The contract's closed set of model tiers (D-35). Tiers compare by equality only. */\nexport type Tier = \"frontier\" | \"standard\" | \"fast\";\nconst TIERS: readonly string[] = [\"frontier\", \"standard\", \"fast\"];\n\nexport type Model = {\n id: ModelId;\n provider: ProviderId;\n reasoningLevels: readonly string[];\n /** The tier its provider declares; absent or null when it declares none. */\n tier?: Tier | null;\n};\n\nexport type SessionBinding = { connectionId: string; modelId: ModelId; lastUsedAt: number };\n\nexport type Session = {\n id: string;\n workspaceId: string;\n visibility: \"private\" | \"shared\";\n /** Null only for a deliberately ownerless service session; it can use shared pools only. */\n ownerId: string | null;\n /** Exact accepted shared-chat consent; not a new account pool. */\n sharedPersonalChoices?: readonly { connectionId: string; ownerId: string }[];\n /** The model the session asked for. */\n preferredModelId: ModelId;\n reasoningLevel: string;\n binding: SessionBinding | null;\n /** An explicit account choice is a pin: the session waits for it rather than moving. */\n pinnedConnectionId: string | null;\n /** \"Only this model\": no cross-provider failover. Same-model account failover still applies. */\n onlyThisModel: boolean;\n /** A compaction completed or the model changed since the last placement (SUB-STICK-05). */\n reselectionPoint?: boolean;\n};\n\nexport type World = {\n settings: SettingsPolicy;\n workspaces: readonly Workspace[];\n people: readonly Person[];\n models: readonly Model[];\n connections: readonly Connection[];\n sessions: readonly Session[];\n /** Prompt-cache lifetime after the last use, per provider. */\n cacheTtlMs: Record<ProviderId, number>;\n};\n\nexport type SwitchKind =\n | \"initial\"\n | \"sticky\"\n | \"pinned\"\n | \"reselected_cold\"\n | \"failover_same_provider\"\n | \"failover_cross_provider\"\n | \"return_to_preferred\";\n\nexport type WaitReason =\n | \"pinned_account_unavailable\"\n /** The explicit choice can never serve this work until a person changes something (D-24). */\n | \"pinned_account_ineligible\"\n | \"no_eligible_capacity\"\n | \"model_not_allowed\"\n /** Decided before placement (an unusable accepted authority); never produced here. */\n | \"accepted_authority_unavailable\";\n\nexport type Decision =\n | {\n kind: \"run\";\n connectionId: string;\n modelId: ModelId;\n reasoningLevel: string;\n switch: SwitchKind;\n }\n | { kind: \"wait\"; reason: WaitReason; earliestResetAt: number | null };\n\n// Effective settings\n\nexport type EffectiveSettings = {\n values: SubscriptionSettings;\n sources: Record<SettingKey, \"organization\" | \"workspace\">;\n};\n\nconst SETTING_KEYS: readonly SettingKey[] = [\n \"rotation\",\n \"inferenceSource\",\n \"crossProviderFailover\",\n \"fallbackOrder\",\n \"personalConnectionsAllowed\",\n \"personalFallbackAllowed\",\n];\n\n/**\n * SUB-SET-01..03: organization default, unless a workspace overrides an\n * unlocked setting. Per-provider and per-model maps are overridden entry by\n * entry, so a workspace that sets one provider's rotation keeps the others\n * (D-25); the source is \"workspace\" when the workspace overrides any entry.\n */\nexport function effectiveSettings(policy: SettingsPolicy, workspaceId: string): EffectiveSettings {\n const override = policy.workspaceOverrides[workspaceId] ?? {};\n const values = { ...policy.organization } as SubscriptionSettings;\n const sources = {} as Record<SettingKey, \"organization\" | \"workspace\">;\n for (const key of SETTING_KEYS) {\n const overridden = override[key] !== undefined && !policy.locked.includes(key);\n if (overridden) {\n (values as Record<SettingKey, unknown>)[key] =\n key === \"rotation\" || key === \"inferenceSource\" || key === \"fallbackOrder\"\n ? { ...policy.organization[key], ...(override[key] as object) }\n : override[key];\n }\n sources[key] = overridden ? \"workspace\" : \"organization\";\n }\n return { values, sources };\n}\n\n// Eligibility\n\nfunction byId<T extends { id: string }>(items: readonly T[], id: string): T | undefined {\n return items.find((item) => item.id === id);\n}\n\nexport function isCacheWarm(world: World, binding: SessionBinding, now: number): boolean {\n const connection = byId(world.connections, binding.connectionId);\n if (!connection) return false;\n const ttl = world.cacheTtlMs[connection.provider] ?? 0;\n return now - binding.lastUsedAt <= ttl;\n}\n\nfunction hasCapacity(connection: Connection, now: number): boolean {\n // Unknown quota stays unknown: it is neither availability nor exhaustion (SUB-ELIG-06).\n return (\n connection.quota.kind !== \"exhausted\" ||\n (connection.quota.resetsAt !== null && connection.quota.resetsAt <= now) ||\n spendsCredits(connection, now)\n );\n}\n\nfunction spendsCredits(connection: Connection, now: number): boolean {\n return (\n connection.extraCreditsEnabled === true &&\n (connection.refusalUntil == null || connection.refusalUntil <= now) &&\n connection.quota.kind === \"exhausted\" &&\n (connection.quota.resetsAt === null || connection.quota.resetsAt > now)\n );\n}\n\nfunction modelAllowed(world: World, session: Session, modelId: ModelId): boolean {\n const workspace = byId(world.workspaces, session.workspaceId);\n return (\n !!workspace && (workspace.allowedModels === null || workspace.allowedModels.includes(modelId))\n );\n}\n\n/**\n * Why this connection may not serve this session's work at all, ignoring the\n * model, capacity and the explicit-choice rule for personal accounts, labelled\n * with the requirement that forbids it; null when it may.\n */\nexport function authorizationFailure(\n world: World,\n session: Session,\n connection: Connection,\n): InvariantViolation | null {\n const failure = (requirement: string, message: string) => ({ requirement, message });\n const workspace = byId(world.workspaces, session.workspaceId);\n if (!workspace) return failure(\"SUB-ELIG-01\", \"the session's workspace is unknown\");\n if (!connection.healthy || !connection.allocatorEnabled) {\n return failure(\"SUB-ELIG-04\", \"the account is unhealthy or excluded from allocation\");\n }\n if (connection.ownership.kind === \"personal\") {\n const settings = effectiveSettings(world.settings, workspace.id).values;\n const owner = byId(world.people, connection.ownership.ownerId);\n const ownersOwnWork =\n (session.ownerId !== null &&\n session.sharedPersonalChoices?.some(\n (choice) => choice.connectionId === connection.id && choice.ownerId === owner?.id,\n )) ||\n (session.ownerId === connection.ownership.ownerId &&\n (session.visibility === \"private\" ||\n (workspace.kind === \"personal\" && workspace.ownerId === connection.ownership.ownerId)));\n if (!settings.personalConnectionsAllowed) {\n return failure(\"SUB-OWN-05\", \"personal connections are disabled here\");\n }\n if (!owner?.active) return failure(\"SUB-ACCESS-06\", \"the personal account's owner left\");\n if (!ownersOwnWork) {\n return failure(\"SUB-ELIG-05\", \"a personal account served work other than its owner's own\");\n }\n return null;\n }\n if (connection.assignmentPolicies !== undefined) {\n const source =\n effectiveSettings(world.settings, workspace.id).values.inferenceSource?.[\n connection.provider\n ] ?? \"automatic\";\n const matching = connection.assignmentPolicies.filter(\n (policy) =>\n policy.workspaceId === workspace.id &&\n (source === \"automatic\" || policy.inferencePool === source),\n );\n if (matching.length === 0) {\n return failure(\"SUB-SET-06\", \"the effective inference source excludes this assignment\");\n }\n }\n const scope = connection.ownership.scope;\n const inScope =\n scope.kind === \"organization\" ||\n (scope.kind === \"workspaces\"\n ? scope.workspaceIds.includes(workspace.id) ||\n (workspace.kind === \"personal\" && scope.personalWorkspaces)\n : session.ownerId !== null && scope.personIds.includes(session.ownerId));\n return inScope ? null : failure(\"SUB-ELIG-01\", \"the account's scope excludes this work\");\n}\n\n/** May this connection serve this session's work at all? SUB-ELIG-01, 04, 05. */\nexport function isAuthorized(world: World, session: Session, connection: Connection): boolean {\n return authorizationFailure(world, session, connection) === null;\n}\n\n/**\n * Why this connection cannot serve this session on this model now, labelled\n * with the requirement that forbids it; null when it can.\n */\nexport function servingFailure(\n world: World,\n session: Session,\n connection: Connection,\n modelId: ModelId,\n now: number,\n): InvariantViolation | null {\n const model = byId(world.models, modelId);\n if (\n !model ||\n model.provider !== connection.provider ||\n !connection.entitledModels.includes(modelId)\n ) {\n return { requirement: \"SUB-ELIG-03\", message: \"the account's plan does not include the model\" };\n }\n if (connection.allowedModelIds != null && !connection.allowedModelIds.includes(modelId)) {\n return {\n requirement: \"SUB-ELIG-03\",\n message: \"the account's access policy excludes the model\",\n };\n }\n if (connection.assignmentPolicies !== undefined) {\n const workspace = byId(world.workspaces, session.workspaceId)!;\n const source =\n effectiveSettings(world.settings, workspace.id).values.inferenceSource?.[\n connection.provider\n ] ?? \"automatic\";\n const matching = connection.assignmentPolicies.filter(\n (policy) =>\n policy.workspaceId === workspace.id &&\n (source === \"automatic\" || policy.inferencePool === source),\n );\n const hasAllocatableAssignment = matching.some((policy) => policy.allocatorEnabled);\n if (!hasAllocatableAssignment) {\n return {\n requirement: \"SUB-ELIG-04\",\n message: \"the source assignment is excluded from allocation\",\n };\n }\n if (\n !matching.some(\n (policy) =>\n policy.allocatorEnabled &&\n (policy.allowedModelIds === null || policy.allowedModelIds.includes(modelId)) &&\n !policy.excludedModelIds?.includes(modelId),\n )\n ) {\n const hasModelAssignment = matching.some(\n (policy) =>\n (policy.allowedModelIds === null || policy.allowedModelIds.includes(modelId)) &&\n !policy.excludedModelIds?.includes(modelId),\n );\n return {\n requirement: hasModelAssignment ? \"SUB-ELIG-04\" : \"SUB-ELIG-03\",\n message: hasModelAssignment\n ? \"model access exists only on a source assignment excluded from allocation\"\n : \"no source assignment allows the model\",\n };\n }\n }\n if ((connection.modelCooldowns?.[modelId] ?? -Infinity) > now) {\n return { requirement: \"SUB-ELIG-03\", message: \"the account is cooling down for the model\" };\n }\n if (!modelAllowed(world, session, modelId)) {\n return { requirement: \"SUB-ELIG-02\", message: \"the workspace does not allow the model\" };\n }\n const authorization = authorizationFailure(world, session, connection);\n if (authorization) return authorization;\n if (!hasCapacity(connection, now)) {\n return { requirement: \"SUB-FAIL-02\", message: \"the account has no capacity now\" };\n }\n return null;\n}\n\nexport function canServe(\n world: World,\n session: Session,\n connection: Connection,\n modelId: ModelId,\n now: number,\n): boolean {\n return servingFailure(world, session, connection, modelId, now) === null;\n}\n\n// Selection\n\n/**\n * Deterministic hash used to spread sessions across accounts (D-21): FNV-1a\n * over the UTF-16 code units, finished with the murmur3 finalizer, because raw\n * FNV-1a orders similar keys unevenly and so spreads unfairly (SUB-SEL-03, D-23).\n */\nexport function spreadHash(sessionId: string, connectionId: string): number {\n let hash = 0x811c9dc5;\n const key = sessionId + \"|\" + connectionId;\n for (let index = 0; index < key.length; index += 1) {\n hash ^= key.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n // murmur3 fmix32\n hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b) >>> 0;\n hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35) >>> 0;\n return (hash ^ (hash >>> 16)) >>> 0;\n}\n\n/**\n * Rank servable connections for one model. In Primary first the primary takes\n * new work whenever it can serve it, and unknown quota counts as able to serve\n * (D-13, D-14, D-15). Every other choice ranks known capacity before unknown\n * quota (D-14), then a deterministic per-session hash spreads sessions (D-21),\n * then the connection id breaks ties.\n */\nfunction pick(world: World, session: Session, candidates: Connection[]): Connection | null {\n if (candidates.length === 0) return null;\n const provider = candidates[0]!.provider;\n const rotation =\n effectiveSettings(world.settings, session.workspaceId).values.rotation[provider] ??\n ({ mode: \"spread\" } as Rotation);\n if (rotation.mode === \"primary_first\") {\n const primary = candidates.find((candidate) => candidate.id === rotation.primaryConnectionId);\n if (primary) return primary;\n }\n const ranked = [...candidates].sort((left, right) => {\n const spread = spreadHash(session.id, left.id) - spreadHash(session.id, right.id);\n if (spread !== 0) return spread;\n return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;\n });\n return ranked[0]!;\n}\n\n/**\n * SUB-FAIL-03 and D-16: the reasoning level to run `model` at when the session\n * asked for `requested` on its preferred model `from`.\n *\n * 1. The same level name when the model supports it.\n * 2. Otherwise the model's level whose relative position on its own ladder\n * (lowest 0, highest 1) is closest to the requested level's relative\n * position on the preferred model's ladder. A tie goes to the lower level.\n * 3. A level the preferred model does not list has no position and maps to\n * the middle of the ladder (the lower middle when there are two).\n */\nexport function nearestReasoningLevel(\n model: Model,\n requested: string,\n from: Model | undefined,\n): string {\n const levels = model.reasoningLevels;\n if (levels.includes(requested)) return requested;\n if (levels.length <= 1) return levels[0] ?? \"\";\n const source = from?.reasoningLevels ?? [];\n const sourceIndex = source.indexOf(requested);\n // The requested position as an exact fraction, so ties are exact.\n const [numerator, denominator] =\n sourceIndex < 0 || source.length <= 1 ? [1, 2] : [sourceIndex, source.length - 1];\n // |index / (levels - 1) - numerator / denominator|, scaled by both denominators.\n const distance = (index: number) =>\n Math.abs(index * denominator - numerator * (levels.length - 1));\n let best = 0;\n for (let index = 1; index < levels.length; index += 1) {\n if (distance(index) < distance(best)) best = index;\n }\n return levels[best]!;\n}\n\n/**\n * D-35: the fallback order of a preferred model the settings name no entry\n * for. Only with cross-provider failover on, and only when the preferred\n * model declares a tier: every model of another provider declaring exactly\n * that tier (Q-04: never a lower or higher one), provider by provider in\n * sorted id order, each provider's models in the world's order, at most 8.\n * The preferred model's own provider contributes nothing (same-provider\n * model fallback is explicit only).\n */\nexport function derivedFallbacks(\n world: World,\n settings: SubscriptionSettings,\n preferredModelId: ModelId,\n): ModelId[] {\n const preferred = byId(world.models, preferredModelId);\n if (!settings.crossProviderFailover || !preferred) return [];\n const tier = preferred.tier;\n if (typeof tier !== \"string\" || !TIERS.includes(tier)) return [];\n const otherProviders = [...new Set(world.models.map((model) => model.provider))]\n .filter((provider) => provider !== preferred.provider)\n .sort();\n const derived: ModelId[] = [];\n for (const provider of otherProviders) {\n for (const model of world.models) {\n if (model.provider !== provider || model.tier !== tier) continue;\n if (model.id === preferredModelId || derived.includes(model.id)) continue;\n derived.push(model.id);\n }\n }\n return derived.slice(0, 8);\n}\n\n/**\n * Candidate models in failover order: the preferred model, then (if allowed)\n * its fallbacks. An explicit entry for the preferred model, even an empty\n * list, is the order; only a missing entry derives one (D-35).\n */\nexport function candidateModels(world: World, session: Session): ModelId[] {\n const settings = effectiveSettings(world.settings, session.workspaceId).values;\n const preferred = session.preferredModelId;\n if (session.onlyThisModel || session.pinnedConnectionId) return [preferred];\n const preferredProvider = byId(world.models, preferred)?.provider;\n const explicit = Object.prototype.hasOwnProperty.call(settings.fallbackOrder, preferred);\n const order = explicit\n ? (settings.fallbackOrder[preferred] ?? [])\n : derivedFallbacks(world, settings, preferred);\n // Same-provider fallback models are always allowed; other providers only\n // when cross-provider failover is on (SUB-FAIL-02, SUB-FAIL-03).\n const fallbacks = order.filter(\n (modelId, index, all) =>\n modelId !== preferred &&\n all.indexOf(modelId) === index &&\n (byId(world.models, modelId)?.provider === preferredProvider ||\n settings.crossProviderFailover),\n );\n return [preferred, ...fallbacks];\n}\n\n/**\n * D-24: an explicit choice that can never serve this session's model: gone,\n * no longer authorized for this work, another provider's account, or not\n * entitled or allowed for the model. Health, allocation, capacity and\n * cooldowns recover, so they never make an explicit choice permanently unusable.\n */\nexport function pinnedNeverServes(\n world: World,\n session: Session,\n pinned: Connection | undefined,\n): boolean {\n if (!pinned) return true;\n const model = byId(world.models, session.preferredModelId);\n if (!model || model.provider !== pinned.provider) return true;\n if (!pinned.entitledModels.includes(model.id)) return true;\n if (pinned.allowedModelIds != null && !pinned.allowedModelIds.includes(model.id)) return true;\n if (pinned.assignmentPolicies !== undefined) {\n const source =\n effectiveSettings(world.settings, session.workspaceId).values.inferenceSource?.[\n pinned.provider\n ] ?? \"automatic\";\n const assignments = pinned.assignmentPolicies.filter(\n (policy) =>\n policy.workspaceId === session.workspaceId &&\n (source === \"automatic\" || policy.inferencePool === source),\n );\n if (\n !assignments.some(\n (policy) =>\n (policy.allowedModelIds === null || policy.allowedModelIds.includes(model.id)) &&\n !policy.excludedModelIds?.includes(model.id),\n )\n ) {\n return true;\n }\n }\n return !isAuthorized(world, session, { ...pinned, healthy: true, allocatorEnabled: true });\n}\n\n/** Future times at which some quota or model cooldown in the world resets, ascending. */\nfunction futureResetTimes(world: World, now: number): number[] {\n const times = new Set<number>();\n for (const connection of world.connections) {\n if (\n connection.quota.kind === \"exhausted\" &&\n connection.quota.resetsAt !== null &&\n connection.quota.resetsAt > now\n ) {\n times.add(connection.quota.resetsAt);\n }\n if (connection.refusalUntil != null && connection.refusalUntil > now)\n times.add(connection.refusalUntil);\n for (const until of Object.values(connection.modelCooldowns ?? {})) {\n if (until > now) times.add(until);\n }\n }\n return [...times].sort((left, right) => left - right);\n}\n\n/**\n * SUB-WAIT-02, D-22: the earliest future time at which the session could run,\n * assuming nothing else changes; null when no known reset makes it runnable.\n */\nexport function earliestRunnableAt(\n world: World,\n now: number,\n runnableAt: (at: number) => boolean,\n): number | null {\n return futureResetTimes(world, now).find(runnableAt) ?? null;\n}\n\nfunction personalFallbackFor(world: World, session: Session): boolean {\n if (session.ownerId === null) return false;\n if (\n session.visibility === \"shared\" &&\n byId(world.workspaces, session.workspaceId)?.kind === \"shared\"\n )\n return false;\n const settings = effectiveSettings(world.settings, session.workspaceId).values;\n return (\n (byId(world.workspaces, session.workspaceId)?.kind === \"personal\" &&\n byId(world.workspaces, session.workspaceId)?.ownerId === session.ownerId) ||\n (settings.personalFallbackAllowed &&\n !!byId(world.people, session.ownerId)?.personalFallbackOptIn)\n );\n}\n\n/**\n * The contract's decision for a session that wants to run a turn now. The\n * sender is deliberately not an input: the account belongs to the session\n * (SUB-STICK-01).\n */\nexport function decide(world: World, sessionId: string, now: number): Decision {\n const session = byId(world.sessions, sessionId);\n if (!session) throw new Error(\"unknown session \" + sessionId);\n const preferredModel = byId(world.models, session.preferredModelId);\n const level = (model: ModelId) =>\n nearestReasoningLevel(byId(world.models, model)!, session.reasoningLevel, preferredModel);\n const run = (connectionId: string, modelId: ModelId, kind: SwitchKind): Decision => ({\n kind: \"run\",\n connectionId,\n modelId,\n reasoningLevel: level(modelId),\n switch: kind,\n });\n\n // A restricted preferred model falls through to its allowed failover\n // candidates (SUB-ELIG-02, SUB-WAIT-01, D-17); waiting on the restriction is\n // right only when no candidate is allowed.\n const models = candidateModels(world, session);\n const allowedModels = models.filter((modelId) => modelAllowed(world, session, modelId));\n if (allowedModels.length === 0) {\n return { kind: \"wait\", reason: \"model_not_allowed\", earliestResetAt: null };\n }\n\n // Explicit choice is a pin (SUB-SEL-04, SUB-FAIL-05, SUB-STICK-06).\n if (session.pinnedConnectionId) {\n const pinned = byId(world.connections, session.pinnedConnectionId);\n if (pinned && canServe(world, session, pinned, session.preferredModelId, now)) {\n return run(pinned.id, session.preferredModelId, \"pinned\");\n }\n // It can never serve this work: explain that instead of waiting silently (D-24).\n if (pinnedNeverServes(world, session, pinned)) {\n return { kind: \"wait\", reason: \"pinned_account_ineligible\", earliestResetAt: null };\n }\n // Otherwise the earliest future time the chosen account can serve (D-22).\n return {\n kind: \"wait\",\n reason: \"pinned_account_unavailable\",\n earliestResetAt: earliestRunnableAt(world, now, (at) =>\n canServe(world, session, pinned!, session.preferredModelId, at),\n ),\n };\n }\n\n const binding = session.binding;\n const bound = binding ? byId(world.connections, binding.connectionId) : undefined;\n const personalFallback = personalFallbackFor(world, session);\n const bindingServable =\n !!binding &&\n !!bound &&\n models.includes(binding.modelId) &&\n canServe(world, session, bound, binding.modelId, now);\n\n // Stickiness while the cache is warm (SUB-STICK-02, SUB-STICK-03, SUB-FAIL-07).\n const includedAlternative = (modelId: string) =>\n world.connections.some(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n !spendsCredits(connection, now) &&\n canServe(world, session, connection, modelId, now),\n );\n if (\n binding &&\n bound &&\n bindingServable &&\n !session.reselectionPoint &&\n isCacheWarm(world, binding, now) &&\n (!spendsCredits(bound, now) || !includedAlternative(binding.modelId))\n ) {\n return run(binding.connectionId, binding.modelId, \"sticky\");\n }\n\n // Order: each candidate model on shared accounts, then (opt-in) on the\n // owner's personal accounts, before moving to the next model (D-12).\n for (const [index, modelId] of models.entries()) {\n const eligible = world.connections.filter(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n canServe(world, session, connection, modelId, now),\n );\n const included = eligible.filter((connection) => !spendsCredits(connection, now));\n const servable = included.length ? included : eligible;\n const shared = servable.filter((connection) => connection.ownership.kind === \"shared\");\n const personal = servable.filter((connection) => connection.ownership.kind === \"personal\");\n const chosen =\n pick(world, session, shared) ?? (personalFallback ? pick(world, session, personal) : null);\n if (!chosen) continue;\n let kind: SwitchKind;\n if (!binding) kind = \"initial\";\n else if (binding.connectionId === chosen.id && binding.modelId === modelId) kind = \"sticky\";\n else if (index === 0 && binding.modelId !== modelId) kind = \"return_to_preferred\";\n else if (index > 0)\n kind =\n byId(world.models, modelId)?.provider ===\n byId(world.models, session.preferredModelId)?.provider\n ? \"failover_same_provider\"\n : \"failover_cross_provider\";\n else if (bindingServable) kind = \"reselected_cold\";\n else kind = \"failover_same_provider\";\n return run(chosen.id, modelId, kind);\n }\n return {\n kind: \"wait\",\n reason: \"no_eligible_capacity\",\n earliestResetAt: earliestRunnableAt(world, now, (at) =>\n allowedModels.some((modelId) =>\n world.connections.some(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n canServe(world, session, connection, modelId, at),\n ),\n ),\n ),\n };\n}\n\n/** Record that a decision ran: the session binds to the chosen account. */\nexport function applyDecision(\n world: World,\n sessionId: string,\n decision: Decision,\n now: number,\n): World {\n if (decision.kind !== \"run\") return world;\n return {\n ...world,\n sessions: world.sessions.map((session) =>\n session.id === sessionId\n ? {\n ...session,\n binding: {\n connectionId: decision.connectionId,\n modelId: decision.modelId,\n lastUsedAt: now,\n },\n }\n : session,\n ),\n };\n}\n\n// Invariants\n\nexport type InvariantViolation = { requirement: string; message: string };\n\n/**\n * Check any decision (from this model or from production) against the\n * contract's invariants for this world. An empty result means the decision is\n * acceptable; it does not require the decision to equal the model's own.\n */\nexport function checkDecision(\n world: World,\n sessionId: string,\n now: number,\n decision: Decision,\n): InvariantViolation[] {\n const violations: InvariantViolation[] = [];\n const session = byId(world.sessions, sessionId)!;\n const settings = effectiveSettings(world.settings, session.workspaceId).values;\n const models = candidateModels(world, session);\n const fail = (requirement: string, message: string) => violations.push({ requirement, message });\n\n const personalFallback = personalFallbackFor(world, session);\n const servableShared = (modelId: ModelId, credits: boolean) =>\n world.connections.some(\n (connection) =>\n connection.ownership.kind === \"shared\" &&\n (credits || !spendsCredits(connection, now)) &&\n canServe(world, session, connection, modelId, now),\n );\n const servableAutomatically = (modelId: ModelId) =>\n world.connections.some(\n (connection) =>\n canServe(world, session, connection, modelId, now) &&\n (connection.ownership.kind === \"shared\" || personalFallback),\n );\n const anyServable = models.some(servableAutomatically);\n const binding = session.binding;\n const bindingWarm = !!binding && !session.reselectionPoint && isCacheWarm(world, binding, now);\n\n if (decision.kind === \"run\") {\n const connection = byId(world.connections, decision.connectionId);\n if (!connection) {\n fail(\"SUB-ELIG-01\", \"the chosen account does not exist\");\n return violations;\n }\n const ineligible = servingFailure(world, session, connection, decision.modelId, now);\n if (ineligible) {\n violations.push(ineligible);\n return violations;\n }\n if (session.pinnedConnectionId && decision.connectionId !== session.pinnedConnectionId) {\n fail(\"SUB-SEL-04\", \"a pinned session ran on another account\");\n }\n if (!models.includes(decision.modelId)) {\n fail(\"SUB-FAIL-04\", \"ran a model outside the allowed failover candidates\");\n }\n const crossProvider =\n byId(world.models, decision.modelId)?.provider !==\n byId(world.models, session.preferredModelId)?.provider;\n if (crossProvider && (!settings.crossProviderFailover || session.onlyThisModel)) {\n fail(\"SUB-FAIL-03\", \"moved across providers although that is not allowed\");\n }\n const expectedLevel = nearestReasoningLevel(\n byId(world.models, decision.modelId)!,\n session.reasoningLevel,\n byId(world.models, session.preferredModelId),\n );\n if (decision.reasoningLevel !== expectedLevel) {\n fail(\"SUB-FAIL-03\", \"ran at a reasoning level other than the nearest supported level\");\n }\n // Staying on the current account while its cache is warm is always allowed\n // (SUB-STICK-02); every other placement must respect the failover order.\n const stayingWarm =\n !!binding &&\n bindingWarm &&\n binding.connectionId === decision.connectionId &&\n binding.modelId === decision.modelId;\n if (!stayingWarm && !session.pinnedConnectionId) {\n const index = models.indexOf(decision.modelId);\n if (models.slice(0, Math.max(index, 0)).some(servableAutomatically)) {\n fail(\"SUB-FAIL-02\", \"skipped an earlier failover candidate that could still run\");\n }\n if (\n connection.ownership.kind === \"personal\" &&\n (!personalFallback || servableShared(decision.modelId, spendsCredits(connection, now)))\n ) {\n fail(\"SUB-SEL-02\", \"used a personal account without an explicit choice or opt-in fallback\");\n }\n }\n const includedAlternative = (modelId: string) =>\n world.connections.some(\n (candidate) =>\n (candidate.ownership.kind === \"shared\" || personalFallback) &&\n !spendsCredits(candidate, now) &&\n canServe(world, session, candidate, modelId, now),\n );\n if (\n !session.pinnedConnectionId &&\n spendsCredits(connection, now) &&\n includedAlternative(decision.modelId)\n ) {\n fail(\"SUB-CREDITS-01\", \"spent extra credits while an eligible account had included capacity\");\n }\n if (binding && bindingWarm && !session.pinnedConnectionId) {\n const bound = byId(world.connections, binding.connectionId);\n const stillServable =\n !!bound &&\n (!spendsCredits(bound, now) || !includedAlternative(binding.modelId)) &&\n models.includes(binding.modelId) &&\n canServe(world, session, bound, binding.modelId, now);\n if (\n stillServable &&\n (decision.connectionId !== binding.connectionId || decision.modelId !== binding.modelId)\n ) {\n fail(\n \"SUB-STICK-02\",\n \"switched account or model while the cache was warm and nothing forced it\",\n );\n }\n }\n } else {\n // Only a real workspace model restriction justifies this reason: no\n // candidate model, the preferred one or an allowed fallback, is allowed.\n if (\n decision.reason === \"model_not_allowed\" &&\n models.some((modelId) => modelAllowed(world, session, modelId))\n ) {\n fail(\"SUB-WAIT-01\", \"waited for a model restriction although an allowed model exists\");\n }\n const pinned = session.pinnedConnectionId\n ? byId(world.connections, session.pinnedConnectionId)\n : undefined;\n const pinnedServable =\n !!pinned && canServe(world, session, pinned, session.preferredModelId, now);\n if (session.pinnedConnectionId ? pinnedServable : anyServable) {\n fail(\"SUB-WAIT-01\", \"waited although an eligible account had capacity\");\n }\n // The wait explains itself (SUB-WAIT-02, D-24) and names the earliest time\n // a known reset makes the session runnable (SUB-WAIT-02, D-22).\n const allowedModels = models.filter((modelId) => modelAllowed(world, session, modelId));\n const never = !!session.pinnedConnectionId && pinnedNeverServes(world, session, pinned);\n const expectedReason: WaitReason =\n allowedModels.length === 0\n ? \"model_not_allowed\"\n : session.pinnedConnectionId\n ? never\n ? \"pinned_account_ineligible\"\n : \"pinned_account_unavailable\"\n : \"no_eligible_capacity\";\n if (decision.reason !== expectedReason) {\n fail(\n never && decision.reason === \"pinned_account_unavailable\" ? \"SUB-ACCESS-06\" : \"SUB-WAIT-02\",\n \"explained the wait with \" + decision.reason + \" instead of \" + expectedReason,\n );\n }\n const expectedReset =\n expectedReason === \"pinned_account_unavailable\"\n ? earliestRunnableAt(world, now, (at) =>\n canServe(world, session, pinned!, session.preferredModelId, at),\n )\n : expectedReason === \"no_eligible_capacity\"\n ? earliestRunnableAt(world, now, (at) =>\n allowedModels.some((modelId) =>\n world.connections.some(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n canServe(world, session, connection, modelId, at),\n ),\n ),\n )\n : null;\n if (decision.reason === expectedReason && decision.earliestResetAt !== expectedReset) {\n fail(\"SUB-WAIT-02\", \"did not name the earliest time a reset makes the session runnable\");\n }\n }\n return violations;\n}\n","/**\n * Bridge from the production placement input to the independent reference\n * model, so the reference `checkDecision` can judge a production decision for\n * a real world (the worker's shadow comparison). It maps the production\n * concepts the reference model does not have onto ones it does, using only the\n * raw inputs, never the production eligibility or placement functions, so a\n * policy bug cannot hide from the checker:\n *\n * - A provider switched off, a compaction provider lock and the workspace\n * model ceiling become the workspace's allowed model list.\n * - Shared connections a workspace does not manage while organization\n * accounts are off, and personal connections without frozen personal\n * authority for their provider, are left out (nothing may use them).\n * - Quota and cache lifetimes are decoded here, independently of the\n * production decoders, from the raw shared quota model (design 2.2) and\n * cache facts (design 6.1), including the input's staleness bounds. An\n * exhaustion with no known reset stays exhausted, including when evaluating\n * the separate permission to spend extra credits.\n * - An exact cache lifetime on the binding is that provider's lifetime.\n * - An explicit binding is the reference model's pin.\n * - Model tiers pass through as declared, and the fallback order keeps its\n * own entries only, so the reference derives its own default order for a\n * preferred model without an entry (D-35).\n */\nimport * as reference from \"./reference-model\";\nimport { inferenceSourceFor } from \"./settings\";\nimport type {\n CacheFacts,\n PlacementDecision,\n PlacementInput,\n SubscriptionConnection,\n SubscriptionQuota,\n} from \"./types\";\n\n/** Design 6.1: an unmeasured idle cut-off counts as one hour. */\nconst UNMEASURED_CUTOFF_MS = 3_600_000;\n\nfunction lifetimeOf(facts: CacheFacts | undefined): number {\n if (facts?.kind === \"exact_ttl\") return Math.max(0, facts.ttlMs);\n return Math.max(0, facts?.cutoffMs ?? UNMEASURED_CUTOFF_MS);\n}\n\ntype DecodedQuota = reference.Quota;\n\n/**\n * Design 2.2 read from the raw fields: a running deadline or exhausted\n * window is exhaustion until its latest reset; any fresh observed window, an\n * exhausted window whose reset passed, or a passed quota deadline is known\n * capacity; nothing else is known (SUB-ELIG-06).\n */\nfunction decodeQuota(\n quota: SubscriptionQuota | null,\n now: number,\n staleAfterMs: number | undefined,\n): DecodedQuota {\n if (quota === null) return { kind: \"unknown\" };\n const fresh =\n staleAfterMs === undefined ||\n (quota.observedAt !== null && now - quota.observedAt <= staleAfterMs);\n const blockingResets: (number | null)[] = [];\n if (quota.exhaustedUntil !== null && quota.exhaustedUntil > now) {\n blockingResets.push(quota.exhaustedUntil);\n }\n for (const window of quota.windows) {\n if (window.status === \"exhausted\" && (window.resetsAt === null || window.resetsAt > now)) {\n blockingResets.push(window.resetsAt);\n }\n }\n if (blockingResets.length > 0) {\n return blockingResets.includes(null)\n ? { kind: \"exhausted\", resetsAt: null }\n : { kind: \"exhausted\", resetsAt: Math.max(...(blockingResets as number[])) };\n }\n const observed =\n quota.windows.some((window) => window.status !== \"unknown\") ||\n (quota.exhaustedUntil !== null && quota.exhaustedKind === \"quota\");\n return observed && fresh ? { kind: \"available\" } : { kind: \"unknown\" };\n}\n\nfunction referenceConnection(\n input: PlacementInput,\n connection: SubscriptionConnection,\n): reference.Connection {\n const providerModels = input.models\n .filter((model) => model.provider === connection.provider)\n .map((model) => model.id);\n const entitled = (connection.entitledModelIds ?? providerModels).filter(\n (modelId) => !connection.excludedModelIds.includes(modelId),\n );\n const capacity = decodeQuota(\n connection.quota,\n input.now,\n input.quotaStaleAfterMs?.[connection.provider],\n );\n const ownership: reference.Connection[\"ownership\"] =\n connection.ownership.kind === \"personal\"\n ? { kind: \"personal\", ownerId: connection.ownership.ownerMembershipId }\n : {\n kind: \"shared\",\n scope:\n connection.ownership.scope.kind === \"organization\"\n ? { kind: \"organization\" }\n : connection.ownership.scope.kind === \"workspaces\"\n ? {\n kind: \"workspaces\",\n workspaceIds: connection.ownership.scope.workspaceIds,\n personalWorkspaces: connection.ownership.scope.allowPersonalWorkspaces,\n }\n : { kind: \"people\", personIds: connection.ownership.scope.membershipIds },\n };\n return {\n id: connection.id,\n provider: connection.provider,\n ownership,\n healthy: connection.health === \"healthy\",\n allocatorEnabled: connection.allocatorEnabled,\n extraCreditsEnabled: connection.extraCreditsEnabled === true,\n refusalUntil: connection.quota?.exhaustedUntil ?? null,\n entitledModels: entitled,\n allowedModelIds: connection.allowedModelIds,\n ...(connection.assignmentPolicies === undefined\n ? {}\n : { assignmentPolicies: connection.assignmentPolicies }),\n modelCooldowns: { ...connection.quota?.modelCooldowns },\n quota: capacity,\n };\n}\n\n/** The reference world equivalent to one production placement input. */\nexport function toReferenceWorld(input: PlacementInput): {\n world: reference.World;\n sessionId: string;\n} {\n const { session, settings, workspace } = input;\n const switches = (provider: string) => settings.providers[provider];\n const ceiling = input.models\n .filter(\n (model) =>\n (workspace.allowedModelIds === null || workspace.allowedModelIds.includes(model.id)) &&\n switches(model.provider)?.enabled !== false &&\n (session.compactionProviderLock === null ||\n model.provider === session.compactionProviderLock),\n )\n .map((model) => model.id);\n const usable = input.connections.filter((connection) => {\n if (connection.ownership.kind === \"personal\") {\n const owner = connection.ownership.ownerMembershipId;\n return session.personalAuthority.some(\n (authority) =>\n authority.provider === connection.provider &&\n authority.ownerMembershipId === owner &&\n (!authority.sharedSessionChoice ||\n (authority.sharedSessionChoice.sessionId === session.id &&\n authority.sharedSessionChoice.connectionId === connection.id)),\n );\n }\n if (connection.assignmentPolicies !== undefined) return true;\n const source = inferenceSourceFor(settings, connection.provider);\n const managedHere = connection.ownership.managedByWorkspaceId === workspace.id;\n if (source === \"workspace\") return managedHere;\n if (source === \"organization\") return !managedHere;\n return source === \"automatic\" || managedHere;\n });\n const providers = new Set([\n ...input.models.map((model) => model.provider),\n ...input.connections.map((connection) => connection.provider),\n ]);\n const binding = session.binding;\n return {\n sessionId: session.id,\n world: {\n settings: {\n organization: {\n rotation: settings.rotation,\n inferenceSource: Object.fromEntries(\n [...providers].map((provider) => [provider, inferenceSourceFor(settings, provider)]),\n ),\n crossProviderFailover: settings.crossProviderFailover,\n fallbackOrder: Object.fromEntries(\n Object.entries(settings.fallbackOrder).map(([modelId, order]) => [modelId, [...order]]),\n ),\n personalConnectionsAllowed: settings.personalConnectionsAllowed,\n personalFallbackAllowed: settings.personalFallbackAllowed,\n },\n locked: [],\n workspaceOverrides: {},\n },\n workspaces: [\n {\n id: workspace.id,\n kind: workspace.kind,\n ownerId: workspace.ownerMembershipId,\n allowedModels: ceiling,\n },\n ],\n people: input.people.map((person) => ({\n id: person.membershipId,\n active: person.active,\n personalFallbackOptIn: person.personalFallbackOptIn,\n })),\n models: input.models.map((model) => ({\n id: model.id,\n provider: model.provider,\n reasoningLevels: model.reasoningLevels,\n tier: model.tier ?? null,\n })),\n connections: usable.map((connection) => referenceConnection(input, connection)),\n sessions: [\n {\n id: session.id,\n workspaceId: session.workspaceId,\n visibility: session.visibility,\n ownerId: session.ownerMembershipId,\n sharedPersonalChoices: session.personalAuthority.flatMap((authority) =>\n authority.sharedSessionChoice?.sessionId === session.id\n ? [\n {\n connectionId: authority.sharedSessionChoice.connectionId,\n ownerId: authority.ownerMembershipId,\n },\n ]\n : [],\n ),\n preferredModelId: session.preferredModelId,\n reasoningLevel: session.reasoningLevel,\n binding: binding\n ? {\n connectionId: binding.connectionId,\n modelId: binding.modelId,\n lastUsedAt: binding.lastModelCallAt,\n }\n : null,\n pinnedConnectionId: binding?.choice === \"explicit\" ? binding.connectionId : null,\n onlyThisModel: session.onlyThisModel,\n reselectionPoint: session.reselectionPoints.length > 0,\n },\n ],\n cacheTtlMs: Object.fromEntries(\n [...providers].map((provider) => [\n provider,\n binding?.cacheTtlMs != null &&\n input.connections.find((connection) => connection.id === binding.connectionId)\n ?.provider === provider\n ? Math.max(0, binding.cacheTtlMs)\n : lifetimeOf(input.cacheFacts[provider]),\n ]),\n ),\n },\n };\n}\n\n/**\n * The reference-shaped view of a production decision on this input. A wait\n * the production policy explains with the compaction lock is, to the\n * reference model (which sees the lock as a model restriction), a wait on the\n * restriction when no candidate model is left, else a wait for capacity.\n */\nexport function toReferenceDecision(\n decision: PlacementDecision,\n input: PlacementInput,\n): reference.Decision {\n if (decision.kind === \"run\") {\n return {\n kind: \"run\",\n connectionId: decision.connectionId,\n modelId: decision.modelId,\n reasoningLevel: decision.reasoningLevel,\n switch: decision.switch,\n };\n }\n if (decision.reason !== \"compaction_provider_locked\") {\n return { kind: \"wait\", reason: decision.reason, earliestResetAt: decision.earliestResetAt };\n }\n const { world, sessionId } = toReferenceWorld(input);\n const session = world.sessions.find((candidate) => candidate.id === sessionId)!;\n const allowed = world.workspaces[0]!.allowedModels;\n const anyAllowed = reference\n .candidateModels(world, session)\n .some((modelId) => allowed === null || allowed.includes(modelId));\n return {\n kind: \"wait\",\n reason: anyAllowed ? \"no_eligible_capacity\" : \"model_not_allowed\",\n earliestResetAt: decision.earliestResetAt,\n };\n}\n\n/** The reference model's invariant violations for a production decision on this input. */\nexport function checkPlacementDecision(\n input: PlacementInput,\n decision: PlacementDecision,\n): reference.InvariantViolation[] {\n const { world, sessionId } = toReferenceWorld(input);\n return reference.checkDecision(world, sessionId, input.now, toReferenceDecision(decision, input));\n}\n"],"mappings":";;;;;AA2FA,IAAM,QAA2B,CAAC,YAAY,YAAY,MAAM;AA8EhE,IAAM,eAAsC;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,kBAAkB,QAAwB,aAAwC;AAChG,QAAM,WAAW,OAAO,mBAAmB,WAAW,KAAK,CAAC;AAC5D,QAAM,SAAS,EAAE,GAAG,OAAO,aAAa;AACxC,QAAM,UAAU,CAAC;AACjB,aAAW,OAAO,cAAc;AAC9B,UAAM,aAAa,SAAS,GAAG,MAAM,UAAa,CAAC,OAAO,OAAO,SAAS,GAAG;AAC7E,QAAI,YAAY;AACd,MAAC,OAAuC,GAAG,IACzC,QAAQ,cAAc,QAAQ,qBAAqB,QAAQ,kBACvD,EAAE,GAAG,OAAO,aAAa,GAAG,GAAG,GAAI,SAAS,GAAG,EAAa,IAC5D,SAAS,GAAG;AAAA,IACpB;AACA,YAAQ,GAAG,IAAI,aAAa,cAAc;AAAA,EAC5C;AACA,SAAO,EAAE,QAAQ,QAAQ;AAC3B;AAIA,SAAS,KAA+B,OAAqB,IAA2B;AACtF,SAAO,MAAM,KAAK,CAAC,SAAS,KAAK,OAAO,EAAE;AAC5C;AAEO,SAAS,YAAY,OAAc,SAAyB,KAAsB;AACvF,QA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AChC,QAAM,EAAE,OAAO,UAAU,IAAI,iBAAiB,KAAK;AACnD,SAAiB,cAAc,OAAO,WAAW,MAAM,KAAK,oBAAoB,UAAU,KAAK,CAAC;AAClG;","names":[]}
1
+ {"version":3,"sources":["../src/reference-model.ts","../src/reference-bridge.ts"],"sourcesContent":["/**\n * Independent executable reference model of the subscription account contract\n * (docs/subscription-accounts.md). It is written from the contract, not from\n * the production selection code, so conformance tests can compare production\n * decisions against it. Everything here is pure and deterministic: no clock,\n * database or randomness.\n *\n * It ships in `@opengeni/subscriptions` only so the worker's shadow comparison\n * can run `checkDecision` in production; it is published through the separate\n * `@opengeni/subscriptions/reference` entry point, and the placement modules of\n * this package never import it (a test enforces both directions).\n *\n * The model answers one question: given the world and a session that wants to\n * run a turn now, which account and model must it run on, or why must it wait?\n */\n\nexport type ProviderId = string;\nexport type ModelId = string;\n\nexport type Rotation =\n | { mode: \"primary_first\"; primaryConnectionId: string | null }\n | { mode: \"spread\" };\n\nexport type SubscriptionSettings = {\n /** Per provider; a provider without an entry spreads work. */\n rotation: Record<ProviderId, Rotation>;\n /** `automatic` admits both classified shared pools; missing entries retain legacy behavior. */\n inferenceSource?: Record<ProviderId, \"automatic\" | \"workspace\" | \"organization\">;\n crossProviderFailover: boolean;\n /** Ordered fallback models for a preferred model, possibly on other providers. */\n fallbackOrder: Record<ModelId, ModelId[]>;\n personalConnectionsAllowed: boolean;\n personalFallbackAllowed: boolean;\n};\nexport type SettingKey = keyof SubscriptionSettings;\n\nexport type SettingsPolicy = {\n organization: SubscriptionSettings;\n locked: readonly SettingKey[];\n workspaceOverrides: Record<string, Partial<SubscriptionSettings>>;\n};\n\nexport type ConnectionScope =\n | { kind: \"organization\" }\n | { kind: \"workspaces\"; workspaceIds: readonly string[]; personalWorkspaces: boolean }\n | { kind: \"people\"; personIds: readonly string[] };\n\nexport type Quota =\n | { kind: \"available\" }\n | { kind: \"unknown\" }\n | { kind: \"exhausted\"; resetsAt: number | null };\n\nexport type Connection = {\n id: string;\n provider: ProviderId;\n ownership: { kind: \"shared\"; scope: ConnectionScope } | { kind: \"personal\"; ownerId: string };\n healthy: boolean;\n allocatorEnabled: boolean;\n entitledModels: readonly ModelId[];\n /** Administrator access policy on the connection; null or absent allows every entitled model. */\n allowedModelIds?: readonly ModelId[] | null;\n assignmentPolicies?: readonly {\n workspaceId: string;\n inferencePool: \"workspace\" | \"organization\";\n allowedModelIds: readonly ModelId[] | null;\n excludedModelIds?: readonly ModelId[];\n allocatorEnabled: boolean;\n managedByWorkspaceId?: string | null;\n }[];\n /** Per-model cooldowns (some providers report model-specific limits). */\n modelCooldowns?: Readonly<Record<ModelId, number>>;\n quota: Quota;\n /** Explicit consent to spend credits after the included allowance (extra-credits providers only). */\n extraCreditsEnabled?: boolean;\n /** A provider refusal blocks even paid credits until this deadline. */\n refusalUntil?: number | null;\n};\n\nexport type Workspace = {\n id: string;\n kind: \"shared\" | \"personal\";\n /** Owner of a Personal workspace. */\n ownerId: string | null;\n /** Workspace model restriction; null allows every model. */\n allowedModels: readonly ModelId[] | null;\n};\n\nexport type Person = { id: string; active: boolean; personalFallbackOptIn: boolean };\n\n/** The contract's closed set of model tiers (D-35). Tiers compare by equality only. */\nexport type Tier = \"frontier\" | \"standard\" | \"fast\";\nconst TIERS: readonly string[] = [\"frontier\", \"standard\", \"fast\"];\n\nexport type Model = {\n id: ModelId;\n provider: ProviderId;\n reasoningLevels: readonly string[];\n /** The tier its provider declares; absent or null when it declares none. */\n tier?: Tier | null;\n};\n\nexport type SessionBinding = { connectionId: string; modelId: ModelId; lastUsedAt: number };\n\nexport type Session = {\n id: string;\n workspaceId: string;\n visibility: \"private\" | \"shared\";\n /** Null only for a deliberately ownerless service session; it can use shared pools only. */\n ownerId: string | null;\n /** Exact accepted shared-chat consent; not a new account pool. */\n sharedPersonalChoices?: readonly { connectionId: string; ownerId: string }[];\n /** The model the session asked for. */\n preferredModelId: ModelId;\n reasoningLevel: string;\n binding: SessionBinding | null;\n /** An explicit account choice is a pin: the session waits for it rather than moving. */\n pinnedConnectionId: string | null;\n /** \"Only this model\": no cross-provider failover. Same-model account failover still applies. */\n onlyThisModel: boolean;\n /** A compaction completed or the model changed since the last placement (SUB-STICK-05). */\n reselectionPoint?: boolean;\n};\n\nexport type World = {\n settings: SettingsPolicy;\n workspaces: readonly Workspace[];\n people: readonly Person[];\n models: readonly Model[];\n connections: readonly Connection[];\n sessions: readonly Session[];\n /** Prompt-cache lifetime after the last use, per provider. */\n cacheTtlMs: Record<ProviderId, number>;\n};\n\nexport type SwitchKind =\n | \"initial\"\n | \"sticky\"\n | \"pinned\"\n | \"reselected_cold\"\n | \"failover_same_provider\"\n | \"failover_cross_provider\"\n | \"return_to_preferred\";\n\nexport type WaitReason =\n | \"pinned_account_unavailable\"\n | \"pinned_account_disabled\"\n /** The explicit choice can never serve this work until a person changes something (D-24). */\n | \"pinned_account_ineligible\"\n | \"no_eligible_capacity\"\n | \"model_not_allowed\"\n /** Decided before placement (an unusable accepted authority); never produced here. */\n | \"accepted_authority_unavailable\";\n\nexport type Decision =\n | {\n kind: \"run\";\n connectionId: string;\n modelId: ModelId;\n reasoningLevel: string;\n switch: SwitchKind;\n }\n | { kind: \"wait\"; reason: WaitReason; earliestResetAt: number | null };\n\n// Effective settings\n\nexport type EffectiveSettings = {\n values: SubscriptionSettings;\n sources: Record<SettingKey, \"organization\" | \"workspace\">;\n};\n\nconst SETTING_KEYS: readonly SettingKey[] = [\n \"rotation\",\n \"inferenceSource\",\n \"crossProviderFailover\",\n \"fallbackOrder\",\n \"personalConnectionsAllowed\",\n \"personalFallbackAllowed\",\n];\n\n/**\n * SUB-SET-01..03: organization default, unless a workspace overrides an\n * unlocked setting. Per-provider and per-model maps are overridden entry by\n * entry, so a workspace that sets one provider's rotation keeps the others\n * (D-25); the source is \"workspace\" when the workspace overrides any entry.\n */\nexport function effectiveSettings(policy: SettingsPolicy, workspaceId: string): EffectiveSettings {\n const override = policy.workspaceOverrides[workspaceId] ?? {};\n const values = { ...policy.organization } as SubscriptionSettings;\n const sources = {} as Record<SettingKey, \"organization\" | \"workspace\">;\n for (const key of SETTING_KEYS) {\n const overridden = override[key] !== undefined && !policy.locked.includes(key);\n if (overridden) {\n (values as Record<SettingKey, unknown>)[key] =\n key === \"rotation\" || key === \"inferenceSource\" || key === \"fallbackOrder\"\n ? { ...policy.organization[key], ...(override[key] as object) }\n : override[key];\n }\n sources[key] = overridden ? \"workspace\" : \"organization\";\n }\n return { values, sources };\n}\n\n// Eligibility\n\nfunction byId<T extends { id: string }>(items: readonly T[], id: string): T | undefined {\n return items.find((item) => item.id === id);\n}\n\nexport function isCacheWarm(world: World, binding: SessionBinding, now: number): boolean {\n const connection = byId(world.connections, binding.connectionId);\n if (!connection) return false;\n const ttl = world.cacheTtlMs[connection.provider] ?? 0;\n return now - binding.lastUsedAt <= ttl;\n}\n\nfunction hasCapacity(connection: Connection, now: number): boolean {\n // Unknown quota stays unknown: it is neither availability nor exhaustion (SUB-ELIG-06).\n return (\n connection.quota.kind !== \"exhausted\" ||\n (connection.quota.resetsAt !== null && connection.quota.resetsAt <= now) ||\n spendsCredits(connection, now)\n );\n}\n\nfunction spendsCredits(connection: Connection, now: number): boolean {\n return (\n connection.extraCreditsEnabled === true &&\n (connection.refusalUntil == null || connection.refusalUntil <= now) &&\n connection.quota.kind === \"exhausted\" &&\n (connection.quota.resetsAt === null || connection.quota.resetsAt > now)\n );\n}\n\nfunction modelAllowed(world: World, session: Session, modelId: ModelId): boolean {\n const workspace = byId(world.workspaces, session.workspaceId);\n return (\n !!workspace && (workspace.allowedModels === null || workspace.allowedModels.includes(modelId))\n );\n}\n\n/**\n * Why this connection may not serve this session's work at all, ignoring the\n * model, capacity and the explicit-choice rule for personal accounts, labelled\n * with the requirement that forbids it; null when it may.\n */\nexport function authorizationFailure(\n world: World,\n session: Session,\n connection: Connection,\n): InvariantViolation | null {\n const failure = (requirement: string, message: string) => ({ requirement, message });\n const workspace = byId(world.workspaces, session.workspaceId);\n if (!workspace) return failure(\"SUB-ELIG-01\", \"the session's workspace is unknown\");\n if (!connection.healthy || !connection.allocatorEnabled) {\n return failure(\"SUB-ELIG-04\", \"the account is unhealthy or excluded from allocation\");\n }\n if (connection.ownership.kind === \"personal\") {\n const settings = effectiveSettings(world.settings, workspace.id).values;\n const owner = byId(world.people, connection.ownership.ownerId);\n const ownersOwnWork =\n (session.ownerId !== null &&\n session.sharedPersonalChoices?.some(\n (choice) => choice.connectionId === connection.id && choice.ownerId === owner?.id,\n )) ||\n (session.ownerId === connection.ownership.ownerId &&\n (session.visibility === \"private\" ||\n (workspace.kind === \"personal\" && workspace.ownerId === connection.ownership.ownerId)));\n if (!settings.personalConnectionsAllowed) {\n return failure(\"SUB-OWN-05\", \"personal connections are disabled here\");\n }\n if (!owner?.active) return failure(\"SUB-ACCESS-06\", \"the personal account's owner left\");\n if (!ownersOwnWork) {\n return failure(\"SUB-ELIG-05\", \"a personal account served work other than its owner's own\");\n }\n return null;\n }\n if (connection.assignmentPolicies !== undefined) {\n const source =\n effectiveSettings(world.settings, workspace.id).values.inferenceSource?.[\n connection.provider\n ] ?? \"automatic\";\n const matching = connection.assignmentPolicies.filter(\n (policy) =>\n policy.workspaceId === workspace.id &&\n (source === \"automatic\" || policy.inferencePool === source),\n );\n if (matching.length === 0) {\n return failure(\"SUB-SET-06\", \"the effective inference source excludes this assignment\");\n }\n }\n const scope = connection.ownership.scope;\n const inScope =\n scope.kind === \"organization\" ||\n (scope.kind === \"workspaces\"\n ? scope.workspaceIds.includes(workspace.id) ||\n (workspace.kind === \"personal\" && scope.personalWorkspaces)\n : session.ownerId !== null && scope.personIds.includes(session.ownerId));\n return inScope ? null : failure(\"SUB-ELIG-01\", \"the account's scope excludes this work\");\n}\n\n/** May this connection serve this session's work at all? SUB-ELIG-01, 04, 05. */\nexport function isAuthorized(world: World, session: Session, connection: Connection): boolean {\n return authorizationFailure(world, session, connection) === null;\n}\n\n/**\n * Why this connection cannot serve this session on this model now, labelled\n * with the requirement that forbids it; null when it can.\n */\nexport function servingFailure(\n world: World,\n session: Session,\n connection: Connection,\n modelId: ModelId,\n now: number,\n): InvariantViolation | null {\n const model = byId(world.models, modelId);\n if (\n !model ||\n model.provider !== connection.provider ||\n !connection.entitledModels.includes(modelId)\n ) {\n return { requirement: \"SUB-ELIG-03\", message: \"the account's plan does not include the model\" };\n }\n if (connection.allowedModelIds != null && !connection.allowedModelIds.includes(modelId)) {\n return {\n requirement: \"SUB-ELIG-03\",\n message: \"the account's access policy excludes the model\",\n };\n }\n if (connection.assignmentPolicies !== undefined) {\n const workspace = byId(world.workspaces, session.workspaceId)!;\n const source =\n effectiveSettings(world.settings, workspace.id).values.inferenceSource?.[\n connection.provider\n ] ?? \"automatic\";\n const matching = connection.assignmentPolicies.filter(\n (policy) =>\n policy.workspaceId === workspace.id &&\n (source === \"automatic\" || policy.inferencePool === source),\n );\n const hasAllocatableAssignment = matching.some((policy) => policy.allocatorEnabled);\n if (!hasAllocatableAssignment) {\n return {\n requirement: \"SUB-ELIG-04\",\n message: \"the source assignment is excluded from allocation\",\n };\n }\n if (\n !matching.some(\n (policy) =>\n policy.allocatorEnabled &&\n (policy.allowedModelIds === null || policy.allowedModelIds.includes(modelId)) &&\n !policy.excludedModelIds?.includes(modelId),\n )\n ) {\n const hasModelAssignment = matching.some(\n (policy) =>\n (policy.allowedModelIds === null || policy.allowedModelIds.includes(modelId)) &&\n !policy.excludedModelIds?.includes(modelId),\n );\n return {\n requirement: hasModelAssignment ? \"SUB-ELIG-04\" : \"SUB-ELIG-03\",\n message: hasModelAssignment\n ? \"model access exists only on a source assignment excluded from allocation\"\n : \"no source assignment allows the model\",\n };\n }\n }\n if ((connection.modelCooldowns?.[modelId] ?? -Infinity) > now) {\n return { requirement: \"SUB-ELIG-03\", message: \"the account is cooling down for the model\" };\n }\n if (!modelAllowed(world, session, modelId)) {\n return { requirement: \"SUB-ELIG-02\", message: \"the workspace does not allow the model\" };\n }\n const authorization = authorizationFailure(world, session, connection);\n if (authorization) return authorization;\n if (!hasCapacity(connection, now)) {\n return { requirement: \"SUB-FAIL-02\", message: \"the account has no capacity now\" };\n }\n return null;\n}\n\nexport function canServe(\n world: World,\n session: Session,\n connection: Connection,\n modelId: ModelId,\n now: number,\n): boolean {\n return servingFailure(world, session, connection, modelId, now) === null;\n}\n\n// Selection\n\n/**\n * Deterministic hash used to spread sessions across accounts (D-21): FNV-1a\n * over the UTF-16 code units, finished with the murmur3 finalizer, because raw\n * FNV-1a orders similar keys unevenly and so spreads unfairly (SUB-SEL-03, D-23).\n */\nexport function spreadHash(sessionId: string, connectionId: string): number {\n let hash = 0x811c9dc5;\n const key = sessionId + \"|\" + connectionId;\n for (let index = 0; index < key.length; index += 1) {\n hash ^= key.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n // murmur3 fmix32\n hash = Math.imul(hash ^ (hash >>> 16), 0x85ebca6b) >>> 0;\n hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35) >>> 0;\n return (hash ^ (hash >>> 16)) >>> 0;\n}\n\n/**\n * Rank servable connections for one model. In Primary first the primary takes\n * new work whenever it can serve it, and unknown quota counts as able to serve\n * (D-13, D-14, D-15). Every other choice ranks known capacity before unknown\n * quota (D-14), then a deterministic per-session hash spreads sessions (D-21),\n * then the connection id breaks ties.\n */\nfunction pick(world: World, session: Session, candidates: Connection[]): Connection | null {\n if (candidates.length === 0) return null;\n const provider = candidates[0]!.provider;\n const rotation =\n effectiveSettings(world.settings, session.workspaceId).values.rotation[provider] ??\n ({ mode: \"spread\" } as Rotation);\n if (rotation.mode === \"primary_first\") {\n const primary = candidates.find((candidate) => candidate.id === rotation.primaryConnectionId);\n if (primary) return primary;\n }\n const ranked = [...candidates].sort((left, right) => {\n const spread = spreadHash(session.id, left.id) - spreadHash(session.id, right.id);\n if (spread !== 0) return spread;\n return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;\n });\n return ranked[0]!;\n}\n\n/**\n * SUB-FAIL-03 and D-16: the reasoning level to run `model` at when the session\n * asked for `requested` on its preferred model `from`.\n *\n * 1. The same level name when the model supports it.\n * 2. Otherwise the model's level whose relative position on its own ladder\n * (lowest 0, highest 1) is closest to the requested level's relative\n * position on the preferred model's ladder. A tie goes to the lower level.\n * 3. A level the preferred model does not list has no position and maps to\n * the middle of the ladder (the lower middle when there are two).\n */\nexport function nearestReasoningLevel(\n model: Model,\n requested: string,\n from: Model | undefined,\n): string {\n const levels = model.reasoningLevels;\n if (levels.includes(requested)) return requested;\n if (levels.length <= 1) return levels[0] ?? \"\";\n const source = from?.reasoningLevels ?? [];\n const sourceIndex = source.indexOf(requested);\n // The requested position as an exact fraction, so ties are exact.\n const [numerator, denominator] =\n sourceIndex < 0 || source.length <= 1 ? [1, 2] : [sourceIndex, source.length - 1];\n // |index / (levels - 1) - numerator / denominator|, scaled by both denominators.\n const distance = (index: number) =>\n Math.abs(index * denominator - numerator * (levels.length - 1));\n let best = 0;\n for (let index = 1; index < levels.length; index += 1) {\n if (distance(index) < distance(best)) best = index;\n }\n return levels[best]!;\n}\n\n/**\n * D-35: the fallback order of a preferred model the settings name no entry\n * for. Only with cross-provider failover on, and only when the preferred\n * model declares a tier: every model of another provider declaring exactly\n * that tier (Q-04: never a lower or higher one), provider by provider in\n * sorted id order, each provider's models in the world's order, at most 8.\n * The preferred model's own provider contributes nothing (same-provider\n * model fallback is explicit only).\n */\nexport function derivedFallbacks(\n world: World,\n settings: SubscriptionSettings,\n preferredModelId: ModelId,\n): ModelId[] {\n const preferred = byId(world.models, preferredModelId);\n if (!settings.crossProviderFailover || !preferred) return [];\n const tier = preferred.tier;\n if (typeof tier !== \"string\" || !TIERS.includes(tier)) return [];\n const otherProviders = [...new Set(world.models.map((model) => model.provider))]\n .filter((provider) => provider !== preferred.provider)\n .sort();\n const derived: ModelId[] = [];\n for (const provider of otherProviders) {\n for (const model of world.models) {\n if (model.provider !== provider || model.tier !== tier) continue;\n if (model.id === preferredModelId || derived.includes(model.id)) continue;\n derived.push(model.id);\n }\n }\n return derived.slice(0, 8);\n}\n\n/**\n * Candidate models in failover order: the preferred model, then (if allowed)\n * its fallbacks. An explicit entry for the preferred model, even an empty\n * list, is the order; only a missing entry derives one (D-35).\n */\nexport function candidateModels(world: World, session: Session): ModelId[] {\n const settings = effectiveSettings(world.settings, session.workspaceId).values;\n const preferred = session.preferredModelId;\n if (session.onlyThisModel || session.pinnedConnectionId) return [preferred];\n const preferredProvider = byId(world.models, preferred)?.provider;\n const explicit = Object.prototype.hasOwnProperty.call(settings.fallbackOrder, preferred);\n const order = explicit\n ? (settings.fallbackOrder[preferred] ?? [])\n : derivedFallbacks(world, settings, preferred);\n // Same-provider fallback models are always allowed; other providers only\n // when cross-provider failover is on (SUB-FAIL-02, SUB-FAIL-03).\n const fallbacks = order.filter(\n (modelId, index, all) =>\n modelId !== preferred &&\n all.indexOf(modelId) === index &&\n (byId(world.models, modelId)?.provider === preferredProvider ||\n settings.crossProviderFailover),\n );\n return [preferred, ...fallbacks];\n}\n\n/**\n * D-24: an explicit choice that can never serve this session's model: gone,\n * no longer authorized for this work, another provider's account, or not\n * entitled or allowed for the model. Health, allocation, capacity and\n * cooldowns recover, so they never make an explicit choice permanently unusable.\n */\nexport function pinnedNeverServes(\n world: World,\n session: Session,\n pinned: Connection | undefined,\n): boolean {\n if (!pinned) return true;\n const model = byId(world.models, session.preferredModelId);\n if (!model || model.provider !== pinned.provider) return true;\n if (!pinned.entitledModels.includes(model.id)) return true;\n if (pinned.allowedModelIds != null && !pinned.allowedModelIds.includes(model.id)) return true;\n if (pinned.assignmentPolicies !== undefined) {\n const source =\n effectiveSettings(world.settings, session.workspaceId).values.inferenceSource?.[\n pinned.provider\n ] ?? \"automatic\";\n const assignments = pinned.assignmentPolicies.filter(\n (policy) =>\n policy.workspaceId === session.workspaceId &&\n (source === \"automatic\" || policy.inferencePool === source),\n );\n if (\n !assignments.some(\n (policy) =>\n (policy.allowedModelIds === null || policy.allowedModelIds.includes(model.id)) &&\n !policy.excludedModelIds?.includes(model.id),\n )\n ) {\n return true;\n }\n }\n return !isAuthorized(world, session, { ...pinned, healthy: true, allocatorEnabled: true });\n}\n\nfunction pinnedAllocationDisabled(world: World, session: Session, pinned: Connection): boolean {\n if (!pinned.allocatorEnabled) return true;\n if (pinned.assignmentPolicies === undefined) return false;\n const source =\n effectiveSettings(world.settings, session.workspaceId).values.inferenceSource?.[\n pinned.provider\n ] ?? \"automatic\";\n return !pinned.assignmentPolicies.some(\n (policy) =>\n policy.workspaceId === session.workspaceId &&\n (source === \"automatic\" || policy.inferencePool === source) &&\n policy.allocatorEnabled,\n );\n}\n\n/** Future times at which some quota or model cooldown in the world resets, ascending. */\nfunction futureResetTimes(world: World, now: number): number[] {\n const times = new Set<number>();\n for (const connection of world.connections) {\n if (\n connection.quota.kind === \"exhausted\" &&\n connection.quota.resetsAt !== null &&\n connection.quota.resetsAt > now\n ) {\n times.add(connection.quota.resetsAt);\n }\n if (connection.refusalUntil != null && connection.refusalUntil > now)\n times.add(connection.refusalUntil);\n for (const until of Object.values(connection.modelCooldowns ?? {})) {\n if (until > now) times.add(until);\n }\n }\n return [...times].sort((left, right) => left - right);\n}\n\n/**\n * SUB-WAIT-02, D-22: the earliest future time at which the session could run,\n * assuming nothing else changes; null when no known reset makes it runnable.\n */\nexport function earliestRunnableAt(\n world: World,\n now: number,\n runnableAt: (at: number) => boolean,\n): number | null {\n return futureResetTimes(world, now).find(runnableAt) ?? null;\n}\n\nfunction personalFallbackFor(world: World, session: Session): boolean {\n if (session.ownerId === null) return false;\n if (\n session.visibility === \"shared\" &&\n byId(world.workspaces, session.workspaceId)?.kind === \"shared\"\n )\n return false;\n const settings = effectiveSettings(world.settings, session.workspaceId).values;\n return (\n (byId(world.workspaces, session.workspaceId)?.kind === \"personal\" &&\n byId(world.workspaces, session.workspaceId)?.ownerId === session.ownerId) ||\n (settings.personalFallbackAllowed &&\n !!byId(world.people, session.ownerId)?.personalFallbackOptIn)\n );\n}\n\n/**\n * The contract's decision for a session that wants to run a turn now. The\n * sender is deliberately not an input: the account belongs to the session\n * (SUB-STICK-01).\n */\nexport function decide(world: World, sessionId: string, now: number): Decision {\n const session = byId(world.sessions, sessionId);\n if (!session) throw new Error(\"unknown session \" + sessionId);\n const preferredModel = byId(world.models, session.preferredModelId);\n const level = (model: ModelId) =>\n nearestReasoningLevel(byId(world.models, model)!, session.reasoningLevel, preferredModel);\n const run = (connectionId: string, modelId: ModelId, kind: SwitchKind): Decision => ({\n kind: \"run\",\n connectionId,\n modelId,\n reasoningLevel: level(modelId),\n switch: kind,\n });\n\n // A restricted preferred model falls through to its allowed failover\n // candidates (SUB-ELIG-02, SUB-WAIT-01, D-17); waiting on the restriction is\n // right only when no candidate is allowed.\n const models = candidateModels(world, session);\n const allowedModels = models.filter((modelId) => modelAllowed(world, session, modelId));\n if (allowedModels.length === 0) {\n return { kind: \"wait\", reason: \"model_not_allowed\", earliestResetAt: null };\n }\n\n // Explicit choice is a pin (SUB-SEL-04, SUB-FAIL-05, SUB-STICK-06).\n if (session.pinnedConnectionId) {\n const pinned = byId(world.connections, session.pinnedConnectionId);\n if (pinned && canServe(world, session, pinned, session.preferredModelId, now)) {\n return run(pinned.id, session.preferredModelId, \"pinned\");\n }\n // It can never serve this work: explain that instead of waiting silently (D-24).\n if (pinnedNeverServes(world, session, pinned)) {\n return { kind: \"wait\", reason: \"pinned_account_ineligible\", earliestResetAt: null };\n }\n if (pinned && pinnedAllocationDisabled(world, session, pinned)) {\n return { kind: \"wait\", reason: \"pinned_account_disabled\", earliestResetAt: null };\n }\n // Otherwise the earliest future time the chosen account can serve (D-22).\n return {\n kind: \"wait\",\n reason: \"pinned_account_unavailable\",\n earliestResetAt: earliestRunnableAt(world, now, (at) =>\n canServe(world, session, pinned!, session.preferredModelId, at),\n ),\n };\n }\n\n const binding = session.binding;\n const bound = binding ? byId(world.connections, binding.connectionId) : undefined;\n const personalFallback = personalFallbackFor(world, session);\n const bindingServable =\n !!binding &&\n !!bound &&\n models.includes(binding.modelId) &&\n canServe(world, session, bound, binding.modelId, now);\n\n // Stickiness while the cache is warm (SUB-STICK-02, SUB-STICK-03, SUB-FAIL-07).\n const includedAlternative = (modelId: string) =>\n world.connections.some(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n !spendsCredits(connection, now) &&\n canServe(world, session, connection, modelId, now),\n );\n if (\n binding &&\n bound &&\n bindingServable &&\n !session.reselectionPoint &&\n isCacheWarm(world, binding, now) &&\n (!spendsCredits(bound, now) || !includedAlternative(binding.modelId))\n ) {\n return run(binding.connectionId, binding.modelId, \"sticky\");\n }\n\n // Order: each candidate model on shared accounts, then (opt-in) on the\n // owner's personal accounts, before moving to the next model (D-12).\n for (const [index, modelId] of models.entries()) {\n const eligible = world.connections.filter(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n canServe(world, session, connection, modelId, now),\n );\n const included = eligible.filter((connection) => !spendsCredits(connection, now));\n const servable = included.length ? included : eligible;\n const shared = servable.filter((connection) => connection.ownership.kind === \"shared\");\n const personal = servable.filter((connection) => connection.ownership.kind === \"personal\");\n const chosen =\n pick(world, session, shared) ?? (personalFallback ? pick(world, session, personal) : null);\n if (!chosen) continue;\n let kind: SwitchKind;\n if (!binding) kind = \"initial\";\n else if (binding.connectionId === chosen.id && binding.modelId === modelId) kind = \"sticky\";\n else if (index === 0 && binding.modelId !== modelId) kind = \"return_to_preferred\";\n else if (index > 0)\n kind =\n byId(world.models, modelId)?.provider ===\n byId(world.models, session.preferredModelId)?.provider\n ? \"failover_same_provider\"\n : \"failover_cross_provider\";\n else if (bindingServable) kind = \"reselected_cold\";\n else kind = \"failover_same_provider\";\n return run(chosen.id, modelId, kind);\n }\n return {\n kind: \"wait\",\n reason: \"no_eligible_capacity\",\n earliestResetAt: earliestRunnableAt(world, now, (at) =>\n allowedModels.some((modelId) =>\n world.connections.some(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n canServe(world, session, connection, modelId, at),\n ),\n ),\n ),\n };\n}\n\n/** Record that a decision ran: the session binds to the chosen account. */\nexport function applyDecision(\n world: World,\n sessionId: string,\n decision: Decision,\n now: number,\n): World {\n if (decision.kind !== \"run\") return world;\n return {\n ...world,\n sessions: world.sessions.map((session) =>\n session.id === sessionId\n ? {\n ...session,\n binding: {\n connectionId: decision.connectionId,\n modelId: decision.modelId,\n lastUsedAt: now,\n },\n }\n : session,\n ),\n };\n}\n\n// Invariants\n\nexport type InvariantViolation = { requirement: string; message: string };\n\n/**\n * Check any decision (from this model or from production) against the\n * contract's invariants for this world. An empty result means the decision is\n * acceptable; it does not require the decision to equal the model's own.\n */\nexport function checkDecision(\n world: World,\n sessionId: string,\n now: number,\n decision: Decision,\n): InvariantViolation[] {\n const violations: InvariantViolation[] = [];\n const session = byId(world.sessions, sessionId)!;\n const settings = effectiveSettings(world.settings, session.workspaceId).values;\n const models = candidateModels(world, session);\n const fail = (requirement: string, message: string) => violations.push({ requirement, message });\n\n const personalFallback = personalFallbackFor(world, session);\n const servableShared = (modelId: ModelId, credits: boolean) =>\n world.connections.some(\n (connection) =>\n connection.ownership.kind === \"shared\" &&\n (credits || !spendsCredits(connection, now)) &&\n canServe(world, session, connection, modelId, now),\n );\n const servableAutomatically = (modelId: ModelId) =>\n world.connections.some(\n (connection) =>\n canServe(world, session, connection, modelId, now) &&\n (connection.ownership.kind === \"shared\" || personalFallback),\n );\n const anyServable = models.some(servableAutomatically);\n const binding = session.binding;\n const bindingWarm = !!binding && !session.reselectionPoint && isCacheWarm(world, binding, now);\n\n if (decision.kind === \"run\") {\n const connection = byId(world.connections, decision.connectionId);\n if (!connection) {\n fail(\"SUB-ELIG-01\", \"the chosen account does not exist\");\n return violations;\n }\n const ineligible = servingFailure(world, session, connection, decision.modelId, now);\n if (ineligible) {\n violations.push(ineligible);\n return violations;\n }\n if (session.pinnedConnectionId && decision.connectionId !== session.pinnedConnectionId) {\n fail(\"SUB-SEL-04\", \"a pinned session ran on another account\");\n }\n if (!models.includes(decision.modelId)) {\n fail(\"SUB-FAIL-04\", \"ran a model outside the allowed failover candidates\");\n }\n const crossProvider =\n byId(world.models, decision.modelId)?.provider !==\n byId(world.models, session.preferredModelId)?.provider;\n if (crossProvider && (!settings.crossProviderFailover || session.onlyThisModel)) {\n fail(\"SUB-FAIL-03\", \"moved across providers although that is not allowed\");\n }\n const expectedLevel = nearestReasoningLevel(\n byId(world.models, decision.modelId)!,\n session.reasoningLevel,\n byId(world.models, session.preferredModelId),\n );\n if (decision.reasoningLevel !== expectedLevel) {\n fail(\"SUB-FAIL-03\", \"ran at a reasoning level other than the nearest supported level\");\n }\n // Staying on the current account while its cache is warm is always allowed\n // (SUB-STICK-02); every other placement must respect the failover order.\n const stayingWarm =\n !!binding &&\n bindingWarm &&\n binding.connectionId === decision.connectionId &&\n binding.modelId === decision.modelId;\n if (!stayingWarm && !session.pinnedConnectionId) {\n const index = models.indexOf(decision.modelId);\n if (models.slice(0, Math.max(index, 0)).some(servableAutomatically)) {\n fail(\"SUB-FAIL-02\", \"skipped an earlier failover candidate that could still run\");\n }\n if (\n connection.ownership.kind === \"personal\" &&\n (!personalFallback || servableShared(decision.modelId, spendsCredits(connection, now)))\n ) {\n fail(\"SUB-SEL-02\", \"used a personal account without an explicit choice or opt-in fallback\");\n }\n }\n const includedAlternative = (modelId: string) =>\n world.connections.some(\n (candidate) =>\n (candidate.ownership.kind === \"shared\" || personalFallback) &&\n !spendsCredits(candidate, now) &&\n canServe(world, session, candidate, modelId, now),\n );\n if (\n !session.pinnedConnectionId &&\n spendsCredits(connection, now) &&\n includedAlternative(decision.modelId)\n ) {\n fail(\"SUB-CREDITS-01\", \"spent extra credits while an eligible account had included capacity\");\n }\n if (binding && bindingWarm && !session.pinnedConnectionId) {\n const bound = byId(world.connections, binding.connectionId);\n const stillServable =\n !!bound &&\n (!spendsCredits(bound, now) || !includedAlternative(binding.modelId)) &&\n models.includes(binding.modelId) &&\n canServe(world, session, bound, binding.modelId, now);\n if (\n stillServable &&\n (decision.connectionId !== binding.connectionId || decision.modelId !== binding.modelId)\n ) {\n fail(\n \"SUB-STICK-02\",\n \"switched account or model while the cache was warm and nothing forced it\",\n );\n }\n }\n } else {\n // Only a real workspace model restriction justifies this reason: no\n // candidate model, the preferred one or an allowed fallback, is allowed.\n if (\n decision.reason === \"model_not_allowed\" &&\n models.some((modelId) => modelAllowed(world, session, modelId))\n ) {\n fail(\"SUB-WAIT-01\", \"waited for a model restriction although an allowed model exists\");\n }\n const pinned = session.pinnedConnectionId\n ? byId(world.connections, session.pinnedConnectionId)\n : undefined;\n const pinnedServable =\n !!pinned && canServe(world, session, pinned, session.preferredModelId, now);\n if (session.pinnedConnectionId ? pinnedServable : anyServable) {\n fail(\"SUB-WAIT-01\", \"waited although an eligible account had capacity\");\n }\n // The wait explains itself (SUB-WAIT-02, D-24) and names the earliest time\n // a known reset makes the session runnable (SUB-WAIT-02, D-22).\n const allowedModels = models.filter((modelId) => modelAllowed(world, session, modelId));\n const never = !!session.pinnedConnectionId && pinnedNeverServes(world, session, pinned);\n const expectedReason: WaitReason =\n allowedModels.length === 0\n ? \"model_not_allowed\"\n : session.pinnedConnectionId\n ? never\n ? \"pinned_account_ineligible\"\n : pinned && pinnedAllocationDisabled(world, session, pinned)\n ? \"pinned_account_disabled\"\n : \"pinned_account_unavailable\"\n : \"no_eligible_capacity\";\n if (decision.reason !== expectedReason) {\n fail(\n never && decision.reason === \"pinned_account_unavailable\" ? \"SUB-ACCESS-06\" : \"SUB-WAIT-02\",\n \"explained the wait with \" + decision.reason + \" instead of \" + expectedReason,\n );\n }\n const expectedReset =\n expectedReason === \"pinned_account_unavailable\"\n ? earliestRunnableAt(world, now, (at) =>\n canServe(world, session, pinned!, session.preferredModelId, at),\n )\n : expectedReason === \"no_eligible_capacity\"\n ? earliestRunnableAt(world, now, (at) =>\n allowedModels.some((modelId) =>\n world.connections.some(\n (connection) =>\n (connection.ownership.kind === \"shared\" || personalFallback) &&\n canServe(world, session, connection, modelId, at),\n ),\n ),\n )\n : null;\n if (decision.reason === expectedReason && decision.earliestResetAt !== expectedReset) {\n fail(\"SUB-WAIT-02\", \"did not name the earliest time a reset makes the session runnable\");\n }\n }\n return violations;\n}\n","/**\n * Bridge from the production placement input to the independent reference\n * model, so the reference `checkDecision` can judge a production decision for\n * a real world (the worker's shadow comparison). It maps the production\n * concepts the reference model does not have onto ones it does, using only the\n * raw inputs, never the production eligibility or placement functions, so a\n * policy bug cannot hide from the checker:\n *\n * - A provider switched off, a compaction provider lock and the workspace\n * model ceiling become the workspace's allowed model list.\n * - Shared connections a workspace does not manage while organization\n * accounts are off, and personal connections without frozen personal\n * authority for their provider, are left out (nothing may use them).\n * - Quota and cache lifetimes are decoded here, independently of the\n * production decoders, from the raw shared quota model (design 2.2) and\n * cache facts (design 6.1), including the input's staleness bounds. An\n * exhaustion with no known reset stays exhausted, including when evaluating\n * the separate permission to spend extra credits.\n * - An exact cache lifetime on the binding is that provider's lifetime.\n * - An explicit binding is the reference model's pin.\n * - Model tiers pass through as declared, and the fallback order keeps its\n * own entries only, so the reference derives its own default order for a\n * preferred model without an entry (D-35).\n */\nimport * as reference from \"./reference-model\";\nimport { inferenceSourceFor } from \"./settings\";\nimport type {\n CacheFacts,\n PlacementDecision,\n PlacementInput,\n SubscriptionConnection,\n SubscriptionQuota,\n} from \"./types\";\n\n/** Design 6.1: an unmeasured idle cut-off counts as one hour. */\nconst UNMEASURED_CUTOFF_MS = 3_600_000;\n\nfunction lifetimeOf(facts: CacheFacts | undefined): number {\n if (facts?.kind === \"exact_ttl\") return Math.max(0, facts.ttlMs);\n return Math.max(0, facts?.cutoffMs ?? UNMEASURED_CUTOFF_MS);\n}\n\ntype DecodedQuota = reference.Quota;\n\n/**\n * Design 2.2 read from the raw fields: a running deadline or exhausted\n * window is exhaustion until its latest reset; any fresh observed window, an\n * exhausted window whose reset passed, or a passed quota deadline is known\n * capacity; nothing else is known (SUB-ELIG-06).\n */\nfunction decodeQuota(\n quota: SubscriptionQuota | null,\n now: number,\n staleAfterMs: number | undefined,\n): DecodedQuota {\n if (quota === null) return { kind: \"unknown\" };\n const fresh =\n staleAfterMs === undefined ||\n (quota.observedAt !== null && now - quota.observedAt <= staleAfterMs);\n const blockingResets: (number | null)[] = [];\n if (quota.exhaustedUntil !== null && quota.exhaustedUntil > now) {\n blockingResets.push(quota.exhaustedUntil);\n }\n for (const window of quota.windows) {\n if (window.status === \"exhausted\" && (window.resetsAt === null || window.resetsAt > now)) {\n blockingResets.push(window.resetsAt);\n }\n }\n if (blockingResets.length > 0) {\n return blockingResets.includes(null)\n ? { kind: \"exhausted\", resetsAt: null }\n : { kind: \"exhausted\", resetsAt: Math.max(...(blockingResets as number[])) };\n }\n const observed =\n quota.windows.some((window) => window.status !== \"unknown\") ||\n (quota.exhaustedUntil !== null && quota.exhaustedKind === \"quota\");\n return observed && fresh ? { kind: \"available\" } : { kind: \"unknown\" };\n}\n\nfunction referenceConnection(\n input: PlacementInput,\n connection: SubscriptionConnection,\n): reference.Connection {\n const providerModels = input.models\n .filter((model) => model.provider === connection.provider)\n .map((model) => model.id);\n const entitled = (connection.entitledModelIds ?? providerModels).filter(\n (modelId) => !connection.excludedModelIds.includes(modelId),\n );\n const capacity = decodeQuota(\n connection.quota,\n input.now,\n input.quotaStaleAfterMs?.[connection.provider],\n );\n const ownership: reference.Connection[\"ownership\"] =\n connection.ownership.kind === \"personal\"\n ? { kind: \"personal\", ownerId: connection.ownership.ownerMembershipId }\n : {\n kind: \"shared\",\n scope:\n connection.ownership.scope.kind === \"organization\"\n ? { kind: \"organization\" }\n : connection.ownership.scope.kind === \"workspaces\"\n ? {\n kind: \"workspaces\",\n workspaceIds: connection.ownership.scope.workspaceIds,\n personalWorkspaces: connection.ownership.scope.allowPersonalWorkspaces,\n }\n : { kind: \"people\", personIds: connection.ownership.scope.membershipIds },\n };\n return {\n id: connection.id,\n provider: connection.provider,\n ownership,\n healthy: connection.health === \"healthy\",\n allocatorEnabled: connection.allocatorEnabled,\n extraCreditsEnabled: connection.extraCreditsEnabled === true,\n refusalUntil: connection.quota?.exhaustedUntil ?? null,\n entitledModels: entitled,\n allowedModelIds: connection.allowedModelIds,\n ...(connection.assignmentPolicies === undefined\n ? {}\n : { assignmentPolicies: connection.assignmentPolicies }),\n modelCooldowns: { ...connection.quota?.modelCooldowns },\n quota: capacity,\n };\n}\n\n/** The reference world equivalent to one production placement input. */\nexport function toReferenceWorld(input: PlacementInput): {\n world: reference.World;\n sessionId: string;\n} {\n const { session, settings, workspace } = input;\n const switches = (provider: string) => settings.providers[provider];\n const ceiling = input.models\n .filter(\n (model) =>\n (workspace.allowedModelIds === null || workspace.allowedModelIds.includes(model.id)) &&\n switches(model.provider)?.enabled !== false &&\n (session.compactionProviderLock === null ||\n model.provider === session.compactionProviderLock),\n )\n .map((model) => model.id);\n const usable = input.connections.filter((connection) => {\n if (connection.ownership.kind === \"personal\") {\n const owner = connection.ownership.ownerMembershipId;\n return session.personalAuthority.some(\n (authority) =>\n authority.provider === connection.provider &&\n authority.ownerMembershipId === owner &&\n (!authority.sharedSessionChoice ||\n (authority.sharedSessionChoice.sessionId === session.id &&\n authority.sharedSessionChoice.connectionId === connection.id)),\n );\n }\n if (connection.assignmentPolicies !== undefined) return true;\n const source = inferenceSourceFor(settings, connection.provider);\n const managedHere = connection.ownership.managedByWorkspaceId === workspace.id;\n if (source === \"workspace\") return managedHere;\n if (source === \"organization\") return !managedHere;\n return source === \"automatic\" || managedHere;\n });\n const providers = new Set([\n ...input.models.map((model) => model.provider),\n ...input.connections.map((connection) => connection.provider),\n ]);\n const binding = session.binding;\n return {\n sessionId: session.id,\n world: {\n settings: {\n organization: {\n rotation: settings.rotation,\n inferenceSource: Object.fromEntries(\n [...providers].map((provider) => [provider, inferenceSourceFor(settings, provider)]),\n ),\n crossProviderFailover: settings.crossProviderFailover,\n fallbackOrder: Object.fromEntries(\n Object.entries(settings.fallbackOrder).map(([modelId, order]) => [modelId, [...order]]),\n ),\n personalConnectionsAllowed: settings.personalConnectionsAllowed,\n personalFallbackAllowed: settings.personalFallbackAllowed,\n },\n locked: [],\n workspaceOverrides: {},\n },\n workspaces: [\n {\n id: workspace.id,\n kind: workspace.kind,\n ownerId: workspace.ownerMembershipId,\n allowedModels: ceiling,\n },\n ],\n people: input.people.map((person) => ({\n id: person.membershipId,\n active: person.active,\n personalFallbackOptIn: person.personalFallbackOptIn,\n })),\n models: input.models.map((model) => ({\n id: model.id,\n provider: model.provider,\n reasoningLevels: model.reasoningLevels,\n tier: model.tier ?? null,\n })),\n connections: usable.map((connection) => referenceConnection(input, connection)),\n sessions: [\n {\n id: session.id,\n workspaceId: session.workspaceId,\n visibility: session.visibility,\n ownerId: session.ownerMembershipId,\n sharedPersonalChoices: session.personalAuthority.flatMap((authority) =>\n authority.sharedSessionChoice?.sessionId === session.id\n ? [\n {\n connectionId: authority.sharedSessionChoice.connectionId,\n ownerId: authority.ownerMembershipId,\n },\n ]\n : [],\n ),\n preferredModelId: session.preferredModelId,\n reasoningLevel: session.reasoningLevel,\n binding: binding\n ? {\n connectionId: binding.connectionId,\n modelId: binding.modelId,\n lastUsedAt: binding.lastModelCallAt,\n }\n : null,\n pinnedConnectionId: binding?.choice === \"explicit\" ? binding.connectionId : null,\n onlyThisModel: session.onlyThisModel,\n reselectionPoint: session.reselectionPoints.length > 0,\n },\n ],\n cacheTtlMs: Object.fromEntries(\n [...providers].map((provider) => [\n provider,\n binding?.cacheTtlMs != null &&\n input.connections.find((connection) => connection.id === binding.connectionId)\n ?.provider === provider\n ? Math.max(0, binding.cacheTtlMs)\n : lifetimeOf(input.cacheFacts[provider]),\n ]),\n ),\n },\n };\n}\n\n/**\n * The reference-shaped view of a production decision on this input. A wait\n * the production policy explains with the compaction lock is, to the\n * reference model (which sees the lock as a model restriction), a wait on the\n * restriction when no candidate model is left, else a wait for capacity.\n */\nexport function toReferenceDecision(\n decision: PlacementDecision,\n input: PlacementInput,\n): reference.Decision {\n if (decision.kind === \"run\") {\n return {\n kind: \"run\",\n connectionId: decision.connectionId,\n modelId: decision.modelId,\n reasoningLevel: decision.reasoningLevel,\n switch: decision.switch,\n };\n }\n if (decision.reason !== \"compaction_provider_locked\") {\n return { kind: \"wait\", reason: decision.reason, earliestResetAt: decision.earliestResetAt };\n }\n const { world, sessionId } = toReferenceWorld(input);\n const session = world.sessions.find((candidate) => candidate.id === sessionId)!;\n const allowed = world.workspaces[0]!.allowedModels;\n const anyAllowed = reference\n .candidateModels(world, session)\n .some((modelId) => allowed === null || allowed.includes(modelId));\n return {\n kind: \"wait\",\n reason: anyAllowed ? \"no_eligible_capacity\" : \"model_not_allowed\",\n earliestResetAt: decision.earliestResetAt,\n };\n}\n\n/** The reference model's invariant violations for a production decision on this input. */\nexport function checkPlacementDecision(\n input: PlacementInput,\n decision: PlacementDecision,\n): reference.InvariantViolation[] {\n const { world, sessionId } = toReferenceWorld(input);\n return reference.checkDecision(world, sessionId, input.now, toReferenceDecision(decision, input));\n}\n"],"mappings":";;;;;AA2FA,IAAM,QAA2B,CAAC,YAAY,YAAY,MAAM;AA+EhE,IAAM,eAAsC;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,kBAAkB,QAAwB,aAAwC;AAChG,QAAM,WAAW,OAAO,mBAAmB,WAAW,KAAK,CAAC;AAC5D,QAAM,SAAS,EAAE,GAAG,OAAO,aAAa;AACxC,QAAM,UAAU,CAAC;AACjB,aAAW,OAAO,cAAc;AAC9B,UAAM,aAAa,SAAS,GAAG,MAAM,UAAa,CAAC,OAAO,OAAO,SAAS,GAAG;AAC7E,QAAI,YAAY;AACd,MAAC,OAAuC,GAAG,IACzC,QAAQ,cAAc,QAAQ,qBAAqB,QAAQ,kBACvD,EAAE,GAAG,OAAO,aAAa,GAAG,GAAG,GAAI,SAAS,GAAG,EAAa,IAC5D,SAAS,GAAG;AAAA,IACpB;AACA,YAAQ,GAAG,IAAI,aAAa,cAAc;AAAA,EAC5C;AACA,SAAO,EAAE,QAAQ,QA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;AAC3B,WAAO;AAAA,MACL,MAAM;AAAA,MACN,cAAc,SAAS;AAAA,MACvB,SAAS,SAAS;AAAA,MAClB,gBAAgB,SAAS;AAAA,MACzB,QAAQ,SAAS;AAAA,IACnB;AAAA,EACF;AACA,MAAI,SAAS,WAAW,8BAA8B;AACpD,WAAO,EAAE,MAAM,QAAQ,QAAQ,SAAS,QAAQ,iBAAiB,SAAS,gBAAgB;AAAA,EAC5F;AACA,QAAM,EAAE,OAAO,UAAU,IAAI,iBAAiB,KAAK;AACnD,QAAM,UAAU,MAAM,SAAS,KAAK,CAAC,cAAc,UAAU,OAAO,SAAS;AAC7E,QAAM,UAAU,MAAM,WAAW,CAAC,EAAG;AACrC,QAAM,aACH,gBAAgB,OAAO,OAAO,EAC9B,KAAK,CAAC,YAAY,YAAY,QAAQ,QAAQ,SAAS,OAAO,CAAC;AAClE,SAAO;AAAA,IACL,MAAM;AAAA,IACN,QAAQ,aAAa,yBAAyB;AAAA,IAC9C,iBAAiB,SAAS;AAAA,EAC5B;AACF;AAGO,SAAS,uBACd,OACA,UACgC;AAChC,QAAM,EAAE,OAAO,UAAU,IAAI,iBAAiB,KAAK;AACnD,SAAiB,cAAc,OAAO,WAAW,MAAM,KAAK,oBAAoB,UAAU,KAAK,CAAC;AAClG;","names":[]}
package/dist/types.d.ts CHANGED
@@ -89,12 +89,33 @@ export type QuotaWindow = {
89
89
  status: QuotaWindowStatus;
90
90
  };
91
91
  export type QuotaSource = "usage_endpoint" | "response_headers" | "refusal";
92
+ /**
93
+ * Which reported limits one stored block (a model cooldown, or the quota
94
+ * exhaustion deadline) came from: the provider's own window ids, as the
95
+ * observation that set the block named them, tied to that block's exact
96
+ * deadline. A block whose deadline no longer equals `until` (a later write
97
+ * extended it without evidence) has no claim. A block without a claim (an
98
+ * unrecognized or missing limit, or a refusal without usage evidence) never
99
+ * ends before its own deadline.
100
+ */
101
+ export type QuotaBlockClaim = {
102
+ /** The deadline of the block this claim explains. */
103
+ until: number;
104
+ /** When the observation that set the block was made. */
105
+ observedAt: number;
106
+ /** The provider window ids whose limit set the block (never empty). */
107
+ windowIds: readonly string[];
108
+ };
92
109
  export type SubscriptionQuota = {
93
110
  windows: readonly QuotaWindow[];
94
111
  /** Per-model cooldowns (model-specific limits some providers report). */
95
112
  modelCooldowns: Readonly<Record<ModelId, number>>;
113
+ /** Optional evidence per model cooldown (see `QuotaBlockClaim`); absent: none. */
114
+ modelCooldownClaims?: Readonly<Record<ModelId, QuotaBlockClaim>>;
96
115
  exhaustedUntil: number | null;
97
116
  exhaustedKind: "quota" | "rate_limit" | null;
117
+ /** Optional evidence for `exhaustedUntil` (see `QuotaBlockClaim`); absent: none. */
118
+ exhaustedClaim?: QuotaBlockClaim | null;
98
119
  revision: number;
99
120
  observedAt: number | null;
100
121
  observedRefreshGeneration: number | null;
@@ -274,6 +295,8 @@ export type PlacementSwitch = "initial" | "sticky" | "pinned" | "reselected_cold
274
295
  */
275
296
  export type AccountSwitchReason = "initial" | "reselected_cold" | "failover_same_provider" | "failover_cross_provider" | "return_to_preferred" | "explicit_choice" | "revoked";
276
297
  export type WaitReason = "pinned_account_unavailable"
298
+ /** Allocation was explicitly switched off; a person must enable it or change the pin. */
299
+ | "pinned_account_disabled"
277
300
  /** The explicit choice can never serve this work until a person changes something (D-24). */
278
301
  | "pinned_account_ineligible" | "no_eligible_capacity"
279
302
  /** No candidate model may be used: workspace ceiling or provider switch (D-17, D-26). */
@@ -0,0 +1,4 @@
1
+ /** Current wait guidance shared by initial parking and later reclassification.
2
+ * These are new audit events only; never rewrite an earlier model request. */
3
+ export declare function subscriptionCapacityWaitReasonText(reason: string, name: string): string | null;
4
+ export declare function subscriptionCapacityWaitNeedsAction(reason: string): boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/subscriptions",
3
- "version": "2.0.1",
3
+ "version": "2.0.2-canary.38789554071001",
4
4
  "description": "Pure, provider-neutral subscription account policy for Opengeni: contract types, effective settings, eligibility, placement, failover order, cache coldness, the shared quota model and adapter interfaces. No database, provider SDK or network dependency.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/src/adapter.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { SubscriptionQuotaBlock } from "./quota";
1
2
  import type { CacheFacts, ModelId, ModelTier, ProviderId, SubscriptionQuota } from "./types";
2
3
 
3
4
  /**
@@ -284,6 +285,22 @@ export interface SubscriptionCoreAdapter<Credential = unknown> {
284
285
  * quota exhaustion. Absent: every reading below the limit does.
285
286
  */
286
287
  usageReadConfirmsAvailability?(response: unknown): boolean;
288
+ /**
289
+ * With `usageReadEndsQuotaExhaustion`: which stored blocks one `fetchUsage`
290
+ * response that confirms availability shows have ended, judged from each
291
+ * block's own claim (the limits the observation that set it named, tied
292
+ * to its exact deadline: `QuotaBlockClaim`). `modelId` is the cooled
293
+ * product model, or null for the quota exhaustion deadline. The predicate
294
+ * must be false for a block without a claim, for a claim observed no
295
+ * earlier than the response, and unless the response reports every
296
+ * claimed limit numerically below it (an explicit "no such limit" does
297
+ * not clear a limit that refused). A cooldown the reading itself reports
298
+ * stands, and so does every block the predicate does not end.
299
+ * When defined, a stored quota exhaustion deadline ends only where it
300
+ * returns true. Absent: a reading ends no cooldown (each runs until its
301
+ * own end), and `usageReadEndsQuotaExhaustion` alone decides the deadline.
302
+ */
303
+ usageReadEndsClaimedBlock?(response: unknown): (block: SubscriptionQuotaBlock) => boolean;
287
304
  /**
288
305
  * The provider's usage-endpoint readings are complete: each reports every
289
306
  * window that limits the connection, so a stored exhausted window that a
package/src/index.ts CHANGED
@@ -8,3 +8,4 @@ export * from "./spread";
8
8
  export * from "./placement";
9
9
  export * from "./settlement";
10
10
  export * from "./adapter";
11
+ export * from "./wait-presentation";
package/src/placement.ts CHANGED
@@ -316,6 +316,11 @@ export function decidePlacement(input: PlacementInput): PlacementDecision {
316
316
  ) {
317
317
  return wait("pinned_account_ineligible", null);
318
318
  }
319
+ if (
320
+ connectionIneligibility(input, bound, session.preferredModelId).includes("allocator_disabled")
321
+ ) {
322
+ return wait("pinned_account_disabled", null);
323
+ }
319
324
  const at = servableAgainAt(input, bound, session.preferredModelId);
320
325
  return wait("pinned_account_unavailable", typeof at === "number" ? at : null);
321
326
  }