@agentproto/model-intel 0.0.0-stage → 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 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/README.md CHANGED
@@ -1,3 +1,11 @@
1
- # Temporary Holding Version
1
+ # @agentproto/model-intel
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
+ Model intelligence primitives. This first slice is the unified quota status
4
+ contract of AIP-67 (`quota/v1`):
5
+
6
+ - `QuotaStatus` with a mandatory `basis` (`provider` | `probe` | `observed` | `estimated`)
7
+ - `QuotaWindow.remainingPct` (0-100) is required; a window that cannot state it is omitted
8
+ - `QuotaReader`: never throws, never fabricates, unknown resolves to `undefined`
9
+ - `QuotaReaderRegistry` / `defineQuotaReader`
10
+
11
+ Core readers MUST NOT emit `basis: "probe"`.
@@ -0,0 +1,144 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Where a quota figure came from. `provider` is a documented provider
5
+ * surface; `observed` is derived from this host's own traffic; `estimated`
6
+ * is a local computation; `probe` is an undocumented surface reached through
7
+ * a connector and MUST NOT be emitted by core readers.
8
+ */
9
+ declare const QUOTA_BASES: readonly ["provider", "probe", "observed", "estimated"];
10
+ type QuotaBasis = (typeof QUOTA_BASES)[number];
11
+ declare const quotaWindowSchema: z.ZodObject<{
12
+ id: z.ZodString;
13
+ remainingPct: z.ZodNumber;
14
+ used: z.ZodOptional<z.ZodNumber>;
15
+ limit: z.ZodOptional<z.ZodNumber>;
16
+ remaining: z.ZodOptional<z.ZodNumber>;
17
+ unit: z.ZodOptional<z.ZodString>;
18
+ resetsAt: z.ZodOptional<z.ZodString>;
19
+ }, z.core.$strip>;
20
+ type QuotaWindow = z.infer<typeof quotaWindowSchema>;
21
+ declare const quotaCreditsSchema: z.ZodObject<{
22
+ balanceUsd: z.ZodOptional<z.ZodNumber>;
23
+ unlimited: z.ZodOptional<z.ZodBoolean>;
24
+ currency: z.ZodString;
25
+ }, z.core.$strip>;
26
+ type QuotaCredits = z.infer<typeof quotaCreditsSchema>;
27
+ declare const quotaStatusSchema: z.ZodObject<{
28
+ profileRef: z.ZodString;
29
+ asOf: z.ZodString;
30
+ basis: z.ZodEnum<{
31
+ provider: "provider";
32
+ probe: "probe";
33
+ observed: "observed";
34
+ estimated: "estimated";
35
+ }>;
36
+ source: z.ZodOptional<z.ZodString>;
37
+ windows: z.ZodArray<z.ZodObject<{
38
+ id: z.ZodString;
39
+ remainingPct: z.ZodNumber;
40
+ used: z.ZodOptional<z.ZodNumber>;
41
+ limit: z.ZodOptional<z.ZodNumber>;
42
+ remaining: z.ZodOptional<z.ZodNumber>;
43
+ unit: z.ZodOptional<z.ZodString>;
44
+ resetsAt: z.ZodOptional<z.ZodString>;
45
+ }, z.core.$strip>>;
46
+ credits: z.ZodOptional<z.ZodObject<{
47
+ balanceUsd: z.ZodOptional<z.ZodNumber>;
48
+ unlimited: z.ZodOptional<z.ZodBoolean>;
49
+ currency: z.ZodString;
50
+ }, z.core.$strip>>;
51
+ }, z.core.$strip>;
52
+ type QuotaStatus = z.infer<typeof quotaStatusSchema>;
53
+ /** The minimal auth-profile projection a reader needs. */
54
+ interface QuotaProfile {
55
+ profileRef: string;
56
+ endpoint: string;
57
+ method: "oauth-bearer" | "api-key";
58
+ credentialRef?: string;
59
+ }
60
+ interface QuotaReadContext {
61
+ signal?: AbortSignal;
62
+ /** Resolve a profile's opaque credentialRef to a bearer secret. */
63
+ resolveCredential?(ref: string): Promise<string | undefined>;
64
+ fetchImpl?: typeof fetch;
65
+ now?: () => Date;
66
+ }
67
+ /**
68
+ * Reads quota for a profile. MUST NOT throw: any failure or unknown value
69
+ * resolves to `undefined`. Never fabricates a figure.
70
+ */
71
+ interface QuotaReader {
72
+ readonly id: string;
73
+ supports(profile: QuotaProfile): boolean;
74
+ read(profile: QuotaProfile, ctx: QuotaReadContext): Promise<QuotaStatus | undefined>;
75
+ }
76
+
77
+ /** remainingPct from a used percentage, or undefined when it is not a finite 0-100 number. */
78
+ declare function remainingPctFromUsed(usedPct: number | null | undefined): number | undefined;
79
+ /** remainingPct from remaining/limit counts, or undefined when limit is not a positive finite number. */
80
+ declare function remainingPctFromCounts(remaining: number | null | undefined, limit: number | null | undefined): number | undefined;
81
+ interface BuildQuotaStatusInput {
82
+ profileRef: string;
83
+ basis: QuotaBasis;
84
+ source?: string;
85
+ now?: () => Date;
86
+ /** Candidate windows; any that fail validation are dropped, never repaired. */
87
+ windows?: readonly unknown[];
88
+ credits?: QuotaCredits;
89
+ }
90
+ /**
91
+ * Assemble a QuotaStatus. Invalid windows are omitted. Returns `undefined`
92
+ * when there is nothing to report (no valid window and no credits).
93
+ */
94
+ declare function buildQuotaStatus(input: BuildQuotaStatusInput): QuotaStatus | undefined;
95
+
96
+ /** Identity helper that fixes the QuotaReader contract at definition time (AIP-43 handle). */
97
+ declare function defineQuotaReader(reader: QuotaReader): QuotaReader;
98
+ declare class QuotaReaderRegistry {
99
+ private readonly readers;
100
+ register(reader: QuotaReader): this;
101
+ list(): QuotaReader[];
102
+ /** First registered reader that supports the profile, in registration order. */
103
+ find(profile: QuotaProfile): QuotaReader | undefined;
104
+ /** Read through the first supporting reader. Never throws; unknown -> undefined. */
105
+ read(profile: QuotaProfile, ctx?: QuotaReadContext): Promise<QuotaStatus | undefined>;
106
+ }
107
+
108
+ interface AnthropicHeadersInput {
109
+ profileRef: string;
110
+ headers: Headers | Record<string, string | undefined>;
111
+ now?: () => Date;
112
+ }
113
+ /**
114
+ * PURE: build a QuotaStatus from Anthropic's DOCUMENTED rate-limit headers
115
+ * `anthropic-ratelimit-{requests,tokens,input-tokens,output-tokens}-{limit,remaining,reset}`.
116
+ * The undocumented `anthropic-ratelimit-unified-*` family is never read.
117
+ * A dimension with a missing/non-numeric limit or remaining is skipped.
118
+ */
119
+ declare function quotaFromAnthropicHeaders(input: AnthropicHeadersInput): QuotaStatus | undefined;
120
+
121
+ interface OpenRouterQuotaReaderOptions {
122
+ baseUrl?: string;
123
+ timeoutMs?: number;
124
+ }
125
+ /**
126
+ * OpenRouter quota reader: `GET /key` exposes the key's USD cap and remaining
127
+ * headroom. The whole read is wrapped so it never throws; an uncapped key
128
+ * (`limit_remaining` null/absent) yields no window and no credits.
129
+ */
130
+ declare function createOpenRouterQuotaReader(opts?: OpenRouterQuotaReaderOptions): QuotaReader;
131
+
132
+ /**
133
+ * @agentproto/model-intel — model intelligence primitives.
134
+ *
135
+ * Unified, provider-neutral quota status (AIP-67): one QuotaStatus shape with a
136
+ * mandatory `basis`, a never-throw QuotaReader contract, and a reader registry.
137
+ * Unknown is omitted, never fabricated.
138
+ *
139
+ * @see https://agentproto.sh/docs/aip-67
140
+ */
141
+ declare const SPEC_NAME: "quota/v1";
142
+ declare const SPEC_VERSION: "1.0.0-alpha";
143
+
144
+ export { type BuildQuotaStatusInput, QUOTA_BASES, type QuotaBasis, type QuotaCredits, type QuotaProfile, type QuotaReadContext, type QuotaReader, QuotaReaderRegistry, type QuotaStatus, type QuotaWindow, SPEC_NAME, SPEC_VERSION, buildQuotaStatus, createOpenRouterQuotaReader, defineQuotaReader, quotaCreditsSchema, quotaFromAnthropicHeaders, quotaStatusSchema, quotaWindowSchema, remainingPctFromCounts, remainingPctFromUsed };
package/dist/index.mjs ADDED
@@ -0,0 +1,251 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * @agentproto/model-intel v0.1.0
5
+ * Model intelligence: unified quota status (AIP-67).
6
+ */
7
+
8
+ var QUOTA_BASES = ["provider", "probe", "observed", "estimated"];
9
+ var isoTimestamp = z.string().refine((s) => !Number.isNaN(Date.parse(s)), {
10
+ message: "expected an ISO-8601 timestamp"
11
+ });
12
+ var quotaWindowSchema = z.object({
13
+ /** Open string: "5h", "7d", "month", "minute", "day", "primary", "key_limit", ... */
14
+ id: z.string().min(1),
15
+ /** 0-100. Required: a window that cannot state it is not emitted. */
16
+ remainingPct: z.number().min(0).max(100),
17
+ used: z.number().optional(),
18
+ limit: z.number().optional(),
19
+ remaining: z.number().optional(),
20
+ unit: z.string().optional(),
21
+ resetsAt: isoTimestamp.optional()
22
+ });
23
+ var quotaCreditsSchema = z.object({
24
+ balanceUsd: z.number().optional(),
25
+ unlimited: z.boolean().optional(),
26
+ currency: z.string().min(1)
27
+ });
28
+ var quotaStatusSchema = z.object({
29
+ profileRef: z.string().min(1),
30
+ asOf: isoTimestamp,
31
+ basis: z.enum(QUOTA_BASES),
32
+ source: z.string().optional(),
33
+ windows: z.array(quotaWindowSchema),
34
+ credits: quotaCreditsSchema.optional()
35
+ });
36
+
37
+ // src/build.ts
38
+ function remainingPctFromUsed(usedPct) {
39
+ if (usedPct === null || usedPct === void 0 || !Number.isFinite(usedPct)) return void 0;
40
+ if (usedPct < 0 || usedPct > 100) return void 0;
41
+ return 100 - usedPct;
42
+ }
43
+ function remainingPctFromCounts(remaining, limit) {
44
+ if (remaining === null || remaining === void 0 || limit === null || limit === void 0) {
45
+ return void 0;
46
+ }
47
+ if (!Number.isFinite(remaining) || !Number.isFinite(limit) || limit <= 0) return void 0;
48
+ if (remaining < 0 || remaining > limit) return void 0;
49
+ return remaining / limit * 100;
50
+ }
51
+ function buildQuotaStatus(input) {
52
+ const windows = [];
53
+ for (const candidate of input.windows ?? []) {
54
+ const parsed = quotaWindowSchema.safeParse(candidate);
55
+ if (parsed.success) windows.push(parsed.data);
56
+ }
57
+ if (windows.length === 0 && input.credits === void 0) return void 0;
58
+ return {
59
+ profileRef: input.profileRef,
60
+ asOf: (input.now ?? (() => /* @__PURE__ */ new Date()))().toISOString(),
61
+ basis: input.basis,
62
+ ...input.source !== void 0 ? { source: input.source } : {},
63
+ windows,
64
+ ...input.credits !== void 0 ? { credits: input.credits } : {}
65
+ };
66
+ }
67
+
68
+ // src/registry.ts
69
+ function defineQuotaReader(reader) {
70
+ return reader;
71
+ }
72
+ var QuotaReaderRegistry = class {
73
+ readers = /* @__PURE__ */ new Map();
74
+ register(reader) {
75
+ if (this.readers.has(reader.id)) {
76
+ throw new Error(`quota reader already registered: ${reader.id}`);
77
+ }
78
+ this.readers.set(reader.id, reader);
79
+ return this;
80
+ }
81
+ list() {
82
+ return [...this.readers.values()];
83
+ }
84
+ /** First registered reader that supports the profile, in registration order. */
85
+ find(profile) {
86
+ for (const reader of this.readers.values()) {
87
+ if (safeSupports(reader, profile)) return reader;
88
+ }
89
+ return void 0;
90
+ }
91
+ /** Read through the first supporting reader. Never throws; unknown -> undefined. */
92
+ async read(profile, ctx = {}) {
93
+ const reader = this.find(profile);
94
+ if (!reader) return void 0;
95
+ try {
96
+ return await reader.read(profile, ctx);
97
+ } catch {
98
+ return void 0;
99
+ }
100
+ }
101
+ };
102
+ function safeSupports(reader, profile) {
103
+ try {
104
+ return reader.supports(profile);
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ // src/readers/anthropic.ts
111
+ var DIMENSIONS = [
112
+ { id: "requests-1m", header: "requests", unit: "requests" },
113
+ { id: "tokens-1m", header: "tokens", unit: "tokens" },
114
+ { id: "input-tokens-1m", header: "input-tokens", unit: "tokens" },
115
+ { id: "output-tokens-1m", header: "output-tokens", unit: "tokens" }
116
+ ];
117
+ function headerGet(headers, name) {
118
+ if (headers instanceof Headers) {
119
+ return headers.get(name) ?? void 0;
120
+ }
121
+ const lower = name.toLowerCase();
122
+ for (const [key, value] of Object.entries(headers)) {
123
+ if (key.toLowerCase() === lower) return value;
124
+ }
125
+ return void 0;
126
+ }
127
+ function parseCount(raw) {
128
+ if (raw === void 0) return void 0;
129
+ const trimmed = raw.trim();
130
+ if (!trimmed) return void 0;
131
+ const n = Number(trimmed);
132
+ return Number.isFinite(n) ? n : void 0;
133
+ }
134
+ function parseReset(raw) {
135
+ if (raw === void 0) return void 0;
136
+ const trimmed = raw.trim();
137
+ if (!trimmed) return void 0;
138
+ const date = new Date(trimmed);
139
+ return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
140
+ }
141
+ function quotaFromAnthropicHeaders(input) {
142
+ const windows = [];
143
+ for (const dimension of DIMENSIONS) {
144
+ const prefix = `anthropic-ratelimit-${dimension.header}`;
145
+ const limit = parseCount(headerGet(input.headers, `${prefix}-limit`));
146
+ const remaining = parseCount(headerGet(input.headers, `${prefix}-remaining`));
147
+ if (limit === void 0 || remaining === void 0) continue;
148
+ const remainingPct = remainingPctFromCounts(remaining, limit);
149
+ if (remainingPct === void 0) continue;
150
+ const resetsAt = parseReset(headerGet(input.headers, `${prefix}-reset`));
151
+ windows.push({
152
+ id: dimension.id,
153
+ remainingPct,
154
+ limit,
155
+ remaining,
156
+ unit: dimension.unit,
157
+ ...resetsAt !== void 0 ? { resetsAt } : {}
158
+ });
159
+ }
160
+ return buildQuotaStatus({
161
+ profileRef: input.profileRef,
162
+ basis: "provider",
163
+ source: "anthropic:ratelimit-headers",
164
+ now: input.now,
165
+ windows
166
+ });
167
+ }
168
+ var DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
169
+ var DEFAULT_TIMEOUT_MS = 4e3;
170
+ var OPENROUTER_KEY_SCHEMA = z.object({
171
+ data: z.object({
172
+ limit: z.number().nullable().optional(),
173
+ limit_remaining: z.number().nullable().optional()
174
+ }).passthrough()
175
+ }).passthrough();
176
+ async function getKeyJson(baseUrl, secret, ctx, timeoutMs) {
177
+ const controller = new AbortController();
178
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
179
+ const onAbort = () => controller.abort();
180
+ ctx.signal?.addEventListener("abort", onAbort);
181
+ try {
182
+ const res = await (ctx.fetchImpl ?? fetch)(`${baseUrl}/key`, {
183
+ method: "GET",
184
+ headers: { authorization: `Bearer ${secret}` },
185
+ signal: controller.signal
186
+ });
187
+ if (!res.ok) return void 0;
188
+ return await res.json();
189
+ } catch {
190
+ return void 0;
191
+ } finally {
192
+ clearTimeout(timer);
193
+ ctx.signal?.removeEventListener("abort", onAbort);
194
+ }
195
+ }
196
+ function createOpenRouterQuotaReader(opts) {
197
+ const baseUrl = opts?.baseUrl ?? DEFAULT_BASE_URL;
198
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
199
+ return defineQuotaReader({
200
+ id: "openrouter-key",
201
+ supports: (profile) => profile.endpoint === "openrouter" && profile.method === "api-key",
202
+ read: async (profile, ctx) => {
203
+ try {
204
+ if (!profile.credentialRef) return void 0;
205
+ if (!ctx.resolveCredential) return void 0;
206
+ const secret = await ctx.resolveCredential(profile.credentialRef).catch(() => void 0);
207
+ if (!secret) return void 0;
208
+ const body = await getKeyJson(baseUrl, secret, ctx, timeoutMs);
209
+ if (body === void 0) return void 0;
210
+ const parsed = OPENROUTER_KEY_SCHEMA.safeParse(body);
211
+ if (!parsed.success) return void 0;
212
+ const { limit, limit_remaining } = parsed.data.data;
213
+ const windows = [];
214
+ if (typeof limit === "number" && Number.isFinite(limit) && typeof limit_remaining === "number" && Number.isFinite(limit_remaining)) {
215
+ const remainingPct = remainingPctFromCounts(limit_remaining, limit);
216
+ if (remainingPct !== void 0) {
217
+ windows.push({
218
+ id: "key_limit",
219
+ remainingPct,
220
+ remaining: limit_remaining,
221
+ limit,
222
+ unit: "USD"
223
+ });
224
+ }
225
+ }
226
+ let credits;
227
+ if (typeof limit_remaining === "number" && Number.isFinite(limit_remaining)) {
228
+ credits = { balanceUsd: limit_remaining, currency: "USD" };
229
+ }
230
+ return buildQuotaStatus({
231
+ profileRef: profile.profileRef,
232
+ basis: "provider",
233
+ source: "openrouter:/key",
234
+ now: ctx.now,
235
+ windows,
236
+ ...credits !== void 0 ? { credits } : {}
237
+ });
238
+ } catch {
239
+ return void 0;
240
+ }
241
+ }
242
+ });
243
+ }
244
+
245
+ // src/index.ts
246
+ var SPEC_NAME = "quota/v1";
247
+ var SPEC_VERSION = "1.0.0-alpha";
248
+
249
+ export { QUOTA_BASES, QuotaReaderRegistry, SPEC_NAME, SPEC_VERSION, buildQuotaStatus, createOpenRouterQuotaReader, defineQuotaReader, quotaCreditsSchema, quotaFromAnthropicHeaders, quotaStatusSchema, quotaWindowSchema, remainingPctFromCounts, remainingPctFromUsed };
250
+ //# sourceMappingURL=index.mjs.map
251
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/build.ts","../src/registry.ts","../src/readers/anthropic.ts","../src/readers/openrouter.ts","../src/index.ts"],"names":["z"],"mappings":";;;;;;;AAQO,IAAM,WAAA,GAAc,CAAC,UAAA,EAAY,OAAA,EAAS,YAAY,WAAW;AAGxE,IAAM,YAAA,GAAe,CAAA,CAAE,MAAA,EAAO,CAAE,OAAO,CAAC,CAAA,KAAM,CAAC,MAAA,CAAO,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,EAAG;AAAA,EAC1E,OAAA,EAAS;AACX,CAAC,CAAA;AAEM,IAAM,iBAAA,GAAoB,EAAE,MAAA,CAAO;AAAA;AAAA,EAExC,EAAA,EAAI,CAAA,CAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA;AAAA;AAAA,EAEpB,YAAA,EAAc,EAAE,MAAA,EAAO,CAAE,IAAI,CAAC,CAAA,CAAE,IAAI,GAAG,CAAA;AAAA,EACvC,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC1B,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC3B,SAAA,EAAW,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC/B,IAAA,EAAM,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC1B,QAAA,EAAU,aAAa,QAAA;AACzB,CAAC;AAGM,IAAM,kBAAA,GAAqB,EAAE,MAAA,CAAO;AAAA,EACzC,UAAA,EAAY,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAChC,SAAA,EAAW,CA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;AAC9B,YAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,cACX,EAAA,EAAI,WAAA;AAAA,cACJ,YAAA;AAAA,cACA,SAAA,EAAW,eAAA;AAAA,cACX,KAAA;AAAA,cACA,IAAA,EAAM;AAAA,aACP,CAAA;AAAA,UACH;AAAA,QACF;AACA,QAAA,IAAI,OAAA;AACJ,QAAA,IAAI,OAAO,eAAA,KAAoB,QAAA,IAAY,MAAA,CAAO,QAAA,CAAS,eAAe,CAAA,EAAG;AAC3E,UAAA,OAAA,GAAU,EAAE,UAAA,EAAY,eAAA,EAAiB,QAAA,EAAU,KAAA,EAAM;AAAA,QAC3D;AAEA,QAAA,OAAO,gBAAA,CAAiB;AAAA,UACtB,YAAY,OAAA,CAAQ,UAAA;AAAA,UACpB,KAAA,EAAO,UAAA;AAAA,UACP,MAAA,EAAQ,iBAAA;AAAA,UACR,KAAK,GAAA,CAAI,GAAA;AAAA,UACT,OAAA;AAAA,UACA,GAAI,OAAA,KAAY,KAAA,CAAA,GAAY,EAAE,OAAA,KAAY;AAAC,SAC5C,CAAA;AAAA,MACH,CAAA,CAAA,MAAQ;AACN,QAAA,OAAO,MAAA;AAAA,MACT;AAAA,IACF;AAAA,GACD,CAAA;AACH;;;AC1GO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["import { z } from \"zod\"\n\n/**\n * Where a quota figure came from. `provider` is a documented provider\n * surface; `observed` is derived from this host's own traffic; `estimated`\n * is a local computation; `probe` is an undocumented surface reached through\n * a connector and MUST NOT be emitted by core readers.\n */\nexport const QUOTA_BASES = [\"provider\", \"probe\", \"observed\", \"estimated\"] as const\nexport type QuotaBasis = (typeof QUOTA_BASES)[number]\n\nconst isoTimestamp = z.string().refine((s) => !Number.isNaN(Date.parse(s)), {\n message: \"expected an ISO-8601 timestamp\",\n})\n\nexport const quotaWindowSchema = z.object({\n /** Open string: \"5h\", \"7d\", \"month\", \"minute\", \"day\", \"primary\", \"key_limit\", ... */\n id: z.string().min(1),\n /** 0-100. Required: a window that cannot state it is not emitted. */\n remainingPct: z.number().min(0).max(100),\n used: z.number().optional(),\n limit: z.number().optional(),\n remaining: z.number().optional(),\n unit: z.string().optional(),\n resetsAt: isoTimestamp.optional(),\n})\nexport type QuotaWindow = z.infer<typeof quotaWindowSchema>\n\nexport const quotaCreditsSchema = z.object({\n balanceUsd: z.number().optional(),\n unlimited: z.boolean().optional(),\n currency: z.string().min(1),\n})\nexport type QuotaCredits = z.infer<typeof quotaCreditsSchema>\n\nexport const quotaStatusSchema = z.object({\n profileRef: z.string().min(1),\n asOf: isoTimestamp,\n basis: z.enum(QUOTA_BASES),\n source: z.string().optional(),\n windows: z.array(quotaWindowSchema),\n credits: quotaCreditsSchema.optional(),\n})\nexport type QuotaStatus = z.infer<typeof quotaStatusSchema>\n\n/** The minimal auth-profile projection a reader needs. */\nexport interface QuotaProfile {\n profileRef: string\n endpoint: string\n method: \"oauth-bearer\" | \"api-key\"\n credentialRef?: string\n}\n\nexport interface QuotaReadContext {\n signal?: AbortSignal\n /** Resolve a profile's opaque credentialRef to a bearer secret. */\n resolveCredential?(ref: string): Promise<string | undefined>\n fetchImpl?: typeof fetch\n now?: () => Date\n}\n\n/**\n * Reads quota for a profile. MUST NOT throw: any failure or unknown value\n * resolves to `undefined`. Never fabricates a figure.\n */\nexport interface QuotaReader {\n readonly id: string\n supports(profile: QuotaProfile): boolean\n read(profile: QuotaProfile, ctx: QuotaReadContext): Promise<QuotaStatus | undefined>\n}\n","import type { QuotaBasis, QuotaCredits, QuotaStatus, QuotaWindow } from \"./types.js\"\nimport { quotaWindowSchema } from \"./types.js\"\n\n/** remainingPct from a used percentage, or undefined when it is not a finite 0-100 number. */\nexport function remainingPctFromUsed(usedPct: number | null | undefined): number | undefined {\n if (usedPct === null || usedPct === undefined || !Number.isFinite(usedPct)) return undefined\n if (usedPct < 0 || usedPct > 100) return undefined\n return 100 - usedPct\n}\n\n/** remainingPct from remaining/limit counts, or undefined when limit is not a positive finite number. */\nexport function remainingPctFromCounts(\n remaining: number | null | undefined,\n limit: number | null | undefined,\n): number | undefined {\n if (remaining === null || remaining === undefined || limit === null || limit === undefined) {\n return undefined\n }\n if (!Number.isFinite(remaining) || !Number.isFinite(limit) || limit <= 0) return undefined\n if (remaining < 0 || remaining > limit) return undefined\n return (remaining / limit) * 100\n}\n\nexport interface BuildQuotaStatusInput {\n profileRef: string\n basis: QuotaBasis\n source?: string\n now?: () => Date\n /** Candidate windows; any that fail validation are dropped, never repaired. */\n windows?: readonly unknown[]\n credits?: QuotaCredits\n}\n\n/**\n * Assemble a QuotaStatus. Invalid windows are omitted. Returns `undefined`\n * when there is nothing to report (no valid window and no credits).\n */\nexport function buildQuotaStatus(input: BuildQuotaStatusInput): QuotaStatus | undefined {\n const windows: QuotaWindow[] = []\n for (const candidate of input.windows ?? []) {\n const parsed = quotaWindowSchema.safeParse(candidate)\n if (parsed.success) windows.push(parsed.data)\n }\n if (windows.length === 0 && input.credits === undefined) return undefined\n return {\n profileRef: input.profileRef,\n asOf: (input.now ?? (() => new Date()))().toISOString(),\n basis: input.basis,\n ...(input.source !== undefined ? { source: input.source } : {}),\n windows,\n ...(input.credits !== undefined ? { credits: input.credits } : {}),\n }\n}\n","import type { QuotaProfile, QuotaReadContext, QuotaReader, QuotaStatus } from \"./types.js\"\n\n/** Identity helper that fixes the QuotaReader contract at definition time (AIP-43 handle). */\nexport function defineQuotaReader(reader: QuotaReader): QuotaReader {\n return reader\n}\n\nexport class QuotaReaderRegistry {\n private readonly readers = new Map<string, QuotaReader>()\n\n register(reader: QuotaReader): this {\n if (this.readers.has(reader.id)) {\n throw new Error(`quota reader already registered: ${reader.id}`)\n }\n this.readers.set(reader.id, reader)\n return this\n }\n\n list(): QuotaReader[] {\n return [...this.readers.values()]\n }\n\n /** First registered reader that supports the profile, in registration order. */\n find(profile: QuotaProfile): QuotaReader | undefined {\n for (const reader of this.readers.values()) {\n if (safeSupports(reader, profile)) return reader\n }\n return undefined\n }\n\n /** Read through the first supporting reader. Never throws; unknown -> undefined. */\n async read(profile: QuotaProfile, ctx: QuotaReadContext = {}): Promise<QuotaStatus | undefined> {\n const reader = this.find(profile)\n if (!reader) return undefined\n try {\n return await reader.read(profile, ctx)\n } catch {\n return undefined\n }\n }\n}\n\nfunction safeSupports(reader: QuotaReader, profile: QuotaProfile): boolean {\n try {\n return reader.supports(profile)\n } catch {\n return false\n }\n}\n","import { buildQuotaStatus, remainingPctFromCounts } from \"../build.js\"\nimport type { QuotaStatus } from \"../types.js\"\n\nexport interface AnthropicHeadersInput {\n profileRef: string\n headers: Headers | Record<string, string | undefined>\n now?: () => Date\n}\n\ninterface Dimension {\n id: string\n header: string\n unit: string\n}\n\nconst DIMENSIONS: readonly Dimension[] = [\n { id: \"requests-1m\", header: \"requests\", unit: \"requests\" },\n { id: \"tokens-1m\", header: \"tokens\", unit: \"tokens\" },\n { id: \"input-tokens-1m\", header: \"input-tokens\", unit: \"tokens\" },\n { id: \"output-tokens-1m\", header: \"output-tokens\", unit: \"tokens\" },\n]\n\n/** Read a header case-insensitively from a `Headers` or a plain record. */\nfunction headerGet(\n headers: Headers | Record<string, string | undefined>,\n name: string,\n): string | undefined {\n if (headers instanceof Headers) {\n return headers.get(name) ?? undefined\n }\n const lower = name.toLowerCase()\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === lower) return value\n }\n return undefined\n}\n\n/** Parse a numeric rate-limit header; empty/garbage → undefined. */\nfunction parseCount(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined\n const trimmed = raw.trim()\n if (!trimmed) return undefined\n const n = Number(trimmed)\n return Number.isFinite(n) ? n : undefined\n}\n\n/** Normalize an RFC 3339 reset header to an ISO string; unparseable → undefined. */\nfunction parseReset(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined\n const trimmed = raw.trim()\n if (!trimmed) return undefined\n const date = new Date(trimmed)\n return Number.isNaN(date.getTime()) ? undefined : date.toISOString()\n}\n\n/**\n * PURE: build a QuotaStatus from Anthropic's DOCUMENTED rate-limit headers\n * `anthropic-ratelimit-{requests,tokens,input-tokens,output-tokens}-{limit,remaining,reset}`.\n * The undocumented `anthropic-ratelimit-unified-*` family is never read.\n * A dimension with a missing/non-numeric limit or remaining is skipped.\n */\nexport function quotaFromAnthropicHeaders(input: AnthropicHeadersInput): QuotaStatus | undefined {\n const windows: Record<string, unknown>[] = []\n for (const dimension of DIMENSIONS) {\n const prefix = `anthropic-ratelimit-${dimension.header}`\n const limit = parseCount(headerGet(input.headers, `${prefix}-limit`))\n const remaining = parseCount(headerGet(input.headers, `${prefix}-remaining`))\n if (limit === undefined || remaining === undefined) continue\n const remainingPct = remainingPctFromCounts(remaining, limit)\n if (remainingPct === undefined) continue\n const resetsAt = parseReset(headerGet(input.headers, `${prefix}-reset`))\n windows.push({\n id: dimension.id,\n remainingPct,\n limit,\n remaining,\n unit: dimension.unit,\n ...(resetsAt !== undefined ? { resetsAt } : {}),\n })\n }\n return buildQuotaStatus({\n profileRef: input.profileRef,\n basis: \"provider\",\n source: \"anthropic:ratelimit-headers\",\n now: input.now,\n windows,\n })\n}\n","import { z } from \"zod\"\nimport { buildQuotaStatus, remainingPctFromCounts } from \"../build.js\"\nimport { defineQuotaReader } from \"../registry.js\"\nimport type { QuotaCredits, QuotaProfile, QuotaReadContext, QuotaReader, QuotaStatus, QuotaWindow } from \"../types.js\"\n\nconst DEFAULT_BASE_URL = \"https://openrouter.ai/api/v1\"\nconst DEFAULT_TIMEOUT_MS = 4000\n\nconst OPENROUTER_KEY_SCHEMA = z\n .object({\n data: z\n .object({\n limit: z.number().nullable().optional(),\n limit_remaining: z.number().nullable().optional(),\n })\n .passthrough(),\n })\n .passthrough()\n\nexport interface OpenRouterQuotaReaderOptions {\n baseUrl?: string\n timeoutMs?: number\n}\n\n/** GET `${baseUrl}/key` and parse the body, never throwing. */\nasync function getKeyJson(\n baseUrl: string,\n secret: string,\n ctx: QuotaReadContext,\n timeoutMs: number,\n): Promise<unknown | undefined> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), timeoutMs)\n const onAbort = () => controller.abort()\n ctx.signal?.addEventListener(\"abort\", onAbort)\n try {\n const res = await (ctx.fetchImpl ?? fetch)(`${baseUrl}/key`, {\n method: \"GET\",\n headers: { authorization: `Bearer ${secret}` },\n signal: controller.signal,\n })\n if (!res.ok) return undefined\n return await res.json()\n } catch {\n return undefined\n } finally {\n clearTimeout(timer)\n ctx.signal?.removeEventListener(\"abort\", onAbort)\n }\n}\n\n/**\n * OpenRouter quota reader: `GET /key` exposes the key's USD cap and remaining\n * headroom. The whole read is wrapped so it never throws; an uncapped key\n * (`limit_remaining` null/absent) yields no window and no credits.\n */\nexport function createOpenRouterQuotaReader(opts?: OpenRouterQuotaReaderOptions): QuotaReader {\n const baseUrl = opts?.baseUrl ?? DEFAULT_BASE_URL\n const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS\n\n return defineQuotaReader({\n id: \"openrouter-key\",\n supports: (profile: QuotaProfile): boolean =>\n profile.endpoint === \"openrouter\" && profile.method === \"api-key\",\n read: async (\n profile: QuotaProfile,\n ctx: QuotaReadContext,\n ): Promise<QuotaStatus | undefined> => {\n try {\n if (!profile.credentialRef) return undefined\n if (!ctx.resolveCredential) return undefined\n const secret = await ctx.resolveCredential(profile.credentialRef).catch(() => undefined)\n if (!secret) return undefined\n\n const body = await getKeyJson(baseUrl, secret, ctx, timeoutMs)\n if (body === undefined) return undefined\n const parsed = OPENROUTER_KEY_SCHEMA.safeParse(body)\n if (!parsed.success) return undefined\n\n const { limit, limit_remaining } = parsed.data.data\n const windows: QuotaWindow[] = []\n if (\n typeof limit === \"number\" &&\n Number.isFinite(limit) &&\n typeof limit_remaining === \"number\" &&\n Number.isFinite(limit_remaining)\n ) {\n const remainingPct = remainingPctFromCounts(limit_remaining, limit)\n if (remainingPct !== undefined) {\n windows.push({\n id: \"key_limit\",\n remainingPct,\n remaining: limit_remaining,\n limit,\n unit: \"USD\",\n })\n }\n }\n let credits: QuotaCredits | undefined\n if (typeof limit_remaining === \"number\" && Number.isFinite(limit_remaining)) {\n credits = { balanceUsd: limit_remaining, currency: \"USD\" }\n }\n\n return buildQuotaStatus({\n profileRef: profile.profileRef,\n basis: \"provider\",\n source: \"openrouter:/key\",\n now: ctx.now,\n windows,\n ...(credits !== undefined ? { credits } : {}),\n })\n } catch {\n return undefined\n }\n },\n })\n}\n","/**\n * @agentproto/model-intel — model intelligence primitives.\n *\n * Unified, provider-neutral quota status (AIP-67): one QuotaStatus shape with a\n * mandatory `basis`, a never-throw QuotaReader contract, and a reader registry.\n * Unknown is omitted, never fabricated.\n *\n * @see https://agentproto.sh/docs/aip-67\n */\n\nexport const SPEC_NAME = \"quota/v1\" as const\nexport const SPEC_VERSION = \"1.0.0-alpha\" as const\n\nexport {\n QUOTA_BASES,\n quotaCreditsSchema,\n quotaStatusSchema,\n quotaWindowSchema,\n} from \"./types.js\"\nexport type {\n QuotaBasis,\n QuotaCredits,\n QuotaProfile,\n QuotaReadContext,\n QuotaReader,\n QuotaStatus,\n QuotaWindow,\n} from \"./types.js\"\nexport {\n buildQuotaStatus,\n remainingPctFromCounts,\n remainingPctFromUsed,\n} from \"./build.js\"\nexport type { BuildQuotaStatusInput } from \"./build.js\"\nexport { QuotaReaderRegistry, defineQuotaReader } from \"./registry.js\"\nexport { quotaFromAnthropicHeaders } from \"./readers/anthropic.js\"\nexport { createOpenRouterQuotaReader } from \"./readers/openrouter.js\"\n"]}
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@agentproto/model-intel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "@agentproto/model-intel — model intelligence primitives. Unified, provider-neutral quota status (AIP-67): a QuotaStatus shape with a mandatory basis, a never-throw QuotaReader contract, and a reader registry. Unknown is omitted, never fabricated.",
5
+ "keywords": [
6
+ "agentproto",
7
+ "aip-67",
8
+ "quota",
9
+ "model-intel",
10
+ "llm",
11
+ "open-standard",
12
+ "agentic"
13
+ ],
14
+ "homepage": "https://agentproto.sh/docs/aip-67",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/agentproto/ts",
18
+ "directory": "packages/model-intel"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/agentproto/ts/issues"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "type": "module",
25
+ "main": "dist/index.mjs",
26
+ "module": "dist/index.mjs",
27
+ "types": "dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.mjs",
32
+ "default": "./dist/index.mjs"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "README.md",
39
+ "LICENSE"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "zod": "^4.6.7"
46
+ },
47
+ "devDependencies": {
48
+ "@types/node": "^25.9.9",
49
+ "tsup": "^8.5.1",
50
+ "typescript": "^5.9.3",
51
+ "vitest": "^3.2.7",
52
+ "@agentproto/tooling": "0.1.0"
53
+ },
54
+ "scripts": {
55
+ "dev": "tsup --watch",
56
+ "build": "tsup",
57
+ "clean": "rm -rf dist",
58
+ "check-types": "tsc --noEmit",
59
+ "test": "vitest run",
60
+ "test:watch": "vitest"
61
+ }
6
62
  }