@opengeni/subscriptions 0.0.0-stage → 1.4.5-canary.37754244159001

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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Cloudgeni-ai
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,39 @@
1
- # Temporary Holding Version
1
+ # `@opengeni/subscriptions`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The pure policy layer of Opengeni's shared subscription core. It decides which
4
+ subscription account (Codex, Claude, SuperGrok, or an API-key connection) a
5
+ session's turn runs on, and why it waits otherwise. It has no database,
6
+ provider SDK or network dependency, no clock and no randomness: every input
7
+ is passed in, and every function is deterministic.
8
+
9
+ The package owns:
10
+
11
+ - contract types: connections and scopes, settings with workspace overrides
12
+ and locks, session bindings, the shared quota model, placement decisions,
13
+ switch, wait and fail reasons;
14
+ - `effectiveSettings`: organization defaults, unlocked workspace overrides and
15
+ the source of every value;
16
+ - eligibility: authorization (scope, personal ownership, frozen personal
17
+ authority, provider switches) separated from serviceability (health,
18
+ allocator, entitlement, access policy, cooldowns, capacity);
19
+ - `decidePlacement`: explicit choice, cache-aware stickiness, re-selection
20
+ points, failover candidate order, primary-first and spread ranking,
21
+ personal fallback, explicit failures and explained waits;
22
+ - cache coldness, reasoning-level mapping and the spread hash; and
23
+ - the provider adapter interface types.
24
+
25
+ Authority stays in SQL: a bug here can at worst pick a worse eligible account,
26
+ never a forbidden one. Persistence, leases, waiters and provider calls live in
27
+ `@opengeni/db`, the worker and the provider adapters.
28
+
29
+ The behaviour contract is [`docs/subscription-accounts.md`](../../docs/subscription-accounts.md)
30
+ and the design is
31
+ [`docs/design/subscription-core-2026-10-07.md`](../../docs/design/subscription-core-2026-10-07.md).
32
+ The independent reference model of the contract ships separately as
33
+ `@opengeni/subscriptions/reference`, with a bridge that lets its
34
+ `checkDecision` judge production decisions; placement never imports it. It is
35
+ there so the worker's shadow comparison can check decisions in production.
36
+ Conformance tests compare every decision with the reference model over
37
+ generated reference worlds, generated production-only inputs (provider
38
+ switches, personal authority, compaction locks, quota shapes) and scripted
39
+ scenarios.
@@ -0,0 +1,110 @@
1
+ import type { CacheFacts, ModelId, ProviderId, SubscriptionQuota } from "./types.js";
2
+ /**
3
+ * Provider differences are capability flags, never provider conditionals in
4
+ * shared code (SUB-PROV-02).
5
+ */
6
+ export type ProviderCapabilities = {
7
+ /** The credential renews itself through refresh (false for setup tokens). */
8
+ autoRenews: boolean;
9
+ resetCredits: boolean;
10
+ modelEntitlements: boolean;
11
+ realtime: boolean;
12
+ fundsMedia: boolean;
13
+ apps: boolean;
14
+ remoteCompaction: boolean;
15
+ quotaWindows: boolean;
16
+ };
17
+ /** Shared error outcomes every adapter classifies into (SUB-PROV-01). */
18
+ export type ProviderErrorOutcome = {
19
+ kind: "exhausted";
20
+ resetAt: number | null;
21
+ } | {
22
+ kind: "rate_limited";
23
+ retryAfterMs: number | null;
24
+ } | {
25
+ kind: "unauthorized";
26
+ } | {
27
+ kind: "forbidden";
28
+ } | {
29
+ kind: "entitlement_missing";
30
+ modelId: ModelId;
31
+ } | {
32
+ kind: "overloaded";
33
+ } | {
34
+ kind: "transient";
35
+ } | {
36
+ kind: "fatal";
37
+ };
38
+ /** An encrypted credential as stored; the core never decrypts it. */
39
+ export type EncryptedCredential = {
40
+ credentialEncrypted: string;
41
+ credentialFormat: string;
42
+ expiresAt: number | null;
43
+ };
44
+ /** Identity a sign-in reports for the connection row. */
45
+ export type ConnectionIdentity = {
46
+ providerAccountId: string;
47
+ accountEmail: string | null;
48
+ planType: string | null;
49
+ };
50
+ export type SignInResult = {
51
+ credential: EncryptedCredential;
52
+ identity: ConnectionIdentity;
53
+ };
54
+ /** Items in conversation history that only their own provider accepts. */
55
+ export type ProviderHistoryItemKind = "encrypted_reasoning" | "thinking_signature" | "provider_tool" | "remote_compaction";
56
+ /**
57
+ * What a provider can accept from history written while another provider
58
+ * served the session (design 4, SUB-FAIL-08).
59
+ */
60
+ export type HistoryCompatibility = {
61
+ /** Provider-specific item kinds to drop from a request copy for this provider. */
62
+ dropFromOtherProviders: readonly ProviderHistoryItemKind[];
63
+ };
64
+ /**
65
+ * The adapter surface every model connection implements, including API-key
66
+ * connectors (SUB-PROV-04). `Transport` is the provider's request-local
67
+ * authorization handle; `ProviderError` is whatever the transport throws.
68
+ */
69
+ export interface ModelConnectionAdapter<Transport = unknown, ProviderError = unknown> {
70
+ readonly provider: ProviderId;
71
+ readonly capabilities: ProviderCapabilities;
72
+ /** Request-local authorization and wire normalization for one selected connection. */
73
+ transport(input: {
74
+ connectionId: string;
75
+ credential: EncryptedCredential;
76
+ }): Promise<Transport>;
77
+ /** Models the connection's plan can serve, including provider-observed exclusions. */
78
+ entitledModels(input: {
79
+ planType: string | null;
80
+ excludedModelIds: readonly ModelId[];
81
+ }): readonly ModelId[] | null;
82
+ /** Null when the error is not a provider outcome (for example a programming error). */
83
+ classifyError(error: ProviderError): ProviderErrorOutcome | null;
84
+ cacheFacts(input: {
85
+ modelId: ModelId;
86
+ }): CacheFacts;
87
+ historyCompatibility(): HistoryCompatibility;
88
+ }
89
+ /**
90
+ * The full adapter of a signed-in subscription (SUB-PROV-01): sign-in,
91
+ * refresh, quota decoding, plus the shared connection surface.
92
+ */
93
+ export interface SubscriptionProviderAdapter<Transport = unknown, ProviderError = unknown, SignInInput = unknown, UsageResponse = unknown> extends ModelConnectionAdapter<Transport, ProviderError> {
94
+ /** OAuth, device code or setup token; returns an encrypted secret and identity. */
95
+ signIn(input: SignInInput): Promise<SignInResult>;
96
+ /**
97
+ * Token refresh, called only under the core's single per-connection lock.
98
+ * The core increments `refresh_generation` for every successful refresh.
99
+ */
100
+ refresh(input: {
101
+ connectionId: string;
102
+ credential: EncryptedCredential;
103
+ }): Promise<EncryptedCredential>;
104
+ /** Usage responses or headers decoded into the shared quota model. */
105
+ decodeQuota(input: {
106
+ response: UsageResponse;
107
+ observedAt: number;
108
+ refreshGeneration: number;
109
+ }): Omit<SubscriptionQuota, "revision">;
110
+ }
@@ -0,0 +1,17 @@
1
+ import type { CacheFacts, SessionBinding } from "./types.js";
2
+ /**
3
+ * Idle cut-off used for providers whose cut-off has not been measured yet
4
+ * (design 6.1). Erring towards "warm" avoids paying a cache miss for a switch
5
+ * that was not needed.
6
+ */
7
+ export declare const DEFAULT_IDLE_CUTOFF_MS: number;
8
+ /** How long the provider prompt cache stays warm after a model call. */
9
+ export declare function cacheLifetimeMs(facts: CacheFacts | undefined): number;
10
+ /**
11
+ * The cache is warm while the session has been idle no longer than the
12
+ * provider's cache lifetime (SUB-STICK-04). Idle time is measured from the
13
+ * latest completed model call, not the turn start, so a long turn is not
14
+ * mistaken for a cold cache. An exact lifetime sent with the latest request
15
+ * (Claude) takes precedence over the provider's facts.
16
+ */
17
+ export declare function isCacheWarm(binding: Pick<SessionBinding, "lastModelCallAt" | "cacheTtlMs">, facts: CacheFacts | undefined, now: number): boolean;
@@ -0,0 +1,122 @@
1
+ // src/settings.ts
2
+ var SCALAR_SETTING_KEYS = Object.freeze([
3
+ "crossProviderFailover",
4
+ "personalConnectionsAllowed",
5
+ "personalFallbackAllowed"
6
+ ]);
7
+ var KEYED_SETTING_KEYS = Object.freeze([
8
+ "rotation",
9
+ "providers",
10
+ "fallbackOrder"
11
+ ]);
12
+ var SUBSCRIPTION_SETTING_KEYS = Object.freeze([
13
+ ...SCALAR_SETTING_KEYS,
14
+ ...KEYED_SETTING_KEYS
15
+ ]);
16
+ var DEFAULT_ROTATION = Object.freeze({ mode: "spread" });
17
+ var DEFAULT_PROVIDER_SWITCHES = Object.freeze({
18
+ useOrganizationAccounts: true,
19
+ enabled: true
20
+ });
21
+ function effectiveSettings(policy, workspaceId) {
22
+ const override = policy.workspaces[workspaceId] ?? {};
23
+ const locked = new Set(policy.locked);
24
+ const organization = policy.organization;
25
+ const scalar = (key) => {
26
+ const value = override[key];
27
+ const overridden = value !== void 0 && !locked.has(key);
28
+ return {
29
+ value: overridden ? value : organization[key],
30
+ source: overridden ? "workspace" : "organization"
31
+ };
32
+ };
33
+ const keyed = (key) => {
34
+ const base = organization[key];
35
+ const entries = locked.has(key) ? void 0 : override[key];
36
+ const value = { ...base };
37
+ const sources = {};
38
+ for (const [entryKey, entry] of Object.entries(base)) {
39
+ if (key === "providers" && entry.inferenceSource !== void 0) {
40
+ value[entryKey] = resolveProviderSwitches(entry);
41
+ }
42
+ sources[entryKey] = "organization";
43
+ }
44
+ for (const [entryKey, entry] of Object.entries(entries ?? {})) {
45
+ if (entry === void 0) continue;
46
+ value[entryKey] = key === "providers" ? mergeProviderSwitches(
47
+ base[entryKey],
48
+ entry
49
+ ) : entry;
50
+ sources[entryKey] = "workspace";
51
+ }
52
+ return { value, sources };
53
+ };
54
+ const crossProviderFailover = scalar("crossProviderFailover");
55
+ const personalConnectionsAllowed = scalar("personalConnectionsAllowed");
56
+ const personalFallbackAllowed = scalar("personalFallbackAllowed");
57
+ const rotation = keyed("rotation");
58
+ const providers = keyed("providers");
59
+ const fallbackOrder = keyed("fallbackOrder");
60
+ return {
61
+ values: {
62
+ rotation: rotation.value,
63
+ providers: providers.value,
64
+ crossProviderFailover: crossProviderFailover.value,
65
+ fallbackOrder: fallbackOrder.value,
66
+ personalConnectionsAllowed: personalConnectionsAllowed.value,
67
+ personalFallbackAllowed: personalFallbackAllowed.value
68
+ },
69
+ sources: {
70
+ crossProviderFailover: crossProviderFailover.source,
71
+ personalConnectionsAllowed: personalConnectionsAllowed.source,
72
+ personalFallbackAllowed: personalFallbackAllowed.source,
73
+ rotation: rotation.sources,
74
+ providers: providers.sources,
75
+ fallbackOrder: fallbackOrder.sources
76
+ }
77
+ };
78
+ }
79
+ function rotationFor(settings, provider) {
80
+ return settings.rotation[provider] ?? DEFAULT_ROTATION;
81
+ }
82
+ function providerSwitchesFor(settings, provider) {
83
+ return settings.providers[provider] ?? DEFAULT_PROVIDER_SWITCHES;
84
+ }
85
+ function resolveProviderSwitches(switches) {
86
+ const inferenceSource = switches.inferenceSource ?? (switches.useOrganizationAccounts ? "automatic" : "workspace");
87
+ return {
88
+ ...switches,
89
+ inferenceSource,
90
+ useOrganizationAccounts: inferenceSource !== "workspace"
91
+ };
92
+ }
93
+ function inferenceSourceFor(settings, provider) {
94
+ return resolveProviderSwitches(providerSwitchesFor(settings, provider)).inferenceSource;
95
+ }
96
+ function mergeProviderSwitches(base, override) {
97
+ const inherited = resolveProviderSwitches({ ...DEFAULT_PROVIDER_SWITCHES, ...base });
98
+ const inferenceSource = override.inferenceSource ?? (override.useOrganizationAccounts === void 0 ? inherited.inferenceSource : override.useOrganizationAccounts ? "automatic" : "workspace");
99
+ const hasAuthoritativeSource = override.inferenceSource !== void 0 || base?.inferenceSource !== void 0;
100
+ const { inferenceSource: _inheritedSource, ...inheritedValues } = inherited;
101
+ const { inferenceSource: _overrideSource, ...overrideValues } = override;
102
+ return {
103
+ ...inheritedValues,
104
+ ...overrideValues,
105
+ ...hasAuthoritativeSource ? { inferenceSource } : {},
106
+ useOrganizationAccounts: inferenceSource !== "workspace"
107
+ };
108
+ }
109
+
110
+ export {
111
+ SCALAR_SETTING_KEYS,
112
+ KEYED_SETTING_KEYS,
113
+ SUBSCRIPTION_SETTING_KEYS,
114
+ DEFAULT_ROTATION,
115
+ DEFAULT_PROVIDER_SWITCHES,
116
+ effectiveSettings,
117
+ rotationFor,
118
+ providerSwitchesFor,
119
+ resolveProviderSwitches,
120
+ inferenceSourceFor
121
+ };
122
+ //# sourceMappingURL=chunk-D3SQAOOO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/settings.ts"],"sourcesContent":["import type {\n EffectiveSubscriptionSettings,\n KeyedSettingKey,\n ProviderId,\n ProviderSwitches,\n RotationSetting,\n ScalarSettingKey,\n SettingSource,\n SubscriptionSettingKey,\n SubscriptionSettingsPolicy,\n SubscriptionSettingValues,\n} from \"./types\";\n\nexport const SCALAR_SETTING_KEYS: readonly ScalarSettingKey[] = Object.freeze([\n \"crossProviderFailover\",\n \"personalConnectionsAllowed\",\n \"personalFallbackAllowed\",\n]);\n\nexport const KEYED_SETTING_KEYS: readonly KeyedSettingKey[] = Object.freeze([\n \"rotation\",\n \"providers\",\n \"fallbackOrder\",\n]);\n\nexport const SUBSCRIPTION_SETTING_KEYS: readonly SubscriptionSettingKey[] = Object.freeze([\n ...SCALAR_SETTING_KEYS,\n ...KEYED_SETTING_KEYS,\n]);\n\n/** Default when a provider has no rotation entry: spread work (design 3.3). */\nexport const DEFAULT_ROTATION: RotationSetting = Object.freeze({ mode: \"spread\" });\n\nexport const DEFAULT_PROVIDER_SWITCHES: ProviderSwitches = Object.freeze({\n useOrganizationAccounts: true,\n enabled: true,\n});\n\n/**\n * Resolve one workspace's effective settings (SUB-SET-01..03).\n *\n * Every setting resolves to exactly one value with its source: the\n * organization default, or the workspace override when the setting is not\n * locked. For map-valued settings (`rotation`, `providers`, `fallbackOrder`) a\n * workspace row overrides individual entries, so overriding one provider's\n * rotation does not reset another provider's, and a provider's switches\n * override field by field (D-25). Locking a map-valued setting locks every\n * entry.\n */\nexport function effectiveSettings(\n policy: SubscriptionSettingsPolicy,\n workspaceId: string,\n): EffectiveSubscriptionSettings {\n const override = policy.workspaces[workspaceId] ?? {};\n const locked = new Set<SubscriptionSettingKey>(policy.locked);\n const organization = policy.organization;\n\n const scalar = <K extends ScalarSettingKey>(key: K) => {\n const value = override[key];\n const overridden = value !== undefined && !locked.has(key);\n return {\n value: (overridden ? value : organization[key]) as SubscriptionSettingValues[K],\n source: (overridden ? \"workspace\" : \"organization\") as SettingSource,\n };\n };\n const keyed = <K extends KeyedSettingKey>(key: K) => {\n const base = organization[key] as Readonly<Record<string, unknown>>;\n const entries = locked.has(key)\n ? undefined\n : (override[key] as Readonly<Record<string, unknown>> | undefined);\n const value: Record<string, unknown> = { ...base };\n const sources: Record<string, SettingSource> = {};\n for (const [entryKey, entry] of Object.entries(base)) {\n if (key === \"providers\" && (entry as ProviderSwitches).inferenceSource !== undefined) {\n value[entryKey] = resolveProviderSwitches(entry as ProviderSwitches);\n }\n sources[entryKey] = \"organization\";\n }\n for (const [entryKey, entry] of Object.entries(entries ?? {})) {\n if (entry === undefined) continue;\n // A provider's switches override field by field (D-25).\n value[entryKey] =\n key === \"providers\"\n ? mergeProviderSwitches(\n base[entryKey] as ProviderSwitches | undefined,\n entry as Partial<ProviderSwitches>,\n )\n : entry;\n sources[entryKey] = \"workspace\";\n }\n return { value: value as SubscriptionSettingValues[K], sources };\n };\n\n const crossProviderFailover = scalar(\"crossProviderFailover\");\n const personalConnectionsAllowed = scalar(\"personalConnectionsAllowed\");\n const personalFallbackAllowed = scalar(\"personalFallbackAllowed\");\n const rotation = keyed(\"rotation\");\n const providers = keyed(\"providers\");\n const fallbackOrder = keyed(\"fallbackOrder\");\n return {\n values: {\n rotation: rotation.value,\n providers: providers.value,\n crossProviderFailover: crossProviderFailover.value,\n fallbackOrder: fallbackOrder.value,\n personalConnectionsAllowed: personalConnectionsAllowed.value,\n personalFallbackAllowed: personalFallbackAllowed.value,\n },\n sources: {\n crossProviderFailover: crossProviderFailover.source,\n personalConnectionsAllowed: personalConnectionsAllowed.source,\n personalFallbackAllowed: personalFallbackAllowed.source,\n rotation: rotation.sources,\n providers: providers.sources,\n fallbackOrder: fallbackOrder.sources,\n },\n };\n}\n\nexport function rotationFor(\n settings: SubscriptionSettingValues,\n provider: ProviderId,\n): RotationSetting {\n return settings.rotation[provider] ?? DEFAULT_ROTATION;\n}\n\nexport function providerSwitchesFor(\n settings: SubscriptionSettingValues,\n provider: ProviderId,\n): ProviderSwitches {\n return settings.providers[provider] ?? DEFAULT_PROVIDER_SWITCHES;\n}\n\n/** Legacy boolean rows remain readable; all effective values expose one source. */\nexport function resolveProviderSwitches(switches: ProviderSwitches): ProviderSwitches & {\n inferenceSource: NonNullable<ProviderSwitches[\"inferenceSource\"]>;\n} {\n const inferenceSource =\n switches.inferenceSource ?? (switches.useOrganizationAccounts ? \"automatic\" : \"workspace\");\n return {\n ...switches,\n inferenceSource,\n useOrganizationAccounts: inferenceSource !== \"workspace\",\n };\n}\n\nexport function inferenceSourceFor(\n settings: SubscriptionSettingValues,\n provider: ProviderId,\n): NonNullable<ProviderSwitches[\"inferenceSource\"]> {\n return resolveProviderSwitches(providerSwitchesFor(settings, provider)).inferenceSource;\n}\n\nfunction mergeProviderSwitches(\n base: ProviderSwitches | undefined,\n override: Partial<ProviderSwitches>,\n): ProviderSwitches {\n const inherited = resolveProviderSwitches({ ...DEFAULT_PROVIDER_SWITCHES, ...base });\n const inferenceSource =\n override.inferenceSource ??\n (override.useOrganizationAccounts === undefined\n ? inherited.inferenceSource\n : override.useOrganizationAccounts\n ? \"automatic\"\n : \"workspace\");\n const hasAuthoritativeSource =\n override.inferenceSource !== undefined || base?.inferenceSource !== undefined;\n const { inferenceSource: _inheritedSource, ...inheritedValues } = inherited;\n const { inferenceSource: _overrideSource, ...overrideValues } = override;\n return {\n ...inheritedValues,\n ...overrideValues,\n ...(hasAuthoritativeSource ? { inferenceSource } : {}),\n useOrganizationAccounts: inferenceSource !== \"workspace\",\n };\n}\n"],"mappings":"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","names":[]}
@@ -0,0 +1,48 @@
1
+ import { type QuotaCapacity } from "./quota.js";
2
+ import type { ModelId, PlacementInput, PlacementWorkspace, SubscriptionConnection } from "./types.js";
3
+ /**
4
+ * Reasons a connection may not serve a session at all. These are authority:
5
+ * the database enforces the same rules, so a connection with any of them must
6
+ * never be selected (SUB-ELIG-01, SUB-ELIG-05, SUB-SET-06, SUB-FAIL-04).
7
+ */
8
+ export type AuthorizationIneligibility = "provider_disabled" | "organization_accounts_off" | "inference_source_excludes_connection" | "out_of_scope" | "personal_connections_disabled" | "personal_owner_inactive" | "personal_not_owners_work" | "personal_authority_missing";
9
+ /** Reasons an authorized connection cannot serve a model now (SUB-ELIG-02..04). */
10
+ export type ServiceIneligibility = "unhealthy" | "allocator_disabled" | "wrong_provider" | "model_unknown" | "model_not_allowed_by_workspace" | "model_not_entitled" | "model_not_allowed_by_connection" | "source_assignment_allocator_mismatch" | "model_cooling_down" | "exhausted";
11
+ export type Ineligibility = AuthorizationIneligibility | ServiceIneligibility;
12
+ export declare const AUTHORIZATION_INELIGIBILITIES: readonly AuthorizationIneligibility[];
13
+ export declare function isAuthorizationIneligibility(reason: Ineligibility): reason is AuthorizationIneligibility;
14
+ /**
15
+ * Reasons that neither time nor a quota reset clears: the work is not
16
+ * authorized on the account, or the account cannot serve the model at all.
17
+ * Health and allocator eligibility are not permanent: reconnecting or
18
+ * re-enabling allocation restores them.
19
+ */
20
+ export declare function isPermanentIneligibility(reason: Ineligibility): boolean;
21
+ /** Capacity of a connection now, with the input's staleness bound for its provider. */
22
+ export declare function connectionCapacity(input: PlacementInput, connection: SubscriptionConnection): QuotaCapacity;
23
+ /** Workspace model restrictions are a ceiling on every selection (SUB-ELIG-02). */
24
+ export declare function modelAllowedInWorkspace(workspace: PlacementWorkspace, modelId: ModelId): boolean;
25
+ /** Is the provider switched on for this workspace (SUB-SET-06)? */
26
+ export declare function providerEnabled(input: PlacementInput, provider: string): boolean;
27
+ /**
28
+ * Authorization of one connection for the session's work, independent of
29
+ * model and capacity. Personal connections serve only their owner's own work,
30
+ * in the owner's private sessions or Personal workspace, with frozen personal
31
+ * authority for that provider (SUB-ELIG-05, design 3.7, 3.8). Shared
32
+ * connections serve the workspaces and people in their scope, where people are
33
+ * evaluated against the session owner.
34
+ */
35
+ export declare function authorizationIneligibility(input: PlacementInput, connection: SubscriptionConnection): AuthorizationIneligibility[];
36
+ /** Every reason this connection cannot serve this session and model now; empty when it can. */
37
+ export declare function connectionIneligibility(input: PlacementInput, connection: SubscriptionConnection, modelId: ModelId): Ineligibility[];
38
+ /** SUB-ELIG-01..06: may this connection serve this session's model now? */
39
+ export declare function canServe(input: PlacementInput, connection: SubscriptionConnection, modelId: ModelId): boolean;
40
+ /**
41
+ * When a connection that is blocked only by capacity or a model cooldown can
42
+ * serve this model again. Returns `undefined` when something other than time
43
+ * blocks it, or when it is not blocked at all, and `null` when the reset time
44
+ * is unknown.
45
+ */
46
+ export declare function servableAgainAt(input: PlacementInput, connection: SubscriptionConnection, modelId: ModelId): number | null | undefined;
47
+ /** The owner opted in and the effective setting allows personal fallback (SUB-SEL-02, D-12). */
48
+ export declare function personalFallbackActive(input: PlacementInput): boolean;
@@ -0,0 +1,9 @@
1
+ export * from "./types.js";
2
+ export * from "./settings.js";
3
+ export * from "./quota.js";
4
+ export * from "./cache.js";
5
+ export * from "./eligibility.js";
6
+ export * from "./reasoning.js";
7
+ export * from "./spread.js";
8
+ export * from "./placement.js";
9
+ export type * from "./adapter.js";