@supersolutions/super-router-core 0.0.0 → 0.1.0
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 +202 -0
- package/NOTICE +14 -0
- package/dist/credit-rates.d.ts +173 -0
- package/dist/credit-rates.js +121 -0
- package/dist/index.d.ts +264 -0
- package/dist/index.js +448 -0
- package/package.json +27 -7
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
SuperRouter
|
|
2
|
+
Copyright 2026 SUPER SOLUTION LABS INC
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { z, Price, type Principal, type Service } from "@supersolutions/super-router-contracts";
|
|
2
|
+
/** Credits are a fixed accounting unit. Developers configure units per credit, never the scale. */
|
|
3
|
+
export declare const CREDIT_ATOMS = 1000000000n;
|
|
4
|
+
export declare const CreditRateConfig: z.ZodObject<{
|
|
5
|
+
asset: z.ZodString;
|
|
6
|
+
tokens: z.ZodOptional<z.ZodObject<{
|
|
7
|
+
input: z.ZodObject<{
|
|
8
|
+
units: z.ZodString;
|
|
9
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
10
|
+
}, z.core.$strict>;
|
|
11
|
+
cached: z.ZodObject<{
|
|
12
|
+
units: z.ZodString;
|
|
13
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
14
|
+
}, z.core.$strict>;
|
|
15
|
+
cache_write: z.ZodObject<{
|
|
16
|
+
units: z.ZodString;
|
|
17
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
18
|
+
}, z.core.$strict>;
|
|
19
|
+
output: z.ZodObject<{
|
|
20
|
+
units: z.ZodString;
|
|
21
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
22
|
+
}, z.core.$strict>;
|
|
23
|
+
}, z.core.$strict>>;
|
|
24
|
+
media: z.ZodOptional<z.ZodObject<{
|
|
25
|
+
images: z.ZodOptional<z.ZodObject<{
|
|
26
|
+
units: z.ZodString;
|
|
27
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
28
|
+
}, z.core.$strict>>;
|
|
29
|
+
video_ms: z.ZodOptional<z.ZodObject<{
|
|
30
|
+
units: z.ZodString;
|
|
31
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
32
|
+
}, z.core.$strict>>;
|
|
33
|
+
audio_ms: z.ZodOptional<z.ZodObject<{
|
|
34
|
+
units: z.ZodString;
|
|
35
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
36
|
+
}, z.core.$strict>>;
|
|
37
|
+
tasks: z.ZodOptional<z.ZodObject<{
|
|
38
|
+
units: z.ZodString;
|
|
39
|
+
credits: z.ZodDefault<z.ZodString>;
|
|
40
|
+
}, z.core.$strict>>;
|
|
41
|
+
}, z.core.$strict>>;
|
|
42
|
+
}, z.core.$strict>;
|
|
43
|
+
export type CreditRateConfig = z.input<typeof CreditRateConfig>;
|
|
44
|
+
/** Compile exact rational units-per-credit to existing wire Price. Token mode requires all four categories; media categories are explicit. */
|
|
45
|
+
export declare function compileCreditPrice(raw: unknown): Price;
|
|
46
|
+
export interface CreditRatePublisher {
|
|
47
|
+
getService(p: Principal, id: string, version?: number): Promise<Service>;
|
|
48
|
+
publish(p: Principal, service: unknown, mode?: "cloud" | "self-host", expectedVersion?: number): Promise<Service | undefined>;
|
|
49
|
+
}
|
|
50
|
+
/** Atomically advance only the customer-sale price; supply and platform prices remain server snapshots. */
|
|
51
|
+
export declare function publishCreditRateVersion(store: CreditRatePublisher, p: Principal, id: string, expectedVersion: number, config: unknown, mode?: "cloud" | "self-host"): Promise<{
|
|
52
|
+
version: number;
|
|
53
|
+
price: {
|
|
54
|
+
asset: string;
|
|
55
|
+
input: string;
|
|
56
|
+
cached: string;
|
|
57
|
+
cache_write: string;
|
|
58
|
+
output: string;
|
|
59
|
+
per: number;
|
|
60
|
+
media?: {
|
|
61
|
+
images?: {
|
|
62
|
+
atoms: string;
|
|
63
|
+
per: number;
|
|
64
|
+
} | undefined;
|
|
65
|
+
video_ms?: {
|
|
66
|
+
atoms: string;
|
|
67
|
+
per: number;
|
|
68
|
+
} | undefined;
|
|
69
|
+
audio_ms?: {
|
|
70
|
+
atoms: string;
|
|
71
|
+
per: number;
|
|
72
|
+
} | undefined;
|
|
73
|
+
tasks?: {
|
|
74
|
+
atoms: string;
|
|
75
|
+
per: number;
|
|
76
|
+
} | undefined;
|
|
77
|
+
} | undefined;
|
|
78
|
+
};
|
|
79
|
+
id: string;
|
|
80
|
+
mode: "tier" | "specific" | "pool";
|
|
81
|
+
offerings: {
|
|
82
|
+
id: string;
|
|
83
|
+
provider: string;
|
|
84
|
+
model: string;
|
|
85
|
+
upstream_model: string;
|
|
86
|
+
region: string;
|
|
87
|
+
labels: string[];
|
|
88
|
+
enabled: boolean;
|
|
89
|
+
source: "platform" | "byok";
|
|
90
|
+
max_input_tokens: number;
|
|
91
|
+
max_output_tokens: number;
|
|
92
|
+
price: {
|
|
93
|
+
asset: string;
|
|
94
|
+
input: string;
|
|
95
|
+
cached: string;
|
|
96
|
+
cache_write: string;
|
|
97
|
+
output: string;
|
|
98
|
+
per: number;
|
|
99
|
+
media?: {
|
|
100
|
+
images?: {
|
|
101
|
+
atoms: string;
|
|
102
|
+
per: number;
|
|
103
|
+
} | undefined;
|
|
104
|
+
video_ms?: {
|
|
105
|
+
atoms: string;
|
|
106
|
+
per: number;
|
|
107
|
+
} | undefined;
|
|
108
|
+
audio_ms?: {
|
|
109
|
+
atoms: string;
|
|
110
|
+
per: number;
|
|
111
|
+
} | undefined;
|
|
112
|
+
tasks?: {
|
|
113
|
+
atoms: string;
|
|
114
|
+
per: number;
|
|
115
|
+
} | undefined;
|
|
116
|
+
} | undefined;
|
|
117
|
+
};
|
|
118
|
+
task_kind?: "image" | "video" | "audio" | "task" | undefined;
|
|
119
|
+
max_usage?: {
|
|
120
|
+
images?: number | undefined;
|
|
121
|
+
video_ms?: number | undefined;
|
|
122
|
+
audio_ms?: number | undefined;
|
|
123
|
+
tasks?: number | undefined;
|
|
124
|
+
} | undefined;
|
|
125
|
+
latency_ms?: number | undefined;
|
|
126
|
+
reliability?: number | undefined;
|
|
127
|
+
quality?: number | undefined;
|
|
128
|
+
}[];
|
|
129
|
+
regions: string[];
|
|
130
|
+
required_labels: string[];
|
|
131
|
+
max_attempts: number;
|
|
132
|
+
max_provider_cost: string;
|
|
133
|
+
max_output_tokens: number;
|
|
134
|
+
weights: {
|
|
135
|
+
cost: number;
|
|
136
|
+
latency: number;
|
|
137
|
+
reliability: number;
|
|
138
|
+
quality: number;
|
|
139
|
+
};
|
|
140
|
+
cost_scale: string;
|
|
141
|
+
latency_scale_ms: number;
|
|
142
|
+
unknown_score: number;
|
|
143
|
+
task_kind?: "image" | "video" | "audio" | "task" | undefined;
|
|
144
|
+
model?: string | undefined;
|
|
145
|
+
tier?: string | undefined;
|
|
146
|
+
platform_price?: {
|
|
147
|
+
asset: string;
|
|
148
|
+
input: string;
|
|
149
|
+
cached: string;
|
|
150
|
+
cache_write: string;
|
|
151
|
+
output: string;
|
|
152
|
+
per: number;
|
|
153
|
+
media?: {
|
|
154
|
+
images?: {
|
|
155
|
+
atoms: string;
|
|
156
|
+
per: number;
|
|
157
|
+
} | undefined;
|
|
158
|
+
video_ms?: {
|
|
159
|
+
atoms: string;
|
|
160
|
+
per: number;
|
|
161
|
+
} | undefined;
|
|
162
|
+
audio_ms?: {
|
|
163
|
+
atoms: string;
|
|
164
|
+
per: number;
|
|
165
|
+
} | undefined;
|
|
166
|
+
tasks?: {
|
|
167
|
+
atoms: string;
|
|
168
|
+
per: number;
|
|
169
|
+
} | undefined;
|
|
170
|
+
} | undefined;
|
|
171
|
+
} | undefined;
|
|
172
|
+
requires_subscription?: boolean | undefined;
|
|
173
|
+
}>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { z, Price, RouterError, } from "@supersolutions/super-router-contracts";
|
|
2
|
+
/** Credits are a fixed accounting unit. Developers configure units per credit, never the scale. */
|
|
3
|
+
export const CREDIT_ATOMS = 1000000000n;
|
|
4
|
+
const integer = z.string().regex(/^[1-9][0-9]{0,29}$/);
|
|
5
|
+
const ratio = z
|
|
6
|
+
.object({ units: integer, credits: integer.default("1") })
|
|
7
|
+
.strict();
|
|
8
|
+
export const CreditRateConfig = z
|
|
9
|
+
.object({
|
|
10
|
+
asset: z
|
|
11
|
+
.string()
|
|
12
|
+
.min(1)
|
|
13
|
+
.max(120)
|
|
14
|
+
.regex(/^[a-zA-Z0-9_.:/-]+$/),
|
|
15
|
+
tokens: z
|
|
16
|
+
.object({
|
|
17
|
+
input: ratio,
|
|
18
|
+
cached: ratio,
|
|
19
|
+
cache_write: ratio,
|
|
20
|
+
output: ratio,
|
|
21
|
+
})
|
|
22
|
+
.strict()
|
|
23
|
+
.optional(),
|
|
24
|
+
media: z
|
|
25
|
+
.object({
|
|
26
|
+
images: ratio.optional(),
|
|
27
|
+
video_ms: ratio.optional(),
|
|
28
|
+
audio_ms: ratio.optional(),
|
|
29
|
+
tasks: ratio.optional(),
|
|
30
|
+
})
|
|
31
|
+
.strict()
|
|
32
|
+
.optional(),
|
|
33
|
+
})
|
|
34
|
+
.strict();
|
|
35
|
+
const tokenKeys = ["input", "cached", "cache_write", "output"];
|
|
36
|
+
const mediaKeys = ["images", "video_ms", "audio_ms", "tasks"];
|
|
37
|
+
function gcd(a, b) {
|
|
38
|
+
while (b) {
|
|
39
|
+
[a, b] = [b, a % b];
|
|
40
|
+
}
|
|
41
|
+
return a;
|
|
42
|
+
}
|
|
43
|
+
function rate(value) {
|
|
44
|
+
const numerator = CREDIT_ATOMS * BigInt(value.credits), denominator = BigInt(value.units), g = gcd(numerator, denominator);
|
|
45
|
+
return { numerator: numerator / g, denominator: denominator / g };
|
|
46
|
+
}
|
|
47
|
+
/** Compile exact rational units-per-credit to existing wire Price. Token mode requires all four categories; media categories are explicit. */
|
|
48
|
+
export function compileCreditPrice(raw) {
|
|
49
|
+
const parsed = CreditRateConfig.safeParse(raw);
|
|
50
|
+
if (!parsed.success)
|
|
51
|
+
throw new RouterError("invalid_credit_rates");
|
|
52
|
+
const config = parsed.data;
|
|
53
|
+
if ((!config.tokens && !mediaKeys.some((k) => config.media?.[k])) ||
|
|
54
|
+
(config.tokens && tokenKeys.some((k) => !config.tokens?.[k])))
|
|
55
|
+
throw new RouterError("invalid_credit_rates");
|
|
56
|
+
const rates = tokenKeys.map((key) => config.tokens?.[key]
|
|
57
|
+
? rate(config.tokens[key])
|
|
58
|
+
: { numerator: 0n, denominator: 1n });
|
|
59
|
+
let per = 1n;
|
|
60
|
+
for (const r of rates) {
|
|
61
|
+
per = (per / gcd(per, r.denominator)) * r.denominator;
|
|
62
|
+
if (per > 1000000000n)
|
|
63
|
+
throw new RouterError("unsupported_rate_precision", 422);
|
|
64
|
+
}
|
|
65
|
+
const tokens = Object.fromEntries(tokenKeys.map((key, i) => [
|
|
66
|
+
key,
|
|
67
|
+
(rates[i].numerator * (per / rates[i].denominator)).toString(),
|
|
68
|
+
]));
|
|
69
|
+
const media = {};
|
|
70
|
+
for (const key of mediaKeys) {
|
|
71
|
+
const value = config.media?.[key];
|
|
72
|
+
if (!value)
|
|
73
|
+
continue;
|
|
74
|
+
const r = rate(value);
|
|
75
|
+
if (r.denominator > 1000000000n)
|
|
76
|
+
throw new RouterError("unsupported_rate_precision", 422);
|
|
77
|
+
media[key] = { atoms: r.numerator.toString(), per: Number(r.denominator) };
|
|
78
|
+
}
|
|
79
|
+
const compiled = Price.safeParse({
|
|
80
|
+
asset: config.asset,
|
|
81
|
+
...tokens,
|
|
82
|
+
per: Number(per),
|
|
83
|
+
...(Object.keys(media).length ? { media } : {}),
|
|
84
|
+
});
|
|
85
|
+
if (!compiled.success)
|
|
86
|
+
throw new RouterError("unsupported_rate_precision", 422);
|
|
87
|
+
return compiled.data;
|
|
88
|
+
}
|
|
89
|
+
/** Atomically advance only the customer-sale price; supply and platform prices remain server snapshots. */
|
|
90
|
+
export async function publishCreditRateVersion(store, p, id, expectedVersion, config, mode = "self-host") {
|
|
91
|
+
if (!p.scopes.includes("service:write"))
|
|
92
|
+
throw new RouterError("scope_denied", 403);
|
|
93
|
+
if (!Number.isSafeInteger(expectedVersion) ||
|
|
94
|
+
expectedVersion < 1 ||
|
|
95
|
+
expectedVersion >= Number.MAX_SAFE_INTEGER)
|
|
96
|
+
throw new RouterError("invalid_service_version");
|
|
97
|
+
const current = await store.getService(p, id);
|
|
98
|
+
if (current.version !== expectedVersion)
|
|
99
|
+
throw new RouterError("service_version_conflict", 409);
|
|
100
|
+
const price = compileCreditPrice(config);
|
|
101
|
+
const parsedConfig = CreditRateConfig.parse(config);
|
|
102
|
+
const requiredMeter = current.task_kind
|
|
103
|
+
? {
|
|
104
|
+
image: "images",
|
|
105
|
+
video: "video_ms",
|
|
106
|
+
audio: "audio_ms",
|
|
107
|
+
task: "tasks",
|
|
108
|
+
}[current.task_kind]
|
|
109
|
+
: undefined;
|
|
110
|
+
if (requiredMeter
|
|
111
|
+
? !parsedConfig.media?.[requiredMeter] ||
|
|
112
|
+
!!parsedConfig.tokens ||
|
|
113
|
+
mediaKeys.some((k) => k !== requiredMeter && !!parsedConfig.media?.[k])
|
|
114
|
+
: !parsedConfig.tokens || !!parsedConfig.media)
|
|
115
|
+
throw new RouterError("credit_rate_kind_mismatch", 422);
|
|
116
|
+
if (price.asset !== current.price.asset)
|
|
117
|
+
throw new RouterError("credit_asset_mismatch", 422);
|
|
118
|
+
const next = { ...current, version: current.version + 1, price };
|
|
119
|
+
await store.publish(p, next, mode, expectedVersion);
|
|
120
|
+
return next;
|
|
121
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { Invocation, Service, RouterError, type Principal, type Provider, type Offering, type Usage, type Price, type StreamEvent } from "@supersolutions/super-router-contracts";
|
|
2
|
+
export { RouterError };
|
|
3
|
+
export interface Leg {
|
|
4
|
+
kind: "customer_sale" | "platform_sale";
|
|
5
|
+
account: string;
|
|
6
|
+
price: Price;
|
|
7
|
+
reserved: string;
|
|
8
|
+
}
|
|
9
|
+
export interface RequestRecord {
|
|
10
|
+
id: string;
|
|
11
|
+
workspace: string;
|
|
12
|
+
environment: string;
|
|
13
|
+
customer: string;
|
|
14
|
+
service: Service;
|
|
15
|
+
execution: string;
|
|
16
|
+
billing: string;
|
|
17
|
+
cancel_requested: boolean;
|
|
18
|
+
output_started: boolean;
|
|
19
|
+
deadline: string;
|
|
20
|
+
legs: Leg[];
|
|
21
|
+
provider_spent: string;
|
|
22
|
+
}
|
|
23
|
+
export interface Store {
|
|
24
|
+
replay(p: Principal, key: string, digest: string): Promise<RequestRecord | null>;
|
|
25
|
+
getService(p: Principal, id: string, version?: number): Promise<Service>;
|
|
26
|
+
accounts(p: Principal, service: Service): Promise<Leg[]>;
|
|
27
|
+
reserve(p: Principal, key: string, digest: string, service: Service, legs: Leg[], deadline: string, decision?: unknown): Promise<{
|
|
28
|
+
request: RequestRecord;
|
|
29
|
+
fresh: boolean;
|
|
30
|
+
}>;
|
|
31
|
+
get(p: Principal, id: string): Promise<RequestRecord>;
|
|
32
|
+
begin(p: Principal, id: string, offering: Offering, bound: string): Promise<string>;
|
|
33
|
+
output(p: Principal, id: string): Promise<void>;
|
|
34
|
+
attemptResult(p: Principal, id: string, attempt: string, status: string, usage: Usage | null, cost: string | null, upstream?: string): Promise<void>;
|
|
35
|
+
finish(p: Principal, id: string, execution: string, usage: Usage | null, pending: boolean): Promise<void>;
|
|
36
|
+
cancel(p: Principal, id: string): Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
export interface BalanceRow {
|
|
39
|
+
id: string;
|
|
40
|
+
kind: string;
|
|
41
|
+
asset: string;
|
|
42
|
+
balance: string;
|
|
43
|
+
held: string;
|
|
44
|
+
available: string;
|
|
45
|
+
}
|
|
46
|
+
/** A source of epoch milliseconds. Stores and the router accept one so tests and conformance runs control time. */
|
|
47
|
+
export type Clock = () => number;
|
|
48
|
+
/**
|
|
49
|
+
* Everything the data-plane server and worker need from storage, beyond the router's own {@link Store} port.
|
|
50
|
+
* Implement this to plug in another database; run the store contract suite against it.
|
|
51
|
+
*/
|
|
52
|
+
export interface DataStore extends Store {
|
|
53
|
+
publish(p: Principal, service: unknown, mode?: "cloud" | "self-host", expectedVersion?: number): Promise<Service | undefined>;
|
|
54
|
+
list(p: Principal): Promise<Service[]>;
|
|
55
|
+
balance(p: Principal): Promise<BalanceRow[]>;
|
|
56
|
+
grant(p: Principal, kind: "customer_sale" | "platform_sale", asset: string, amount: string, source: string, expires?: Date): Promise<string>;
|
|
57
|
+
disable(p: Principal, offering: string): Promise<void>;
|
|
58
|
+
/** Settle or release expired reservations. Returns how many requests were processed. */
|
|
59
|
+
recover(): Promise<number>;
|
|
60
|
+
/** Optional operator view: recent requests with attempts and settled amounts. */
|
|
61
|
+
recent?(p: Principal, limit?: number, customer?: string): Promise<RecentRequest[]>;
|
|
62
|
+
}
|
|
63
|
+
export interface RecentRequest {
|
|
64
|
+
id: string;
|
|
65
|
+
customer: string;
|
|
66
|
+
service: string;
|
|
67
|
+
service_version: number;
|
|
68
|
+
execution: string;
|
|
69
|
+
billing: string;
|
|
70
|
+
provider_cost: string;
|
|
71
|
+
created_at: Date;
|
|
72
|
+
attempts: {
|
|
73
|
+
offering: string;
|
|
74
|
+
status: string;
|
|
75
|
+
cost: string | null;
|
|
76
|
+
usage: unknown;
|
|
77
|
+
}[];
|
|
78
|
+
settled: Record<string, string>;
|
|
79
|
+
}
|
|
80
|
+
export declare const mediaKeys: readonly ["images", "video_ms", "audio_ms", "tasks"];
|
|
81
|
+
export declare const kindMeter: {
|
|
82
|
+
readonly image: "images";
|
|
83
|
+
readonly video: "video_ms";
|
|
84
|
+
readonly audio: "audio_ms";
|
|
85
|
+
readonly task: "tasks";
|
|
86
|
+
};
|
|
87
|
+
export declare function charge(usage: Usage, price: Price): bigint;
|
|
88
|
+
export declare function bound(input: number, output: number, price: Price): bigint;
|
|
89
|
+
/** The canonical JSON of a value: object keys sorted, no whitespace. It is the input of the idempotency digest. */
|
|
90
|
+
export declare function canonical(value: unknown): string;
|
|
91
|
+
export declare function route(service: Service, input: Invocation): {
|
|
92
|
+
candidates: {
|
|
93
|
+
offering: {
|
|
94
|
+
id: string;
|
|
95
|
+
provider: string;
|
|
96
|
+
model: string;
|
|
97
|
+
upstream_model: string;
|
|
98
|
+
region: string;
|
|
99
|
+
labels: string[];
|
|
100
|
+
enabled: boolean;
|
|
101
|
+
source: "platform" | "byok";
|
|
102
|
+
max_input_tokens: number;
|
|
103
|
+
max_output_tokens: number;
|
|
104
|
+
price: {
|
|
105
|
+
asset: string;
|
|
106
|
+
input: string;
|
|
107
|
+
cached: string;
|
|
108
|
+
cache_write: string;
|
|
109
|
+
output: string;
|
|
110
|
+
per: number;
|
|
111
|
+
media?: {
|
|
112
|
+
images?: {
|
|
113
|
+
atoms: string;
|
|
114
|
+
per: number;
|
|
115
|
+
} | undefined;
|
|
116
|
+
video_ms?: {
|
|
117
|
+
atoms: string;
|
|
118
|
+
per: number;
|
|
119
|
+
} | undefined;
|
|
120
|
+
audio_ms?: {
|
|
121
|
+
atoms: string;
|
|
122
|
+
per: number;
|
|
123
|
+
} | undefined;
|
|
124
|
+
tasks?: {
|
|
125
|
+
atoms: string;
|
|
126
|
+
per: number;
|
|
127
|
+
} | undefined;
|
|
128
|
+
} | undefined;
|
|
129
|
+
};
|
|
130
|
+
task_kind?: "image" | "video" | "audio" | "task" | undefined;
|
|
131
|
+
max_usage?: {
|
|
132
|
+
images?: number | undefined;
|
|
133
|
+
video_ms?: number | undefined;
|
|
134
|
+
audio_ms?: number | undefined;
|
|
135
|
+
tasks?: number | undefined;
|
|
136
|
+
} | undefined;
|
|
137
|
+
latency_ms?: number | undefined;
|
|
138
|
+
reliability?: number | undefined;
|
|
139
|
+
quality?: number | undefined;
|
|
140
|
+
};
|
|
141
|
+
cost: bigint;
|
|
142
|
+
score: number;
|
|
143
|
+
}[];
|
|
144
|
+
excluded: {
|
|
145
|
+
id: string;
|
|
146
|
+
reason: string;
|
|
147
|
+
}[];
|
|
148
|
+
};
|
|
149
|
+
export declare class Router {
|
|
150
|
+
store: Store;
|
|
151
|
+
private providers;
|
|
152
|
+
private digestKey;
|
|
153
|
+
private clock;
|
|
154
|
+
constructor(store: Store, providers: Record<string, Provider>, digestKey: string, clock?: Clock);
|
|
155
|
+
/** Own providers only: an offering may name its provider `constructor` or `toString`, which `providers[name]` finds on Object.prototype. */
|
|
156
|
+
private providerFor;
|
|
157
|
+
infer(principal: Principal, raw: unknown, key: string, emit?: (event: StreamEvent) => Promise<void>, signal?: AbortSignal): Promise<{
|
|
158
|
+
replayed: boolean;
|
|
159
|
+
id: string;
|
|
160
|
+
execution_status: string;
|
|
161
|
+
billing_status: string;
|
|
162
|
+
service_version?: undefined;
|
|
163
|
+
model?: undefined;
|
|
164
|
+
tier?: undefined;
|
|
165
|
+
output?: undefined;
|
|
166
|
+
usage?: undefined;
|
|
167
|
+
billing?: undefined;
|
|
168
|
+
} | {
|
|
169
|
+
id: string;
|
|
170
|
+
execution_status: string;
|
|
171
|
+
billing_status: string;
|
|
172
|
+
service_version: number;
|
|
173
|
+
model: string | undefined;
|
|
174
|
+
tier: string | undefined;
|
|
175
|
+
output: {
|
|
176
|
+
role: string;
|
|
177
|
+
content: string;
|
|
178
|
+
};
|
|
179
|
+
usage: {
|
|
180
|
+
status: string;
|
|
181
|
+
meters: {
|
|
182
|
+
input: number;
|
|
183
|
+
cached: number;
|
|
184
|
+
cache_write: number;
|
|
185
|
+
output: number;
|
|
186
|
+
images?: number | undefined;
|
|
187
|
+
video_ms?: number | undefined;
|
|
188
|
+
audio_ms?: number | undefined;
|
|
189
|
+
tasks?: number | undefined;
|
|
190
|
+
};
|
|
191
|
+
} | {
|
|
192
|
+
status: string;
|
|
193
|
+
meters?: undefined;
|
|
194
|
+
};
|
|
195
|
+
billing: {
|
|
196
|
+
charges: {
|
|
197
|
+
kind: "customer_sale" | "platform_sale";
|
|
198
|
+
asset: string;
|
|
199
|
+
atoms: string;
|
|
200
|
+
scale: number;
|
|
201
|
+
}[];
|
|
202
|
+
};
|
|
203
|
+
replayed?: undefined;
|
|
204
|
+
}>;
|
|
205
|
+
}
|
|
206
|
+
export declare class MockProvider implements Provider {
|
|
207
|
+
private behavior;
|
|
208
|
+
private delay;
|
|
209
|
+
calls: number;
|
|
210
|
+
constructor(behavior?: "success" | "reject" | "unknown" | "partial", delay?: number);
|
|
211
|
+
invoke(input: Invocation, _offering: Offering, signal: AbortSignal): AsyncGenerator<{
|
|
212
|
+
type: "delta";
|
|
213
|
+
text: string;
|
|
214
|
+
usage?: undefined;
|
|
215
|
+
upstream_id?: undefined;
|
|
216
|
+
} | {
|
|
217
|
+
type: "usage";
|
|
218
|
+
usage: {
|
|
219
|
+
input: number;
|
|
220
|
+
cached: number;
|
|
221
|
+
cache_write: number;
|
|
222
|
+
output: number;
|
|
223
|
+
};
|
|
224
|
+
upstream_id: `${string}-${string}-${string}-${string}-${string}`;
|
|
225
|
+
text?: undefined;
|
|
226
|
+
} | {
|
|
227
|
+
type: "done";
|
|
228
|
+
text?: undefined;
|
|
229
|
+
usage?: undefined;
|
|
230
|
+
upstream_id?: undefined;
|
|
231
|
+
}, void, unknown>;
|
|
232
|
+
}
|
|
233
|
+
/** Simulated bounded task adapter. Produces a receipt, never actual image/video/audio. */
|
|
234
|
+
export declare class MockTaskProvider implements Provider {
|
|
235
|
+
private behavior;
|
|
236
|
+
calls: number;
|
|
237
|
+
constructor(behavior?: "success" | "reject" | "unknown" | "partial");
|
|
238
|
+
invoke(input: Invocation, offering: Offering, signal: AbortSignal): AsyncGenerator<{
|
|
239
|
+
type: "delta";
|
|
240
|
+
text: string;
|
|
241
|
+
usage?: undefined;
|
|
242
|
+
upstream_id?: undefined;
|
|
243
|
+
completion?: undefined;
|
|
244
|
+
} | {
|
|
245
|
+
type: "usage";
|
|
246
|
+
usage: {
|
|
247
|
+
[x: string]: number;
|
|
248
|
+
input: number;
|
|
249
|
+
cached: number;
|
|
250
|
+
cache_write: number;
|
|
251
|
+
output: number;
|
|
252
|
+
};
|
|
253
|
+
upstream_id: `${string}-${string}-${string}-${string}-${string}`;
|
|
254
|
+
text?: undefined;
|
|
255
|
+
completion?: undefined;
|
|
256
|
+
} | {
|
|
257
|
+
type: "done";
|
|
258
|
+
completion: "succeeded" | "partial";
|
|
259
|
+
text?: undefined;
|
|
260
|
+
usage?: undefined;
|
|
261
|
+
upstream_id?: undefined;
|
|
262
|
+
}, void, unknown>;
|
|
263
|
+
}
|
|
264
|
+
export * from "./credit-rates.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
import { createHmac, randomUUID } from "node:crypto";
|
|
2
|
+
import { Invocation, Meters, RouterError, ProviderError, } from "@supersolutions/super-router-contracts";
|
|
3
|
+
export { RouterError };
|
|
4
|
+
export const mediaKeys = ["images", "video_ms", "audio_ms", "tasks"];
|
|
5
|
+
export const kindMeter = {
|
|
6
|
+
image: "images",
|
|
7
|
+
video: "video_ms",
|
|
8
|
+
audio: "audio_ms",
|
|
9
|
+
task: "tasks",
|
|
10
|
+
};
|
|
11
|
+
export function charge(usage, price) {
|
|
12
|
+
const numerator = ["input", "cached", "cache_write", "output"].reduce((sum, key) => sum + BigInt(usage[key]) * BigInt(price[key]), 0n);
|
|
13
|
+
let total = (numerator + BigInt(price.per) - 1n) / BigInt(price.per);
|
|
14
|
+
for (const key of mediaKeys) {
|
|
15
|
+
const units = usage[key] ?? 0;
|
|
16
|
+
const rate = price.media?.[key];
|
|
17
|
+
if (units && !rate)
|
|
18
|
+
throw new RouterError("unpriced_meter", 422);
|
|
19
|
+
if (rate)
|
|
20
|
+
total +=
|
|
21
|
+
(BigInt(units) * BigInt(rate.atoms) + BigInt(rate.per) - 1n) /
|
|
22
|
+
BigInt(rate.per);
|
|
23
|
+
}
|
|
24
|
+
return total;
|
|
25
|
+
}
|
|
26
|
+
function invocationBound(input, maxInput, price) {
|
|
27
|
+
if (!input.input.task)
|
|
28
|
+
return bound(maxInput, input.limits.max_output_tokens, price);
|
|
29
|
+
return charge({
|
|
30
|
+
input: 0,
|
|
31
|
+
cached: 0,
|
|
32
|
+
cache_write: 0,
|
|
33
|
+
output: 0,
|
|
34
|
+
...input.limits.max_usage,
|
|
35
|
+
}, price);
|
|
36
|
+
}
|
|
37
|
+
export function bound(input, output, price) {
|
|
38
|
+
const rate = [price.input, price.cached, price.cache_write]
|
|
39
|
+
.map(BigInt)
|
|
40
|
+
.reduce((a, b) => (a > b ? a : b));
|
|
41
|
+
return ((BigInt(input) * rate +
|
|
42
|
+
BigInt(output) * BigInt(price.output) +
|
|
43
|
+
BigInt(price.per) -
|
|
44
|
+
1n) /
|
|
45
|
+
BigInt(price.per));
|
|
46
|
+
}
|
|
47
|
+
/** The canonical JSON of a value: object keys sorted, no whitespace. It is the input of the idempotency digest. */
|
|
48
|
+
export function canonical(value) {
|
|
49
|
+
if (Array.isArray(value))
|
|
50
|
+
return "[" + value.map(canonical).join(",") + "]";
|
|
51
|
+
if (value && typeof value === "object")
|
|
52
|
+
return ("{" +
|
|
53
|
+
Object.entries(value)
|
|
54
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
55
|
+
.map(([k, v]) => JSON.stringify(k) + ":" + canonical(v))
|
|
56
|
+
.join(",") +
|
|
57
|
+
"}");
|
|
58
|
+
return JSON.stringify(value);
|
|
59
|
+
}
|
|
60
|
+
export function route(service, input) {
|
|
61
|
+
const excluded = [];
|
|
62
|
+
const candidates = service.offerings
|
|
63
|
+
.flatMap((o) => {
|
|
64
|
+
let reason = "";
|
|
65
|
+
if (o.task_kind !== input.input.task?.kind ||
|
|
66
|
+
service.task_kind !== input.input.task?.kind)
|
|
67
|
+
reason = "task_kind_mismatch";
|
|
68
|
+
else if (!o.enabled)
|
|
69
|
+
reason = "disabled";
|
|
70
|
+
else if (service.mode === "specific" && o.model !== service.model)
|
|
71
|
+
reason = "model_mismatch";
|
|
72
|
+
else if (!service.regions.includes(o.region))
|
|
73
|
+
reason = "region_mismatch";
|
|
74
|
+
else if (service.required_labels.some((x) => !o.labels.includes(x)))
|
|
75
|
+
reason = "label_mismatch";
|
|
76
|
+
else if (input.limits.max_output_tokens > o.max_output_tokens)
|
|
77
|
+
reason = "output_limit";
|
|
78
|
+
if (!reason && input.input.task) {
|
|
79
|
+
const key = kindMeter[input.input.task.kind];
|
|
80
|
+
const units = input.limits.max_usage?.[key];
|
|
81
|
+
if (!units ||
|
|
82
|
+
units > (o.max_usage?.[key] ?? 0) ||
|
|
83
|
+
!o.price.media?.[key])
|
|
84
|
+
reason = "meter_limit";
|
|
85
|
+
}
|
|
86
|
+
const cost = reason
|
|
87
|
+
? 0n
|
|
88
|
+
: invocationBound(input, o.max_input_tokens, o.price);
|
|
89
|
+
if (!reason && cost > BigInt(service.max_provider_cost))
|
|
90
|
+
reason = "budget_exceeded";
|
|
91
|
+
if (reason) {
|
|
92
|
+
excluded.push({ id: o.id, reason });
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
const ratio = Number((cost * 1000000n) / BigInt(service.cost_scale)) / 1_000_000;
|
|
96
|
+
const score = service.weights.cost * (1 - Math.min(1, ratio)) +
|
|
97
|
+
service.weights.latency *
|
|
98
|
+
(o.latency_ms === undefined
|
|
99
|
+
? service.unknown_score
|
|
100
|
+
: 1 - Math.min(1, o.latency_ms / service.latency_scale_ms)) +
|
|
101
|
+
service.weights.reliability * (o.reliability ?? service.unknown_score) +
|
|
102
|
+
service.weights.quality * (o.quality ?? service.unknown_score);
|
|
103
|
+
return [{ offering: o, cost, score }];
|
|
104
|
+
})
|
|
105
|
+
.sort((a, b) => b.score - a.score || a.offering.id.localeCompare(b.offering.id));
|
|
106
|
+
return { candidates, excluded };
|
|
107
|
+
}
|
|
108
|
+
export class Router {
|
|
109
|
+
store;
|
|
110
|
+
providers;
|
|
111
|
+
digestKey;
|
|
112
|
+
clock;
|
|
113
|
+
constructor(store, providers, digestKey, clock = Date.now) {
|
|
114
|
+
this.store = store;
|
|
115
|
+
this.providers = providers;
|
|
116
|
+
this.digestKey = digestKey;
|
|
117
|
+
this.clock = clock;
|
|
118
|
+
if (digestKey.length < 32)
|
|
119
|
+
throw new Error("digest key must be >=32 characters");
|
|
120
|
+
}
|
|
121
|
+
/** Own providers only: an offering may name its provider `constructor` or `toString`, which `providers[name]` finds on Object.prototype. */
|
|
122
|
+
providerFor(name) {
|
|
123
|
+
return Object.hasOwn(this.providers, name)
|
|
124
|
+
? this.providers[name]
|
|
125
|
+
: undefined;
|
|
126
|
+
}
|
|
127
|
+
async infer(principal, raw, key, emit, signal) {
|
|
128
|
+
if (!principal.scopes.includes("invoke"))
|
|
129
|
+
throw new RouterError("scope_denied", 403);
|
|
130
|
+
const parsed = Invocation.safeParse(raw);
|
|
131
|
+
if (!parsed.success)
|
|
132
|
+
throw new RouterError("invalid_request", 400);
|
|
133
|
+
const input = parsed.data;
|
|
134
|
+
if (input.input.task) {
|
|
135
|
+
const meter = kindMeter[input.input.task.kind];
|
|
136
|
+
const limits = input.limits.max_usage;
|
|
137
|
+
if (input.input.messages.length ||
|
|
138
|
+
!limits?.[meter] ||
|
|
139
|
+
mediaKeys.some((k) => k !== meter && (limits[k] ?? 0) !== 0) ||
|
|
140
|
+
(meter === "tasks" && limits.tasks !== 1))
|
|
141
|
+
throw new RouterError("invalid_task_limits", 400);
|
|
142
|
+
}
|
|
143
|
+
else if (!input.input.messages.length || input.limits.max_usage)
|
|
144
|
+
throw new RouterError("invalid_request", 400);
|
|
145
|
+
if (principal.service_ids && !principal.service_ids.includes(input.service))
|
|
146
|
+
throw new RouterError("scope_denied", 403);
|
|
147
|
+
if (input.customer_id !== principal.customer)
|
|
148
|
+
throw new RouterError("scope_denied", 403);
|
|
149
|
+
if (!key || key.length > 200)
|
|
150
|
+
throw new RouterError("missing_idempotency_key", 400);
|
|
151
|
+
const digest = createHmac("sha256", this.digestKey)
|
|
152
|
+
.update(canonical(input))
|
|
153
|
+
.digest("hex");
|
|
154
|
+
const existing = await this.store.replay(principal, key, digest);
|
|
155
|
+
if (existing)
|
|
156
|
+
return {
|
|
157
|
+
replayed: true,
|
|
158
|
+
id: existing.id,
|
|
159
|
+
execution_status: existing.execution,
|
|
160
|
+
billing_status: existing.billing,
|
|
161
|
+
};
|
|
162
|
+
const service = await this.store.getService(principal, input.service, input.service_version);
|
|
163
|
+
if (input.service_version !== undefined) {
|
|
164
|
+
const active = await this.store.getService(principal, input.service);
|
|
165
|
+
if (active.version !== service.version)
|
|
166
|
+
throw new RouterError("inactive_service_version", 409);
|
|
167
|
+
}
|
|
168
|
+
if (input.limits.max_output_tokens > service.max_output_tokens)
|
|
169
|
+
throw new RouterError("unsupported_capability", 422);
|
|
170
|
+
const decision = route(service, input);
|
|
171
|
+
if (!decision.candidates.length)
|
|
172
|
+
throw new RouterError("no_eligible_offering", 422);
|
|
173
|
+
if (decision.candidates.some((c) => !this.providerFor(c.offering.provider)))
|
|
174
|
+
throw new RouterError("provider_unavailable", 503);
|
|
175
|
+
const maxInput = Math.max(...decision.candidates.map((c) => c.offering.max_input_tokens));
|
|
176
|
+
const legs = await this.store.accounts(principal, service);
|
|
177
|
+
for (const leg of legs) {
|
|
178
|
+
leg.reserved = invocationBound(input, maxInput, leg.price).toString();
|
|
179
|
+
if (leg.kind === "customer_sale" &&
|
|
180
|
+
input.limits.max_charge &&
|
|
181
|
+
(input.limits.max_charge.asset !== leg.price.asset ||
|
|
182
|
+
BigInt(input.limits.max_charge.atoms) < BigInt(leg.reserved)))
|
|
183
|
+
throw new RouterError("budget_exceeded", 402);
|
|
184
|
+
}
|
|
185
|
+
const reservation = await this.store.reserve(principal, key, digest, service, legs, new Date(this.clock() + input.limits.timeout_ms).toISOString(), {
|
|
186
|
+
excluded: decision.excluded,
|
|
187
|
+
candidates: decision.candidates.map((c) => ({
|
|
188
|
+
id: c.offering.id,
|
|
189
|
+
score: c.score,
|
|
190
|
+
cost: c.cost.toString(),
|
|
191
|
+
})),
|
|
192
|
+
});
|
|
193
|
+
const request = reservation.request;
|
|
194
|
+
if (!reservation.fresh)
|
|
195
|
+
return {
|
|
196
|
+
replayed: true,
|
|
197
|
+
id: request.id,
|
|
198
|
+
execution_status: request.execution,
|
|
199
|
+
billing_status: request.billing,
|
|
200
|
+
};
|
|
201
|
+
let seq = 0, text = "", started = false, finalUsage = null, execution = "failed", pending = false, lastModel;
|
|
202
|
+
const send = async (type, data = {}) => {
|
|
203
|
+
await emit?.({ type, request_id: request.id, sequence: ++seq, ...data });
|
|
204
|
+
};
|
|
205
|
+
const controller = new AbortController();
|
|
206
|
+
const abort = () => controller.abort();
|
|
207
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
208
|
+
if (signal?.aborted)
|
|
209
|
+
abort();
|
|
210
|
+
const timeout = setTimeout(abort, input.limits.timeout_ms);
|
|
211
|
+
let polling = false;
|
|
212
|
+
const poll = setInterval(() => {
|
|
213
|
+
if (polling)
|
|
214
|
+
return;
|
|
215
|
+
polling = true;
|
|
216
|
+
void this.store
|
|
217
|
+
.get(principal, request.id)
|
|
218
|
+
.then((r) => {
|
|
219
|
+
if (r.cancel_requested)
|
|
220
|
+
abort();
|
|
221
|
+
})
|
|
222
|
+
.catch(abort)
|
|
223
|
+
.finally(() => {
|
|
224
|
+
polling = false;
|
|
225
|
+
});
|
|
226
|
+
}, 100);
|
|
227
|
+
poll.unref();
|
|
228
|
+
try {
|
|
229
|
+
await send("request.started", { service_version: service.version });
|
|
230
|
+
for (const candidate of decision.candidates.slice(0, service.max_attempts)) {
|
|
231
|
+
if (controller.signal.aborted) {
|
|
232
|
+
execution = "cancelled";
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
const provider = this.providerFor(candidate.offering.provider);
|
|
236
|
+
if (!provider)
|
|
237
|
+
throw new RouterError("provider_unavailable", 503);
|
|
238
|
+
let attempt;
|
|
239
|
+
try {
|
|
240
|
+
attempt = await this.store.begin(principal, request.id, candidate.offering, candidate.cost.toString());
|
|
241
|
+
}
|
|
242
|
+
catch (e) {
|
|
243
|
+
if (e instanceof RouterError &&
|
|
244
|
+
["budget_exceeded", "connection_disabled", "cancelled"].includes(e.code)) {
|
|
245
|
+
execution = e.code === "cancelled" ? "cancelled" : "failed";
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
throw e;
|
|
249
|
+
}
|
|
250
|
+
let usage = null, upstream, done = false, completion = "succeeded";
|
|
251
|
+
lastModel = candidate.offering.model;
|
|
252
|
+
try {
|
|
253
|
+
for await (const event of provider.invoke(input, candidate.offering, controller.signal)) {
|
|
254
|
+
if (event.type === "delta") {
|
|
255
|
+
if (!started) {
|
|
256
|
+
await this.store.output(principal, request.id);
|
|
257
|
+
started = true;
|
|
258
|
+
}
|
|
259
|
+
text += event.text;
|
|
260
|
+
if (Buffer.byteLength(text) > 1_000_000)
|
|
261
|
+
throw new ProviderError(false, false, "output_too_large");
|
|
262
|
+
await send("output.delta", { text: event.text });
|
|
263
|
+
}
|
|
264
|
+
else if (event.type === "usage") {
|
|
265
|
+
const parsedUsage = Meters.safeParse(event.usage);
|
|
266
|
+
if (!parsedUsage.success)
|
|
267
|
+
throw new ProviderError(false, false, "invalid_usage");
|
|
268
|
+
usage = parsedUsage.data;
|
|
269
|
+
upstream = event.upstream_id;
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
done = true;
|
|
273
|
+
completion = event.completion ?? "succeeded";
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (!done || !usage)
|
|
277
|
+
throw new ProviderError(false, false, "usage_unknown");
|
|
278
|
+
if (input.input.task) {
|
|
279
|
+
const meter = kindMeter[input.input.task.kind];
|
|
280
|
+
if (["input", "cached", "cache_write", "output"].some((k) => usage[k] !== 0) ||
|
|
281
|
+
mediaKeys.some((k) => (usage[k] ?? 0) > (input.limits.max_usage?.[k] ?? 0)) ||
|
|
282
|
+
(meter === "tasks" &&
|
|
283
|
+
usage.tasks !== (completion === "succeeded" ? 1 : 0))) {
|
|
284
|
+
usage = null;
|
|
285
|
+
throw new ProviderError(false, false, "usage_out_of_bounds");
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
else if (mediaKeys.some((k) => (usage[k] ?? 0) !== 0)) {
|
|
289
|
+
usage = null;
|
|
290
|
+
throw new ProviderError(false, false, "unexpected_meter");
|
|
291
|
+
}
|
|
292
|
+
await this.store.attemptResult(principal, request.id, attempt, completion, usage, charge(usage, candidate.offering.price).toString(), upstream);
|
|
293
|
+
finalUsage = usage;
|
|
294
|
+
execution = completion;
|
|
295
|
+
pending = charge(usage, candidate.offering.price) > candidate.cost;
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
catch (e) {
|
|
299
|
+
const definitive = e instanceof ProviderError && e.definitive && !started;
|
|
300
|
+
await this.store.attemptResult(principal, request.id, attempt, definitive ? "failed" : "unknown", usage, usage
|
|
301
|
+
? charge(usage, candidate.offering.price).toString()
|
|
302
|
+
: definitive
|
|
303
|
+
? "0"
|
|
304
|
+
: null, upstream);
|
|
305
|
+
if (!definitive) {
|
|
306
|
+
pending = true;
|
|
307
|
+
execution = started ? "partial" : "unknown";
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
if (!(e instanceof ProviderError && e.retryable))
|
|
311
|
+
break;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
await this.store.finish(principal, request.id, execution, finalUsage, pending);
|
|
315
|
+
const settled = await this.store.get(principal, request.id);
|
|
316
|
+
await send(execution === "succeeded" ? "request.completed" : "request.failed", { execution_status: execution, billing_status: settled.billing });
|
|
317
|
+
return {
|
|
318
|
+
id: request.id,
|
|
319
|
+
execution_status: execution,
|
|
320
|
+
billing_status: settled.billing,
|
|
321
|
+
service_version: service.version,
|
|
322
|
+
model: lastModel,
|
|
323
|
+
tier: service.tier,
|
|
324
|
+
output: { role: "assistant", content: text },
|
|
325
|
+
usage: finalUsage
|
|
326
|
+
? { status: "confirmed", meters: finalUsage }
|
|
327
|
+
: {
|
|
328
|
+
status: settled.billing === "released" ? "not_billable" : "pending",
|
|
329
|
+
},
|
|
330
|
+
billing: {
|
|
331
|
+
charges: finalUsage && settled.billing === "settled"
|
|
332
|
+
? legs
|
|
333
|
+
.filter((l) => l.kind === "customer_sale" ||
|
|
334
|
+
principal.scopes.includes("billing:read"))
|
|
335
|
+
.map((l) => ({
|
|
336
|
+
kind: l.kind,
|
|
337
|
+
asset: l.price.asset,
|
|
338
|
+
atoms: charge(finalUsage, l.price).toString(),
|
|
339
|
+
scale: 9,
|
|
340
|
+
}))
|
|
341
|
+
: [],
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
catch (e) {
|
|
346
|
+
// Unexpected storage/transport failure must never turn an uncertain dispatch into a refund.
|
|
347
|
+
await this.store
|
|
348
|
+
.finish(principal, request.id, started ? "partial" : "unknown", null, true)
|
|
349
|
+
.catch(() => { });
|
|
350
|
+
const failure = e instanceof RouterError
|
|
351
|
+
? e
|
|
352
|
+
: new RouterError("execution_unknown", 503, false);
|
|
353
|
+
failure.request_id = request.id;
|
|
354
|
+
throw failure;
|
|
355
|
+
}
|
|
356
|
+
finally {
|
|
357
|
+
clearTimeout(timeout);
|
|
358
|
+
clearInterval(poll);
|
|
359
|
+
signal?.removeEventListener("abort", abort);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
export class MockProvider {
|
|
364
|
+
behavior;
|
|
365
|
+
delay;
|
|
366
|
+
calls = 0;
|
|
367
|
+
constructor(behavior = "success", delay = 0) {
|
|
368
|
+
this.behavior = behavior;
|
|
369
|
+
this.delay = delay;
|
|
370
|
+
}
|
|
371
|
+
async *invoke(input, _offering, signal) {
|
|
372
|
+
this.calls++;
|
|
373
|
+
if (input.input.task)
|
|
374
|
+
throw new ProviderError(true, false, "unsupported_task");
|
|
375
|
+
if (this.delay)
|
|
376
|
+
await new Promise((resolve, reject) => {
|
|
377
|
+
const t = setTimeout(resolve, this.delay);
|
|
378
|
+
signal.addEventListener("abort", () => {
|
|
379
|
+
clearTimeout(t);
|
|
380
|
+
reject(new ProviderError(false, false));
|
|
381
|
+
}, { once: true });
|
|
382
|
+
});
|
|
383
|
+
if (this.behavior === "reject")
|
|
384
|
+
throw new ProviderError(true, true, "rate_limited");
|
|
385
|
+
if (this.behavior === "unknown" || signal.aborted)
|
|
386
|
+
throw new ProviderError(false, false);
|
|
387
|
+
yield { type: "delta", text: "Hello from SuperRouter." };
|
|
388
|
+
if (this.behavior === "partial")
|
|
389
|
+
throw new ProviderError(false, false);
|
|
390
|
+
yield {
|
|
391
|
+
type: "usage",
|
|
392
|
+
usage: {
|
|
393
|
+
input: 10,
|
|
394
|
+
cached: 0,
|
|
395
|
+
cache_write: 0,
|
|
396
|
+
output: Math.min(5, input.limits.max_output_tokens),
|
|
397
|
+
},
|
|
398
|
+
upstream_id: randomUUID(),
|
|
399
|
+
};
|
|
400
|
+
yield { type: "done" };
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** Simulated bounded task adapter. Produces a receipt, never actual image/video/audio. */
|
|
404
|
+
export class MockTaskProvider {
|
|
405
|
+
behavior;
|
|
406
|
+
calls = 0;
|
|
407
|
+
constructor(behavior = "success") {
|
|
408
|
+
this.behavior = behavior;
|
|
409
|
+
}
|
|
410
|
+
async *invoke(input, offering, signal) {
|
|
411
|
+
this.calls++;
|
|
412
|
+
const task = input.input.task;
|
|
413
|
+
if (!task || task.kind !== offering.task_kind || this.behavior === "reject")
|
|
414
|
+
throw new ProviderError(true, false, "unsupported_task");
|
|
415
|
+
if (signal.aborted || this.behavior === "unknown")
|
|
416
|
+
throw new ProviderError(false, false, "usage_unknown");
|
|
417
|
+
const meter = kindMeter[task.kind];
|
|
418
|
+
const units = input.limits.max_usage?.[meter] ?? 0;
|
|
419
|
+
if (!units || units > (offering.max_usage?.[meter] ?? 0))
|
|
420
|
+
throw new ProviderError(true, false, "meter_limit");
|
|
421
|
+
const partial = this.behavior === "partial";
|
|
422
|
+
const completed = partial
|
|
423
|
+
? meter === "tasks"
|
|
424
|
+
? 0
|
|
425
|
+
: Math.floor(units / 2)
|
|
426
|
+
: units;
|
|
427
|
+
yield {
|
|
428
|
+
type: "delta",
|
|
429
|
+
text: `Simulated ${task.kind} task receipt; no media generated.`,
|
|
430
|
+
};
|
|
431
|
+
yield {
|
|
432
|
+
type: "usage",
|
|
433
|
+
usage: {
|
|
434
|
+
input: 0,
|
|
435
|
+
cached: 0,
|
|
436
|
+
cache_write: 0,
|
|
437
|
+
output: 0,
|
|
438
|
+
[meter]: completed,
|
|
439
|
+
},
|
|
440
|
+
upstream_id: randomUUID(),
|
|
441
|
+
};
|
|
442
|
+
yield {
|
|
443
|
+
type: "done",
|
|
444
|
+
completion: partial ? "partial" : "succeeded",
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
export * from "./credit-rates.js";
|
package/package.json
CHANGED
|
@@ -1,16 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@supersolutions/super-router-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Placeholder; real releases come from GitHub Actions.",
|
|
3
|
+
"version": "0.1.0",
|
|
5
4
|
"license": "Apache-2.0",
|
|
6
|
-
"
|
|
7
|
-
|
|
8
|
-
"
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.js"
|
|
10
|
+
}
|
|
9
11
|
},
|
|
10
12
|
"files": [
|
|
11
|
-
"
|
|
13
|
+
"dist",
|
|
14
|
+
"LICENSE",
|
|
15
|
+
"NOTICE"
|
|
12
16
|
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc -p tsconfig.json"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@supersolutions/super-router-contracts": "0.1.0"
|
|
22
|
+
},
|
|
23
|
+
"author": "SUPER SOLUTION LABS INC",
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/Super-Solution/super-router.git",
|
|
27
|
+
"directory": "packages/core"
|
|
28
|
+
},
|
|
29
|
+
"homepage": "https://github.com/Super-Solution/super-router#readme",
|
|
30
|
+
"bugs": {
|
|
31
|
+
"url": "https://github.com/Super-Solution/super-router/issues"
|
|
32
|
+
},
|
|
13
33
|
"publishConfig": {
|
|
14
34
|
"access": "public"
|
|
15
35
|
}
|
|
16
|
-
}
|
|
36
|
+
}
|
package/README.md
DELETED