@buildanagent/gateway 0.0.0-stage → 0.1.0-alpha.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 +52 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +299 -2
- package/dist/adapters/anthropic/adapter.d.ts +25 -0
- package/dist/adapters/anthropic/adapter.js +183 -0
- package/dist/adapters/anthropic/adapter.js.map +1 -0
- package/dist/adapters/anthropic/failure.d.ts +20 -0
- package/dist/adapters/anthropic/failure.js +46 -0
- package/dist/adapters/anthropic/failure.js.map +1 -0
- package/dist/adapters/anthropic/index.d.ts +3 -0
- package/dist/adapters/anthropic/index.js +3 -0
- package/dist/adapters/anthropic/index.js.map +1 -0
- package/dist/adapters/anthropic/request.d.ts +53 -0
- package/dist/adapters/anthropic/request.js +250 -0
- package/dist/adapters/anthropic/request.js.map +1 -0
- package/dist/adapters/anthropic/response.d.ts +31 -0
- package/dist/adapters/anthropic/response.js +212 -0
- package/dist/adapters/anthropic/response.js.map +1 -0
- package/dist/adapters/anthropic/usage.d.ts +26 -0
- package/dist/adapters/anthropic/usage.js +39 -0
- package/dist/adapters/anthropic/usage.js.map +1 -0
- package/dist/adapters/openai-chat/adapter.d.ts +18 -0
- package/dist/adapters/openai-chat/adapter.js +86 -0
- package/dist/adapters/openai-chat/adapter.js.map +1 -0
- package/dist/adapters/openai-chat/compat.d.ts +58 -0
- package/dist/adapters/openai-chat/compat.js +19 -0
- package/dist/adapters/openai-chat/compat.js.map +1 -0
- package/dist/adapters/openai-chat/failure.d.ts +25 -0
- package/dist/adapters/openai-chat/failure.js +33 -0
- package/dist/adapters/openai-chat/failure.js.map +1 -0
- package/dist/adapters/openai-chat/index.d.ts +4 -0
- package/dist/adapters/openai-chat/index.js +3 -0
- package/dist/adapters/openai-chat/index.js.map +1 -0
- package/dist/adapters/openai-chat/request.d.ts +47 -0
- package/dist/adapters/openai-chat/request.js +227 -0
- package/dist/adapters/openai-chat/request.js.map +1 -0
- package/dist/adapters/openai-chat/response.d.ts +22 -0
- package/dist/adapters/openai-chat/response.js +203 -0
- package/dist/adapters/openai-chat/response.js.map +1 -0
- package/dist/adapters/openai-chat/usage.d.ts +19 -0
- package/dist/adapters/openai-chat/usage.js +22 -0
- package/dist/adapters/openai-chat/usage.js.map +1 -0
- package/dist/adapters/strict-schema.d.ts +67 -0
- package/dist/adapters/strict-schema.js +269 -0
- package/dist/adapters/strict-schema.js.map +1 -0
- package/dist/adapters/wire.d.ts +77 -0
- package/dist/adapters/wire.js +137 -0
- package/dist/adapters/wire.js.map +1 -0
- package/dist/catalog.d.ts +65 -0
- package/dist/catalog.js +145 -0
- package/dist/catalog.js.map +1 -0
- package/dist/catalog.json +120 -0
- package/dist/classify.d.ts +25 -0
- package/dist/classify.js +37 -0
- package/dist/classify.js.map +1 -0
- package/dist/complete.d.ts +9 -0
- package/dist/complete.js +13 -0
- package/dist/complete.js.map +1 -0
- package/dist/cost.d.ts +42 -0
- package/dist/cost.js +122 -0
- package/dist/cost.js.map +1 -0
- package/dist/create-model.d.ts +7 -0
- package/dist/create-model.js +81 -0
- package/dist/create-model.js.map +1 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +17 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +11 -0
- package/dist/middleware.js +22 -0
- package/dist/middleware.js.map +1 -0
- package/dist/names.d.ts +72 -0
- package/dist/names.js +175 -0
- package/dist/names.js.map +1 -0
- package/dist/provider-config.d.ts +15 -0
- package/dist/provider-config.js +23 -0
- package/dist/provider-config.js.map +1 -0
- package/dist/request-dump.d.ts +28 -0
- package/dist/request-dump.js +52 -0
- package/dist/request-dump.js.map +1 -0
- package/dist/request-policy.d.ts +18 -0
- package/dist/request-policy.js +27 -0
- package/dist/request-policy.js.map +1 -0
- package/dist/retry.d.ts +30 -0
- package/dist/retry.js +191 -0
- package/dist/retry.js.map +1 -0
- package/dist/runtime-types.d.ts +112 -0
- package/dist/runtime-types.js +2 -0
- package/dist/runtime-types.js.map +1 -0
- package/dist/spec.d.ts +67 -0
- package/dist/spec.js +2 -0
- package/dist/spec.js.map +1 -0
- package/dist/sse.d.ts +15 -0
- package/dist/sse.js +73 -0
- package/dist/sse.js.map +1 -0
- package/dist/stream-contract.d.ts +23 -0
- package/dist/stream-contract.js +101 -0
- package/dist/stream-contract.js.map +1 -0
- package/dist/testing/guards.d.ts +16 -0
- package/dist/testing/guards.js +48 -0
- package/dist/testing/guards.js.map +1 -0
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.js +13 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/mock-transport.d.ts +49 -0
- package/dist/testing/mock-transport.js +101 -0
- package/dist/testing/mock-transport.js.map +1 -0
- package/dist/testing/random.d.ts +3 -0
- package/dist/testing/random.js +13 -0
- package/dist/testing/random.js.map +1 -0
- package/dist/testing/setup.d.ts +1 -0
- package/dist/testing/setup.js +12 -0
- package/dist/testing/setup.js.map +1 -0
- package/dist/transform-messages.d.ts +32 -0
- package/dist/transform-messages.js +291 -0
- package/dist/transform-messages.js.map +1 -0
- package/dist/types.d.ts +130 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/usage.d.ts +8 -0
- package/dist/usage.js +20 -0
- package/dist/usage.js.map +1 -0
- package/package.json +50 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"strict-schema.js","sourceRoot":"","sources":["../../src/adapters/strict-schema.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAyCH,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACnC,SAAS;IACT,SAAS;IACT,kBAAkB;IAClB,kBAAkB;IAClB,YAAY;IACZ,WAAW;IACX,WAAW;IACX,UAAU;IACV,aAAa;IACb,eAAe;IACf,eAAe;IACf,mBAAmB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can see: the `null` that a nullable dialect adds to an optional property. Each adapter passes its own\n * `StrictDialect`; the rules both first providers share are these:\n *\n * - every object needs `additionalProperties: false`, and an object with any other `additionalProperties` cannot be\n * strict. An object that declares neither `properties` nor `additionalProperties` accepts any keys, and adding\n * `additionalProperties: false` would let the model send only `{}`, so it cannot be strict either;\n * - `not` is unsupported, and `oneOf` must be written as `anyOf`;\n * - numeric constraints, string length constraints and array constraints beyond `minItems` of 0 or 1 are dropped,\n * unless the dialect keeps them. Anthropic rejects them (Structured outputs, \"JSON Schema limitations\",\n * https://platform.claude.com/docs/en/build-with-claude/structured-outputs, as of November 2026).\n *\n * OpenAI's strict mode requires every property (Structured model outputs, \"Supported schemas\",\n * https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas, as of November 2026). It\n * accepts the numeric constraints and `minItems`/`maxItems`, rejects `allOf`, `if`/`then`/`else` and the\n * `dependent*` keywords, and limits a schema's size, for example to 5,000 properties and 10 levels of nesting. Its\n * dialect therefore writes an optional property as a required one that also accepts `null`. The removed constraints\n * are not lost: the SDK validates every call against the original schema, after `stripAddedNulls()`.\n */\n\ntype Json = Record<string, unknown>;\n\n/** How one provider's strict mode differs from the shared rules above. */\nexport interface StrictDialect {\n /** `\"keep\"` leaves optional properties optional; `\"nullable\"` requires them and lets them be `null`. */\n readonly optional: \"keep\" | \"nullable\";\n /** The string formats the provider accepts; any other `format` is dropped. */\n readonly formats: ReadonlySet<string>;\n /** True when the provider accepts only an object schema, with `type: \"object\"`, at the root. */\n readonly objectRoot: boolean;\n /** Keywords the provider enforces, which lowering keeps although the shared rules drop them. */\n readonly keeps?: ReadonlySet<string>;\n /** Keywords the provider rejects; a schema that uses one is sent without strict. */\n readonly rejects?: ReadonlySet<string>;\n /** Limits on one schema; a schema over any of them is sent without strict. */\n readonly limits?: StrictLimits;\n}\n\n/** The size limits of one strict schema. */\nexport interface StrictLimits {\n readonly properties: number;\n /** Levels of object nesting. */\n readonly depth: number;\n readonly enumValues: number;\n /** Characters in all property names, definition names, and string enum and `const` values. */\n readonly stringLength: number;\n /** The most characters one string enum may hold once it has more than `values` values. */\n readonly largeEnum: { readonly values: number; readonly length: number };\n}\n\n/** A schema lowered to strict form, with the counts the request-wide complexity limits are checked against. */\nexport interface StrictSchema {\n readonly schema: Json;\n /** Properties left out of `required`, across the whole schema. Always 0 for a nullable dialect. */\n readonly optional: number;\n /** Subschemas that use `anyOf` or a type array, the null unions a nullable dialect adds included. */\n readonly unions: number;\n}\n\nconst UNSUPPORTED_KEYWORDS = new Set([\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n \"minLength\",\n \"maxLength\",\n \"maxItems\",\n \"uniqueItems\",\n \"minProperties\",\n \"maxProperties\",\n \"patternProperties\",\n \"propertyNames\",\n]);\n// Lookaround, named groups and backreferences fall outside the documented regex subset.\nconst UNSUPPORTED_PATTERN = /\\(\\?|\\\\[1-9k]/;\nconst SCHEMA_LISTS = [\"anyOf\", \"allOf\", \"oneOf\", \"prefixItems\"];\nconst SCHEMA_MAPS = [\"properties\", \"$defs\", \"definitions\"];\n\ninterface Walk {\n readonly dialect: StrictDialect;\n optional: number;\n unions: number;\n /** Properties, object nesting (deepest so far and current), enum values and strings, for `StrictDialect.limits`. */\n properties: number;\n depth: number;\n maxDepth: number;\n enumValues: number;\n stringLength: number;\n /** The character count of the longest string enum with more than `limits.largeEnum.values` values. */\n largeEnumLength: number;\n /** Set when the schema uses a feature strict mode rejects; the tool is then sent without `strict`. */\n failure?: string;\n}\n\nfunction isObject(value: unknown): value is Json {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** True for a key strict mode rejects, so lowering removes it. */\nfunction dropsKey(key: string, value: unknown, dialect: StrictDialect): boolean {\n if (dialect.keeps?.has(key)) return false;\n if (UNSUPPORTED_KEYWORDS.has(key)) return true;\n if (key === \"minItems\") return typeof value !== \"number\" || value > 1;\n if (key === \"format\") return typeof value !== \"string\" || !dialect.formats.has(value);\n return key === \"pattern\" && (typeof value !== \"string\" || UNSUPPORTED_PATTERN.test(value));\n}\n\nfunction lowerChildren(key: string, value: unknown, walk: Walk): unknown {\n if (SCHEMA_LISTS.includes(key) && Array.isArray(value)) return value.map((item) => lowerNode(item, walk));\n if (SCHEMA_MAPS.includes(key) && isObject(value)) {\n return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, lowerNode(item, walk)]));\n }\n if (key === \"items\" && isObject(value)) return lowerNode(value, walk);\n return value;\n}\n\n/**\n * True when the schema already accepts `null`. A schema that constrains nothing, such as `{}`, accepts it; a `$ref`,\n * an `allOf`, or an object or array schema written without `type` counts as not accepting it, so a nullable dialect\n * gives it an explicit `null` branch.\n */\nfunction allowsNull(schema: unknown): boolean {\n if (!isObject(schema)) return true;\n if (schema.type === \"null\" || (Array.isArray(schema.type) && schema.type.includes(\"null\"))) return true;\n if (Array.isArray(schema.enum)) return schema.enum.includes(null);\n if (\"const\" in schema) return schema.const === null;\n const branches = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : undefined;\n if (branches) return branches.some(allowsNull);\n return schema.type === undefined && ![\"$ref\", \"allOf\", \"properties\", \"items\"].some((key) => key in schema);\n}\n\n/** The schema made to accept `null` as well, in the simplest form strict mode reads. */\nfunction withNull(schema: Json, walk: Walk): Json {\n if (allowsNull(schema)) return schema;\n walk.unions += 1;\n if (typeof schema.type === \"string\" && !Array.isArray(schema.enum) && !(\"const\" in schema)) {\n return { ...schema, type: [schema.type, \"null\"] };\n }\n if (Array.isArray(schema.anyOf)) return { ...schema, anyOf: [...schema.anyOf, { type: \"null\" }] };\n return { anyOf: [schema, { type: \"null\" }] };\n}\n\n/** Marks every property required, and lets each one that was optional be `null`. */\nfunction requireAll(lowered: Json, original: Json, walk: Walk): void {\n if (!isObject(lowered.properties)) return;\n const required = new Set(Array.isArray(original.required) ? original.required : []);\n const properties = lowered.properties;\n for (const [name, property] of Object.entries(properties)) {\n if (!required.has(name) && isObject(property)) properties[name] = withNull(property, walk);\n }\n lowered.required = Object.keys(properties);\n}\n\nfunction countOptional(node: Json, walk: Walk): void {\n const properties = isObject(node.properties) ? Object.keys(node.properties) : [];\n const required = new Set(Array.isArray(node.required) ? node.required : []);\n walk.optional += properties.filter((name) => !required.has(name)).length;\n}\n\n/** Why strict mode cannot express this node itself, or `undefined` when it can. */\nfunction strictFailure(node: Json, isObjectSchema: boolean, dialect: StrictDialect): string | undefined {\n if (\"not\" in node) return \"uses not\";\n const rejected = Object.keys(node).find((key) => dialect.rejects?.has(key));\n if (rejected !== undefined) return `uses ${rejected}`;\n if (!isObjectSchema) return undefined;\n if (\"additionalProperties\" in node) {\n return node.additionalProperties === false ? undefined : \"allows additional properties\";\n }\n return isObject(node.properties) ? undefined : \"declares no properties\";\n}\n\n// A nullable object, `type: [\"object\", \"null\"]`, is an object too and needs the same treatment.\nfunction isObjectNode(node: Json): boolean {\n return (\n node.type === \"object\" || (Array.isArray(node.type) && node.type.includes(\"object\")) || isObject(node.properties)\n );\n}\n\n/** Counts the node toward `StrictDialect.limits`; an object nests one level deeper until its children are lowered. */\nfunction measure(node: Json, isObjectSchema: boolean, walk: Walk): void {\n if (isObjectSchema) walk.depth += 1;\n walk.maxDepth = Math.max(walk.maxDepth, walk.depth);\n const names = SCHEMA_MAPS.flatMap((key) => (isObject(node[key]) ? Object.keys(node[key]) : []));\n if (isObject(node.properties)) walk.properties += Object.keys(node.properties).length;\n const strings = [...(Array.isArray(node.enum) ? node.enum : []), node.const].filter((v) => typeof v === \"string\");\n walk.stringLength += [...names, ...strings].reduce((sum, text) => sum + text.length, 0);\n if (!Array.isArray(node.enum)) return;\n walk.enumValues += node.enum.length;\n const enumStrings = node.enum.filter((value) => typeof value === \"string\");\n const large = walk.dialect.limits?.largeEnum.values ?? Number.POSITIVE_INFINITY;\n if (enumStrings.length > large) {\n const length = enumStrings.reduce((sum, text) => sum + text.length, 0);\n walk.largeEnumLength = Math.max(walk.largeEnumLength, length);\n }\n}\n\nfunction overLimits(walk: Walk, limits: StrictLimits | undefined): boolean {\n if (limits === undefined) return false;\n return (\n walk.properties > limits.properties ||\n walk.maxDepth > limits.depth ||\n walk.enumValues > limits.enumValues ||\n walk.stringLength > limits.stringLength ||\n walk.largeEnumLength > limits.largeEnum.length\n );\n}\n\nfunction lowerNode(node: unknown, walk: Walk): unknown {\n if (!isObject(node) || walk.failure !== undefined) return node;\n const isObjectSchema = isObjectNode(node);\n const failure = strictFailure(node, isObjectSchema, walk.dialect);\n if (failure !== undefined) {\n walk.failure = failure;\n return node;\n }\n measure(node, isObjectSchema, walk);\n const lowered: Json = {};\n for (const [key, value] of Object.entries(node)) {\n if (dropsKey(key, value, walk.dialect)) continue;\n lowered[key === \"oneOf\" ? \"anyOf\" : key] = lowerChildren(key, value, walk);\n }\n if (isObjectSchema) walk.depth -= 1;\n if (isObjectSchema) {\n lowered.additionalProperties = false;\n if (walk.dialect.optional === \"nullable\") requireAll(lowered, node, walk);\n else countOptional(node, walk);\n }\n if (Array.isArray(node.type) || Array.isArray(lowered.anyOf)) walk.unions += 1;\n return lowered;\n}\n\n/** The schema in strict form with its counts, or `undefined` when strict mode cannot express it. */\nexport function lowerToStrict(schema: Json, dialect: StrictDialect): StrictSchema | undefined {\n if (dialect.objectRoot && schema.type !== \"object\") return undefined;\n const walk: Walk = {\n dialect,\n optional: 0,\n unions: 0,\n properties: 0,\n depth: 0,\n maxDepth: 0,\n enumValues: 0,\n stringLength: 0,\n largeEnumLength: 0,\n };\n const lowered = lowerNode(schema, walk) as Json;\n if (walk.failure !== undefined || overLimits(walk, dialect.limits)) return undefined;\n return { schema: lowered, optional: walk.optional, unions: walk.unions };\n}\n\n// Stripping the added nulls ------------------------------------------------------------------------------------------\n\n/** Follows a local `#/$defs/…` or `#/definitions/…` reference; any other schema comes back as it is. */\nfunction resolve(schema: unknown, root: Json): unknown {\n if (!isObject(schema) || typeof schema.$ref !== \"string\") return schema;\n const match = /^#\\/(\\$defs|definitions)\\/([^/]+)$/.exec(schema.$ref);\n if (match === null) return schema;\n const defs = root[match[1] ?? \"\"];\n return isObject(defs) ? defs[decodeURIComponent(match[2] ?? \"\")] : schema;\n}\n\n/**\n * The first `anyOf`/`oneOf` branch that can describe the value: for an array, one with `items`; for an object, one\n * whose `properties` name every key the value has. The branch the model chose is the one its value fits.\n */\nfunction matchingBranch(value: unknown, schema: Json, root: Json): unknown {\n const branches = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : [];\n return branches.find((branch) => {\n const resolved = resolve(branch, root);\n if (!isObject(resolved)) return false;\n if (Array.isArray(value)) return isObject(resolved.items);\n const properties = resolved.properties;\n return isObject(value) && isObject(properties) && Object.keys(value).every((key) => key in properties);\n });\n}\n\nfunction strip(value: unknown, node: unknown, root: Json): unknown {\n const schema = resolve(node, root);\n if (!isObject(schema)) return value;\n if (!isObject(schema.properties) && !isObject(schema.items) && value !== null && typeof value === \"object\") {\n const branch = matchingBranch(value, schema, root);\n return branch === undefined ? value : strip(value, branch, root);\n }\n if (Array.isArray(value))\n return isObject(schema.items) ? value.map((item) => strip(item, schema.items, root)) : value;\n return isObject(value) && isObject(schema.properties) ? stripObject(value, schema.properties, schema, root) : value;\n}\n\nfunction stripObject(value: Json, properties: Json, schema: Json, root: Json): Json {\n const required = new Set(Array.isArray(schema.required) ? schema.required : []);\n const out: Json = {};\n for (const [name, item] of Object.entries(value)) {\n const property = properties[name];\n // A null the original schema does not allow here is one lowering added, and leaving the field out is what the\n // model meant by it.\n if (item === null && property !== undefined && !required.has(name) && !allowsNull(resolve(property, root)))\n continue;\n out[name] = property === undefined ? item : strip(item, property, root);\n }\n return out;\n}\n\n/**\n * Removes from a tool call's input each `null` that nullable lowering added: a `null` in a property that the original\n * schema leaves optional and does not let be `null`. It follows `properties`, `items`, local `$ref`s and, for an\n * object or array inside an `anyOf` or `oneOf`, the first branch whose properties or items fit the value.\n */\nexport function stripAddedNulls(input: unknown, original: Json): unknown {\n return strip(input, original, original);\n}\n"]}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every wire adapter shares: sending one HTTP request through the caller's transport, reading a server-sent
|
|
3
|
+
* event stream to its terminal, and turning a failed request, a broken stream or an abort into an `error` terminal.
|
|
4
|
+
* A failed model call never throws; only a guard's error or a `GatewayError` does.
|
|
5
|
+
*/
|
|
6
|
+
import { type ErrorKind } from "../classify.js";
|
|
7
|
+
import type { Transport } from "../runtime-types.js";
|
|
8
|
+
import type { ModelEvent, StreamOptions } from "../spec.js";
|
|
9
|
+
import { type ServerSentEvent } from "../sse.js";
|
|
10
|
+
import type { AssistantMessage, ContentBlock, ModelErrorCode, ModelRef, Usage } from "../types.js";
|
|
11
|
+
/** A JSON object as the adapters read it off the wire. */
|
|
12
|
+
export type Json = Record<string, unknown>;
|
|
13
|
+
/** The content and usage an attempt reached before it ended. */
|
|
14
|
+
export interface PartialReply {
|
|
15
|
+
readonly content?: ContentBlock[];
|
|
16
|
+
readonly usage?: Usage;
|
|
17
|
+
}
|
|
18
|
+
/** What one failure says about itself. */
|
|
19
|
+
export interface WireFailure {
|
|
20
|
+
readonly status?: number;
|
|
21
|
+
/** The provider's error type, such as `"invalid_request_error"`. */
|
|
22
|
+
readonly type?: string;
|
|
23
|
+
/** The provider's finer error code, when the error has one, such as `"insufficient_quota"`. */
|
|
24
|
+
readonly errorCode?: string;
|
|
25
|
+
readonly message: string;
|
|
26
|
+
/** Sets the kind outright, for a failure that no status describes, such as a refusal inside a 200 stream. */
|
|
27
|
+
readonly kind?: ErrorKind;
|
|
28
|
+
}
|
|
29
|
+
/** True for a JSON object, not an array or `null`. */
|
|
30
|
+
export declare function isObject(value: unknown): value is Json;
|
|
31
|
+
/** The value when it is a string, or `""`. */
|
|
32
|
+
export declare function str(value: unknown): string;
|
|
33
|
+
/** A token count: a finite positive number, or 0. */
|
|
34
|
+
export declare function count(value: unknown): number;
|
|
35
|
+
/** A tool call's input: the parsed JSON, or the partial JSON text when the output limit cut it off. */
|
|
36
|
+
export declare function parseToolInput(text: string, empty?: unknown): unknown;
|
|
37
|
+
/** An assistant message with an unknown cost, which `createModel()` prices from the catalog. */
|
|
38
|
+
export declare function terminalMessage(model: ModelRef, partial: PartialReply, stopReason: AssistantMessage["stopReason"], error?: NonNullable<AssistantMessage["error"]>): AssistantMessage;
|
|
39
|
+
/** The `error` terminal of an aborted call, which carries no `error`. */
|
|
40
|
+
export declare function abortedEvent(model: ModelRef, partial?: PartialReply): Extract<ModelEvent, {
|
|
41
|
+
type: "error";
|
|
42
|
+
}>;
|
|
43
|
+
/**
|
|
44
|
+
* The `error` terminal for a failure. A failure with no HTTP status, such as an error event inside a 200 stream,
|
|
45
|
+
* classifies like the status its type stands for in `statusOfType`. The message starts with the error code or type.
|
|
46
|
+
*/
|
|
47
|
+
export declare function failureTerminal(model: ModelRef, failure: WireFailure, statusOfType: Readonly<Record<string, number>>, partial?: PartialReply, code?: ModelErrorCode): Extract<ModelEvent, {
|
|
48
|
+
type: "error";
|
|
49
|
+
}>;
|
|
50
|
+
/** The `error` terminal for a throw: retryable only for a transport failure, and `fatal` for a bug or bad data. */
|
|
51
|
+
export declare function thrownTerminal(model: ModelRef, thrown: unknown, partial?: PartialReply): {
|
|
52
|
+
type: "error";
|
|
53
|
+
message: AssistantMessage;
|
|
54
|
+
};
|
|
55
|
+
/** A failed response's body, parsed as JSON when it is JSON, and its text. */
|
|
56
|
+
export declare function readErrorBody(response: Response): Promise<{
|
|
57
|
+
body: unknown;
|
|
58
|
+
text: string;
|
|
59
|
+
}>;
|
|
60
|
+
/** The body `onPayload` asks for, or the adapter's own when it returns `undefined`. */
|
|
61
|
+
export declare function payloadOf(body: unknown, options: StreamOptions): unknown;
|
|
62
|
+
/**
|
|
63
|
+
* Sends one HTTP request. A transport that throws becomes an `error` terminal unless the throw is a guard's; only a
|
|
64
|
+
* transport failure, by the rule the retries use, may be retried, and any other throw is `fatal`.
|
|
65
|
+
*/
|
|
66
|
+
export declare function sendRequest(transport: Transport, request: Request, model: ModelRef, signal: AbortSignal | undefined): AsyncGenerator<ModelEvent, Response | undefined>;
|
|
67
|
+
/** How one protocol reads its event stream. */
|
|
68
|
+
export interface StreamReader {
|
|
69
|
+
/** The events one server-sent event produces. The stream is over once one of them is the terminal. */
|
|
70
|
+
handle(event: ServerSentEvent): ModelEvent[];
|
|
71
|
+
/** The content and usage so far, for an `error` terminal. */
|
|
72
|
+
partial(): PartialReply;
|
|
73
|
+
/** The events for a stream that closed before its terminal, ending in a terminal. */
|
|
74
|
+
ended(): ModelEvent[];
|
|
75
|
+
}
|
|
76
|
+
/** Reads a 200 stream to its terminal. A stream that breaks or ends early ends in an `error` terminal. */
|
|
77
|
+
export declare function readEventStream(response: Response, model: ModelRef, reader: StreamReader, signal: AbortSignal | undefined): AsyncGenerator<ModelEvent>;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What every wire adapter shares: sending one HTTP request through the caller's transport, reading a server-sent
|
|
3
|
+
* event stream to its terminal, and turning a failed request, a broken stream or an abort into an `error` terminal.
|
|
4
|
+
* A failed model call never throws; only a guard's error or a `GatewayError` does.
|
|
5
|
+
*/
|
|
6
|
+
import { classifyError, isTransportFailure } from "../classify.js";
|
|
7
|
+
import { isGatewayError } from "../errors.js";
|
|
8
|
+
import { assertModelRequestAllowed, ModelRequestsDisabledError } from "../request-policy.js";
|
|
9
|
+
import { readServerSentEvents } from "../sse.js";
|
|
10
|
+
import { emptyUsage } from "../usage.js";
|
|
11
|
+
/** True for a JSON object, not an array or `null`. */
|
|
12
|
+
export function isObject(value) {
|
|
13
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
14
|
+
}
|
|
15
|
+
/** The value when it is a string, or `""`. */
|
|
16
|
+
export function str(value) {
|
|
17
|
+
return typeof value === "string" ? value : "";
|
|
18
|
+
}
|
|
19
|
+
/** A token count: a finite positive number, or 0. */
|
|
20
|
+
export function count(value) {
|
|
21
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
|
|
22
|
+
}
|
|
23
|
+
/** A tool call's input: the parsed JSON, or the partial JSON text when the output limit cut it off. */
|
|
24
|
+
export function parseToolInput(text, empty = {}) {
|
|
25
|
+
if (text === "")
|
|
26
|
+
return empty;
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(text);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return text;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** An assistant message with an unknown cost, which `createModel()` prices from the catalog. */
|
|
35
|
+
export function terminalMessage(model, partial, stopReason, error) {
|
|
36
|
+
return {
|
|
37
|
+
role: "assistant",
|
|
38
|
+
content: partial.content ?? [],
|
|
39
|
+
model,
|
|
40
|
+
stopReason,
|
|
41
|
+
...(error ? { error } : {}),
|
|
42
|
+
usage: partial.usage ?? emptyUsage(),
|
|
43
|
+
cost: { total: null, basis: "unknown", currency: "USD" },
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** The `error` terminal of an aborted call, which carries no `error`. */
|
|
47
|
+
export function abortedEvent(model, partial = {}) {
|
|
48
|
+
return { type: "error", message: terminalMessage(model, partial, "aborted") };
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The `error` terminal for a failure. A failure with no HTTP status, such as an error event inside a 200 stream,
|
|
52
|
+
* classifies like the status its type stands for in `statusOfType`. The message starts with the error code or type.
|
|
53
|
+
*/
|
|
54
|
+
export function failureTerminal(model, failure, statusOfType, partial = {}, code) {
|
|
55
|
+
const status = failure.status ?? (failure.type ? statusOfType[failure.type] : undefined);
|
|
56
|
+
const label = failure.errorCode ?? failure.type;
|
|
57
|
+
// Both go to the classifier: a billing error's code names its cause while its type says `insufficient_quota`.
|
|
58
|
+
const codes = [failure.errorCode, failure.type].filter((part) => part !== undefined && part !== "").join(" ");
|
|
59
|
+
const kind = failure.kind ??
|
|
60
|
+
classifyError({
|
|
61
|
+
...(status === undefined ? {} : { status }),
|
|
62
|
+
...(codes ? { code: codes } : {}),
|
|
63
|
+
message: failure.message,
|
|
64
|
+
});
|
|
65
|
+
const error = {
|
|
66
|
+
kind,
|
|
67
|
+
message: label ? `${label}: ${failure.message}` : failure.message,
|
|
68
|
+
...(failure.status === undefined ? {} : { status: failure.status }),
|
|
69
|
+
...(code ? { code } : {}),
|
|
70
|
+
};
|
|
71
|
+
return { type: "error", message: terminalMessage(model, partial, "error", error) };
|
|
72
|
+
}
|
|
73
|
+
/** The `error` terminal for a throw: retryable only for a transport failure, and `fatal` for a bug or bad data. */
|
|
74
|
+
export function thrownTerminal(model, thrown, partial = {}) {
|
|
75
|
+
const message = thrown instanceof Error ? `${thrown.name}: ${thrown.message}` : String(thrown);
|
|
76
|
+
return failureTerminal(model, { message, ...(isTransportFailure(thrown) ? {} : { kind: "fatal" }) }, {}, partial);
|
|
77
|
+
}
|
|
78
|
+
/** A failed response's body, parsed as JSON when it is JSON, and its text. */
|
|
79
|
+
export async function readErrorBody(response) {
|
|
80
|
+
const text = await response.text().catch(() => "");
|
|
81
|
+
try {
|
|
82
|
+
return { body: JSON.parse(text), text };
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return { body: undefined, text };
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** The body `onPayload` asks for, or the adapter's own when it returns `undefined`. */
|
|
89
|
+
export function payloadOf(body, options) {
|
|
90
|
+
const replaced = options.onPayload ? options.onPayload(body) : undefined;
|
|
91
|
+
return replaced === undefined ? body : replaced;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Sends one HTTP request. A transport that throws becomes an `error` terminal unless the throw is a guard's; only a
|
|
95
|
+
* transport failure, by the rule the retries use, may be retried, and any other throw is `fatal`.
|
|
96
|
+
*/
|
|
97
|
+
export async function* sendRequest(transport, request, model, signal) {
|
|
98
|
+
assertModelRequestAllowed(transport);
|
|
99
|
+
try {
|
|
100
|
+
return await transport(request);
|
|
101
|
+
}
|
|
102
|
+
catch (thrown) {
|
|
103
|
+
if (isGatewayError(thrown) || thrown instanceof ModelRequestsDisabledError)
|
|
104
|
+
throw thrown;
|
|
105
|
+
yield signal?.aborted ? abortedEvent(model) : thrownTerminal(model, thrown);
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** Feeds each server-sent event to the reader; returns true once it has yielded the terminal. */
|
|
110
|
+
async function* pump(body, reader) {
|
|
111
|
+
for await (const sse of readServerSentEvents(body)) {
|
|
112
|
+
for (const event of reader.handle(sse)) {
|
|
113
|
+
yield event;
|
|
114
|
+
if (event.type === "done" || event.type === "error")
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
/** Reads a 200 stream to its terminal. A stream that breaks or ends early ends in an `error` terminal. */
|
|
121
|
+
export async function* readEventStream(response, model, reader, signal) {
|
|
122
|
+
if (response.body === null) {
|
|
123
|
+
yield failureTerminal(model, { message: "the response has no body" }, {});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
if (yield* pump(response.body, reader))
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
catch (thrown) {
|
|
131
|
+
// A broken connection may work on a retry; malformed event data, a SyntaxError, will not parse on one either.
|
|
132
|
+
yield signal?.aborted ? abortedEvent(model, reader.partial()) : thrownTerminal(model, thrown, reader.partial());
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
yield* reader.ended();
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=wire.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wire.js","sourceRoot":"","sources":["../../src/adapters/wire.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,aAAa,EAAkB,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACnF,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC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AAE,CAAC;QACnD,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;YACvC,MAAM,KAAK,CAAC;YACZ,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO;gBAAE,OAAO,IAAI,CAAC;QACnE,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,0GAA0G;AAC1G,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,eAAe,CACpC,QAAkB,EAClB,KAAe,EACf,MAAoB,EACpB,MAA+B;IAE/B,IAAI,QAAQ,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;QAC3B,MAAM,eAAe,CAAC,KAAK,EAAE,EAAE,OAAO,EAAE,0BAA0B,EAAE,EAAE,EAAE,CAAC,CAAC;QAC1E,OAAO;IACT,CAAC;IACD,IAAI,CAAC;QACH,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;YAAE,OAAO;IACjD,CAAC;IAAC,OAAO,MAAM,EAAE,CAAC;QAChB,8GAA8G;QAC9G,MAAM,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,YAAY,CAAC,KAAK,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;QAChH,OAAO;IACT,CAAC;IACD,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;AACxB,CAAC","sourcesContent":["/**\n * What every wire adapter shares: sending one HTTP request through the caller's transport, reading a server-sent\n * event stream to its terminal, and turning a failed request, a broken stream or an abort into an `error` terminal.\n * A failed model call never throws; only a guard's error or a `GatewayError` does.\n */\nimport { classifyError, type ErrorKind, isTransportFailure } from \"../classify.js\";\nimport { isGatewayError } from \"../errors.js\";\nimport { assertModelRequestAllowed, ModelRequestsDisabledError } from \"../request-policy.js\";\nimport type { Transport } from \"../runtime-types.js\";\nimport type { ModelEvent, StreamOptions } from \"../spec.js\";\nimport { readServerSentEvents, type ServerSentEvent } from \"../sse.js\";\nimport type { AssistantMessage, ContentBlock, ModelErrorCode, ModelRef, Usage } from \"../types.js\";\nimport { emptyUsage } from \"../usage.js\";\n\n/** A JSON object as the adapters read it off the wire. */\nexport type Json = Record<string, unknown>;\n\n/** The content and usage an attempt reached before it ended. */\nexport interface PartialReply {\n readonly content?: ContentBlock[];\n readonly usage?: Usage;\n}\n\n/** What one failure says about itself. */\nexport interface WireFailure {\n readonly status?: number;\n /** The provider's error type, such as `\"invalid_request_error\"`. */\n readonly type?: string;\n /** The provider's finer error code, when the error has one, such as `\"insufficient_quota\"`. */\n readonly errorCode?: string;\n readonly message: string;\n /** Sets the kind outright, for a failure that no status describes, such as a refusal inside a 200 stream. */\n readonly kind?: ErrorKind;\n}\n\n/** True for a JSON object, not an array or `null`. */\nexport function isObject(value: unknown): value is Json {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** The value when it is a string, or `\"\"`. */\nexport function str(value: unknown): string {\n return typeof value === \"string\" ? value : \"\";\n}\n\n/** A token count: a finite positive number, or 0. */\nexport function count(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\n}\n\n/** A tool call's input: the parsed JSON, or the partial JSON text when the output limit cut it off. */\nexport function parseToolInput(text: string, empty: unknown = {}): unknown {\n if (text === \"\") return empty;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** An assistant message with an unknown cost, which `createModel()` prices from the catalog. */\nexport function terminalMessage(\n model: ModelRef,\n partial: PartialReply,\n stopReason: AssistantMessage[\"stopReason\"],\n error?: NonNullable<AssistantMessage[\"error\"]>,\n): AssistantMessage {\n return {\n role: \"assistant\",\n content: partial.content ?? [],\n model,\n stopReason,\n ...(error ? { error } : {}),\n usage: partial.usage ?? emptyUsage(),\n cost: { total: null, basis: \"unknown\", currency: \"USD\" },\n };\n}\n\n/** The `error` terminal of an aborted call, which carries no `error`. */\nexport function abortedEvent(model: ModelRef, partial: PartialReply = {}): Extract<ModelEvent, { type: \"error\" }> {\n return { type: \"error\", message: terminalMessage(model, partial, \"aborted\") };\n}\n\n/**\n * The `error` terminal for a failure. A failure with no HTTP status, such as an error event inside a 200 stream,\n * classifies like the status its type stands for in `statusOfType`. The message starts with the error code or type.\n */\nexport function failureTerminal(\n model: ModelRef,\n failure: WireFailure,\n statusOfType: Readonly<Record<string, number>>,\n partial: PartialReply = {},\n code?: ModelErrorCode,\n): Extract<ModelEvent, { type: \"error\" }> {\n const status = failure.status ?? (failure.type ? statusOfType[failure.type] : undefined);\n const label = failure.errorCode ?? failure.type;\n // Both go to the classifier: a billing error's code names its cause while its type says `insufficient_quota`.\n const codes = [failure.errorCode, failure.type].filter((part) => part !== undefined && part !== \"\").join(\" \");\n const kind =\n failure.kind ??\n classifyError({\n ...(status === undefined ? {} : { status }),\n ...(codes ? { code: codes } : {}),\n message: failure.message,\n });\n const error: NonNullable<AssistantMessage[\"error\"]> = {\n kind,\n message: label ? `${label}: ${failure.message}` : failure.message,\n ...(failure.status === undefined ? {} : { status: failure.status }),\n ...(code ? { code } : {}),\n };\n return { type: \"error\", message: terminalMessage(model, partial, \"error\", error) };\n}\n\n/** The `error` terminal for a throw: retryable only for a transport failure, and `fatal` for a bug or bad data. */\nexport function thrownTerminal(model: ModelRef, thrown: unknown, partial: PartialReply = {}) {\n const message = thrown instanceof Error ? `${thrown.name}: ${thrown.message}` : String(thrown);\n return failureTerminal(model, { message, ...(isTransportFailure(thrown) ? {} : { kind: \"fatal\" }) }, {}, partial);\n}\n\n/** A failed response's body, parsed as JSON when it is JSON, and its text. */\nexport async function readErrorBody(response: Response): Promise<{ body: unknown; text: string }> {\n const text = await response.text().catch(() => \"\");\n try {\n return { body: JSON.parse(text), text };\n } catch {\n return { body: undefined, text };\n }\n}\n\n/** The body `onPayload` asks for, or the adapter's own when it returns `undefined`. */\nexport function payloadOf(body: unknown, options: StreamOptions): unknown {\n const replaced = options.onPayload ? options.onPayload(body) : undefined;\n return replaced === undefined ? body : replaced;\n}\n\n/**\n * Sends one HTTP request. A transport that throws becomes an `error` terminal unless the throw is a guard's; only a\n * transport failure, by the rule the retries use, may be retried, and any other throw is `fatal`.\n */\nexport async function* sendRequest(\n transport: Transport,\n request: Request,\n model: ModelRef,\n signal: AbortSignal | undefined,\n): AsyncGenerator<ModelEvent, Response | undefined> {\n assertModelRequestAllowed(transport);\n try {\n return await transport(request);\n } catch (thrown) {\n if (isGatewayError(thrown) || thrown instanceof ModelRequestsDisabledError) throw thrown;\n yield signal?.aborted ? abortedEvent(model) : thrownTerminal(model, thrown);\n return undefined;\n }\n}\n\n/** How one protocol reads its event stream. */\nexport interface StreamReader {\n /** The events one server-sent event produces. The stream is over once one of them is the terminal. */\n handle(event: ServerSentEvent): ModelEvent[];\n /** The content and usage so far, for an `error` terminal. */\n partial(): PartialReply;\n /** The events for a stream that closed before its terminal, ending in a terminal. */\n ended(): ModelEvent[];\n}\n\n/** Feeds each server-sent event to the reader; returns true once it has yielded the terminal. */\nasync function* pump(body: ReadableStream<Uint8Array>, reader: StreamReader): AsyncGenerator<ModelEvent, boolean> {\n for await (const sse of readServerSentEvents(body)) {\n for (const event of reader.handle(sse)) {\n yield event;\n if (event.type === \"done\" || event.type === \"error\") return true;\n }\n }\n return false;\n}\n\n/** Reads a 200 stream to its terminal. A stream that breaks or ends early ends in an `error` terminal. */\nexport async function* readEventStream(\n response: Response,\n model: ModelRef,\n reader: StreamReader,\n signal: AbortSignal | undefined,\n): AsyncGenerator<ModelEvent> {\n if (response.body === null) {\n yield failureTerminal(model, { message: \"the response has no body\" }, {});\n return;\n }\n try {\n if (yield* pump(response.body, reader)) return;\n } catch (thrown) {\n // A broken connection may work on a retry; malformed event data, a SyntaxError, will not parse on one either.\n yield signal?.aborted ? abortedEvent(model, reader.partial()) : thrownTerminal(model, thrown, reader.partial());\n return;\n }\n yield* reader.ended();\n}\n"]}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The USD price per million tokens of each token class, for requests up to `upToInputTokens` input tokens.
|
|
3
|
+
* `upToInputTokens` counts every input class, cache reads and cache writes included, and is `null` for the last tier.
|
|
4
|
+
*/
|
|
5
|
+
export interface RateTier {
|
|
6
|
+
readonly upToInputTokens: number | null;
|
|
7
|
+
readonly uncachedInput: number;
|
|
8
|
+
readonly cacheRead: number;
|
|
9
|
+
/**
|
|
10
|
+
* The short and the long cache-write rate. The keys name Anthropic's 5-minute and 1-hour writes; an OpenAI entry
|
|
11
|
+
* stores its 30-minute rate under `"5m"`, the key its adapter counts every Chat Completions write under.
|
|
12
|
+
*/
|
|
13
|
+
readonly cacheWrite: {
|
|
14
|
+
readonly "5m": number;
|
|
15
|
+
readonly "1h": number;
|
|
16
|
+
};
|
|
17
|
+
/** Reasoning tokens are part of output and are billed at this rate. */
|
|
18
|
+
readonly output: number;
|
|
19
|
+
}
|
|
20
|
+
/** Where each part of a catalog entry was copied from: the provider's own pricing and model pages. */
|
|
21
|
+
export interface CatalogSources {
|
|
22
|
+
readonly rates: string;
|
|
23
|
+
readonly contextWindow: string;
|
|
24
|
+
readonly maxOutputTokens: string;
|
|
25
|
+
}
|
|
26
|
+
/** One model in the price catalog: its rates, its limits, and the date and pages they were copied from. */
|
|
27
|
+
export interface CatalogEntry {
|
|
28
|
+
readonly provider: string;
|
|
29
|
+
readonly id: string;
|
|
30
|
+
/** The rate tiers, in ascending order of `upToInputTokens`. A model without long-context pricing has one tier. */
|
|
31
|
+
readonly rates: readonly RateTier[];
|
|
32
|
+
/**
|
|
33
|
+
* The most input tokens one request can send: the context window, or the provider's lower input limit when its
|
|
34
|
+
* model page sets one inside the window.
|
|
35
|
+
*/
|
|
36
|
+
readonly contextWindow: number;
|
|
37
|
+
readonly maxOutputTokens: number;
|
|
38
|
+
/** Whether the model takes image input. Left out, the adapter's default applies. */
|
|
39
|
+
readonly images?: boolean;
|
|
40
|
+
/** Whether the model reasons. Left out, the adapter's default applies. */
|
|
41
|
+
readonly reasoning?: boolean;
|
|
42
|
+
/** The date the rates and limits were copied, as `YYYY-MM-DD`. */
|
|
43
|
+
readonly asOf: string;
|
|
44
|
+
readonly sources: CatalogSources;
|
|
45
|
+
/** How a number was derived when the sources don't state it directly. */
|
|
46
|
+
readonly note?: string;
|
|
47
|
+
}
|
|
48
|
+
/** A list of catalog entries. `createModel()` reads a model's caps and prices from it. */
|
|
49
|
+
export interface PriceCatalog {
|
|
50
|
+
readonly models: readonly CatalogEntry[];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Checks a catalog read from JSON and returns it typed. Throws a `GatewayError` with code `invalid_catalog` that
|
|
54
|
+
* names the first bad field, such as a negative rate, a missing source URL or two entries for one model.
|
|
55
|
+
*/
|
|
56
|
+
export declare function parseCatalog(value: unknown): PriceCatalog;
|
|
57
|
+
/** The catalog that ships with the gateway. `createModel()` uses it unless you pass your own. */
|
|
58
|
+
export declare const defaultCatalog: PriceCatalog;
|
|
59
|
+
/** The entry for one model, or `undefined` when the catalog doesn't list it. */
|
|
60
|
+
export declare function findCatalogEntry(catalog: PriceCatalog, provider: string, id: string): CatalogEntry | undefined;
|
|
61
|
+
/**
|
|
62
|
+
* The entries whose `asOf` date is more than `maxAgeDays` days before `now`. Prices change often, so check a catalog
|
|
63
|
+
* you maintain with this before each release.
|
|
64
|
+
*/
|
|
65
|
+
export declare function staleCatalogEntries(catalog: PriceCatalog, now: Date, maxAgeDays?: number): CatalogEntry[];
|
package/dist/catalog.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The price catalog: per-model rates, limits, the date they were copied and where from (D4). `catalog.json` ships
|
|
3
|
+
* with the package; a caller may pass its own catalog instead. Nothing here fetches prices at run time, so cost never
|
|
4
|
+
* depends on the network.
|
|
5
|
+
*/
|
|
6
|
+
import shipped from "./catalog.json" with { type: "json" };
|
|
7
|
+
import { GatewayError } from "./errors.js";
|
|
8
|
+
function fail(where, problem) {
|
|
9
|
+
throw new GatewayError("invalid_catalog", `price catalog: ${where} ${problem}`);
|
|
10
|
+
}
|
|
11
|
+
function objectAt(value, where) {
|
|
12
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
13
|
+
fail(where, "must be an object");
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
function rate(value, where) {
|
|
17
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
|
|
18
|
+
fail(where, "must be a non-negative number");
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
function tokenCount(value, where) {
|
|
22
|
+
if (!Number.isInteger(value) || value <= 0)
|
|
23
|
+
fail(where, "must be a positive integer");
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
function text(value, where) {
|
|
27
|
+
if (typeof value !== "string" || value === "")
|
|
28
|
+
fail(where, "must be a non-empty string");
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
function url(value, where) {
|
|
32
|
+
const s = text(value, where);
|
|
33
|
+
if (!/^https:\/\/\S+$/.test(s))
|
|
34
|
+
fail(where, "must be an https URL");
|
|
35
|
+
return s;
|
|
36
|
+
}
|
|
37
|
+
function date(value, where) {
|
|
38
|
+
const s = text(value, where);
|
|
39
|
+
// A calendar check, so "2026-02-30" fails as well as "Nov 2026". `Date.parse` is NaN for a month or day out of
|
|
40
|
+
// range, such as "2026-13-01", where `toISOString()` would throw a RangeError.
|
|
41
|
+
const time = /^\d{4}-\d{2}-\d{2}$/.test(s) ? Date.parse(`${s}T00:00:00Z`) : Number.NaN;
|
|
42
|
+
if (Number.isNaN(time) || new Date(time).toISOString().slice(0, 10) !== s) {
|
|
43
|
+
fail(where, "must be a date in the form YYYY-MM-DD");
|
|
44
|
+
}
|
|
45
|
+
return s;
|
|
46
|
+
}
|
|
47
|
+
function optionalFlag(value, where) {
|
|
48
|
+
if (value !== undefined && typeof value !== "boolean")
|
|
49
|
+
fail(where, "must be true or false");
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
function optionalText(value, where) {
|
|
53
|
+
return value === undefined ? undefined : text(value, where);
|
|
54
|
+
}
|
|
55
|
+
function parseTier(value, where, last) {
|
|
56
|
+
const tier = objectAt(value, where);
|
|
57
|
+
const cacheWrite = objectAt(tier.cacheWrite, `${where}.cacheWrite`);
|
|
58
|
+
const limit = tier.upToInputTokens;
|
|
59
|
+
if (last && limit !== null)
|
|
60
|
+
fail(`${where}.upToInputTokens`, "must be null on the last tier");
|
|
61
|
+
return {
|
|
62
|
+
upToInputTokens: last ? null : tokenCount(limit, `${where}.upToInputTokens`),
|
|
63
|
+
uncachedInput: rate(tier.uncachedInput, `${where}.uncachedInput`),
|
|
64
|
+
cacheRead: rate(tier.cacheRead, `${where}.cacheRead`),
|
|
65
|
+
cacheWrite: {
|
|
66
|
+
"5m": rate(cacheWrite["5m"], `${where}.cacheWrite.5m`),
|
|
67
|
+
"1h": rate(cacheWrite["1h"], `${where}.cacheWrite.1h`),
|
|
68
|
+
},
|
|
69
|
+
output: rate(tier.output, `${where}.output`),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function parseTiers(value, where) {
|
|
73
|
+
if (!Array.isArray(value) || value.length === 0)
|
|
74
|
+
fail(where, "must be a non-empty array");
|
|
75
|
+
const tiers = value.map((tier, i) => parseTier(tier, `${where}[${i}]`, i === value.length - 1));
|
|
76
|
+
let previous = 0;
|
|
77
|
+
for (const tier of tiers) {
|
|
78
|
+
if (tier.upToInputTokens === null)
|
|
79
|
+
break;
|
|
80
|
+
if (tier.upToInputTokens <= previous)
|
|
81
|
+
fail(where, "must be in ascending order of upToInputTokens");
|
|
82
|
+
previous = tier.upToInputTokens;
|
|
83
|
+
}
|
|
84
|
+
return tiers;
|
|
85
|
+
}
|
|
86
|
+
function parseSources(value, where) {
|
|
87
|
+
const sources = objectAt(value, where);
|
|
88
|
+
return {
|
|
89
|
+
rates: url(sources.rates, `${where}.rates`),
|
|
90
|
+
contextWindow: url(sources.contextWindow, `${where}.contextWindow`),
|
|
91
|
+
maxOutputTokens: url(sources.maxOutputTokens, `${where}.maxOutputTokens`),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function parseEntry(value, where) {
|
|
95
|
+
const entry = objectAt(value, where);
|
|
96
|
+
const images = optionalFlag(entry.images, `${where}.images`);
|
|
97
|
+
const reasoning = optionalFlag(entry.reasoning, `${where}.reasoning`);
|
|
98
|
+
const note = optionalText(entry.note, `${where}.note`);
|
|
99
|
+
return {
|
|
100
|
+
provider: text(entry.provider, `${where}.provider`),
|
|
101
|
+
id: text(entry.id, `${where}.id`),
|
|
102
|
+
rates: parseTiers(entry.rates, `${where}.rates`),
|
|
103
|
+
contextWindow: tokenCount(entry.contextWindow, `${where}.contextWindow`),
|
|
104
|
+
maxOutputTokens: tokenCount(entry.maxOutputTokens, `${where}.maxOutputTokens`),
|
|
105
|
+
...(images === undefined ? {} : { images }),
|
|
106
|
+
...(reasoning === undefined ? {} : { reasoning }),
|
|
107
|
+
asOf: date(entry.asOf, `${where}.asOf`),
|
|
108
|
+
sources: parseSources(entry.sources, `${where}.sources`),
|
|
109
|
+
...(note === undefined ? {} : { note }),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Checks a catalog read from JSON and returns it typed. Throws a `GatewayError` with code `invalid_catalog` that
|
|
114
|
+
* names the first bad field, such as a negative rate, a missing source URL or two entries for one model.
|
|
115
|
+
*/
|
|
116
|
+
export function parseCatalog(value) {
|
|
117
|
+
const catalog = objectAt(value, "the catalog");
|
|
118
|
+
if (!Array.isArray(catalog.models))
|
|
119
|
+
fail("models", "must be an array");
|
|
120
|
+
const models = catalog.models.map((entry, i) => parseEntry(entry, `models[${i}]`));
|
|
121
|
+
const seen = new Set();
|
|
122
|
+
for (const { provider, id } of models) {
|
|
123
|
+
// A plain `provider/id` join would collide, because both may contain "/".
|
|
124
|
+
const key = JSON.stringify([provider, id]);
|
|
125
|
+
if (seen.has(key))
|
|
126
|
+
fail("models", `lists ${provider}/${id} twice`);
|
|
127
|
+
seen.add(key);
|
|
128
|
+
}
|
|
129
|
+
return { models };
|
|
130
|
+
}
|
|
131
|
+
/** The catalog that ships with the gateway. `createModel()` uses it unless you pass your own. */
|
|
132
|
+
export const defaultCatalog = parseCatalog(shipped);
|
|
133
|
+
/** The entry for one model, or `undefined` when the catalog doesn't list it. */
|
|
134
|
+
export function findCatalogEntry(catalog, provider, id) {
|
|
135
|
+
return catalog.models.find((m) => m.provider === provider && m.id === id);
|
|
136
|
+
}
|
|
137
|
+
const DAY_MS = 86_400_000;
|
|
138
|
+
/**
|
|
139
|
+
* The entries whose `asOf` date is more than `maxAgeDays` days before `now`. Prices change often, so check a catalog
|
|
140
|
+
* you maintain with this before each release.
|
|
141
|
+
*/
|
|
142
|
+
export function staleCatalogEntries(catalog, now, maxAgeDays = 90) {
|
|
143
|
+
return catalog.models.filter((entry) => now.getTime() - Date.parse(`${entry.asOf}T00:00:00Z`) > maxAgeDays * DAY_MS);
|
|
144
|
+
}
|
|
145
|
+
//# sourceMappingURL=catalog.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,OAAO,MAAM,gBAAgB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAwD3C,SAAS,IAAI,CAAC,KAAa,EAAE,OAAe;IAC1C,MAAM,IAAI,YAAY,CAAC,iBAAiB,EAAE,kBAAkB,KAAK,IAAI,OAAO,EAAE,CAAC,CAAC;AAClF,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc,EAAE,KAAa;IAC7C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,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,iGAAiG;AACjG,MAAM,CAAC,MAAM,cAAc,GAAiB,YAAY,CAAC,OAAO,CAAC,CAAC;AAElE,gFAAgF;AAChF,MAAM,UAAU,gBAAgB,CAAC,OAAqB,EAAE,QAAgB,EAAE,EAAU;IAClF,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,QAAQ,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,MAAM,GAAG,UAAU,CAAC;AAE1B;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAqB,EAAE,GAAS,EAAE,UAAU,GAAG,EAAE;IACnF,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC,IAAI,YAAY,CAAC,GAAG,UAAU,GAAG,MAAM,CAAC,CAAC;AACvH,CAAC","sourcesContent":["/**\n * The price catalog: per-model rates, limits, the date they were copied and where from (D4). `catalog.json` ships\n * with the package; a caller may pass its own catalog instead. Nothing here fetches prices at run time, so cost never\n * depends on the network.\n */\nimport shipped from \"./catalog.json\" with { type: \"json\" };\nimport { GatewayError } from \"./errors.js\";\n\n/**\n * The USD price per million tokens of each token class, for requests up to `upToInputTokens` input tokens.\n * `upToInputTokens` counts every input class, cache reads and cache writes included, and is `null` for the last tier.\n */\nexport interface RateTier {\n readonly upToInputTokens: number | null;\n readonly uncachedInput: number;\n readonly cacheRead: number;\n /**\n * The short and the long cache-write rate. The keys name Anthropic's 5-minute and 1-hour writes; an OpenAI entry\n * stores its 30-minute rate under `\"5m\"`, the key its adapter counts every Chat Completions write under.\n */\n readonly cacheWrite: { readonly \"5m\": number; readonly \"1h\": number };\n /** Reasoning tokens are part of output and are billed at this rate. */\n readonly output: number;\n}\n\n/** Where each part of a catalog entry was copied from: the provider's own pricing and model pages. */\nexport interface CatalogSources {\n readonly rates: string;\n readonly contextWindow: string;\n readonly maxOutputTokens: string;\n}\n\n/** One model in the price catalog: its rates, its limits, and the date and pages they were copied from. */\nexport interface CatalogEntry {\n readonly provider: string;\n readonly id: string;\n /** The rate tiers, in ascending order of `upToInputTokens`. A model without long-context pricing has one tier. */\n readonly rates: readonly RateTier[];\n /**\n * The most input tokens one request can send: the context window, or the provider's lower input limit when its\n * model page sets one inside the window.\n */\n readonly contextWindow: number;\n readonly maxOutputTokens: number;\n /** Whether the model takes image input. Left out, the adapter's default applies. */\n readonly images?: boolean;\n /** Whether the model reasons. Left out, the adapter's default applies. */\n readonly reasoning?: boolean;\n /** The date the rates and limits were copied, as `YYYY-MM-DD`. */\n readonly asOf: string;\n readonly sources: CatalogSources;\n /** How a number was derived when the sources don't state it directly. */\n readonly note?: string;\n}\n\n/** A list of catalog entries. `createModel()` reads a model's caps and prices from it. */\nexport interface PriceCatalog {\n readonly models: readonly CatalogEntry[];\n}\n\ntype Json = Record<string, unknown>;\n\nfunction fail(where: string, problem: string): never {\n throw new GatewayError(\"invalid_catalog\", `price catalog: ${where} ${problem}`);\n}\n\nfunction objectAt(value: unknown, where: string): Json {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) fail(where, \"must be an object\");\n return value as Json;\n}\n\nfunction rate(value: unknown, where: string): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) fail(where, \"must be a non-negative number\");\n return value;\n}\n\nfunction tokenCount(value: unknown, where: string): number {\n if (!Number.isInteger(value) || (value as number) <= 0) fail(where, \"must be a positive integer\");\n return value as number;\n}\n\nfunction text(value: unknown, where: string): string {\n if (typeof value !== \"string\" || value === \"\") fail(where, \"must be a non-empty string\");\n return value;\n}\n\nfunction url(value: unknown, where: string): string {\n const s = text(value, where);\n if (!/^https:\\/\\/\\S+$/.test(s)) fail(where, \"must be an https URL\");\n return s;\n}\n\nfunction date(value: unknown, where: string): string {\n const s = text(value, where);\n // A calendar check, so \"2026-02-30\" fails as well as \"Nov 2026\". `Date.parse` is NaN for a month or day out of\n // range, such as \"2026-13-01\", where `toISOString()` would throw a RangeError.\n const time = /^\\d{4}-\\d{2}-\\d{2}$/.test(s) ? Date.parse(`${s}T00:00:00Z`) : Number.NaN;\n if (Number.isNaN(time) || new Date(time).toISOString().slice(0, 10) !== s) {\n fail(where, \"must be a date in the form YYYY-MM-DD\");\n }\n return s;\n}\n\nfunction optionalFlag(value: unknown, where: string): boolean | undefined {\n if (value !== undefined && typeof value !== \"boolean\") fail(where, \"must be true or false\");\n return value;\n}\n\nfunction optionalText(value: unknown, where: string): string | undefined {\n return value === undefined ? undefined : text(value, where);\n}\n\nfunction parseTier(value: unknown, where: string, last: boolean): RateTier {\n const tier = objectAt(value, where);\n const cacheWrite = objectAt(tier.cacheWrite, `${where}.cacheWrite`);\n const limit = tier.upToInputTokens;\n if (last && limit !== null) fail(`${where}.upToInputTokens`, \"must be null on the last tier\");\n return {\n upToInputTokens: last ? null : tokenCount(limit, `${where}.upToInputTokens`),\n uncachedInput: rate(tier.uncachedInput, `${where}.uncachedInput`),\n cacheRead: rate(tier.cacheRead, `${where}.cacheRead`),\n cacheWrite: {\n \"5m\": rate(cacheWrite[\"5m\"], `${where}.cacheWrite.5m`),\n \"1h\": rate(cacheWrite[\"1h\"], `${where}.cacheWrite.1h`),\n },\n output: rate(tier.output, `${where}.output`),\n };\n}\n\nfunction parseTiers(value: unknown, where: string): RateTier[] {\n if (!Array.isArray(value) || value.length === 0) fail(where, \"must be a non-empty array\");\n const tiers = value.map((tier, i) => parseTier(tier, `${where}[${i}]`, i === value.length - 1));\n let previous = 0;\n for (const tier of tiers) {\n if (tier.upToInputTokens === null) break;\n if (tier.upToInputTokens <= previous) fail(where, \"must be in ascending order of upToInputTokens\");\n previous = tier.upToInputTokens;\n }\n return tiers;\n}\n\nfunction parseSources(value: unknown, where: string): CatalogSources {\n const sources = objectAt(value, where);\n return {\n rates: url(sources.rates, `${where}.rates`),\n contextWindow: url(sources.contextWindow, `${where}.contextWindow`),\n maxOutputTokens: url(sources.maxOutputTokens, `${where}.maxOutputTokens`),\n };\n}\n\nfunction parseEntry(value: unknown, where: string): CatalogEntry {\n const entry = objectAt(value, where);\n const images = optionalFlag(entry.images, `${where}.images`);\n const reasoning = optionalFlag(entry.reasoning, `${where}.reasoning`);\n const note = optionalText(entry.note, `${where}.note`);\n return {\n provider: text(entry.provider, `${where}.provider`),\n id: text(entry.id, `${where}.id`),\n rates: parseTiers(entry.rates, `${where}.rates`),\n contextWindow: tokenCount(entry.contextWindow, `${where}.contextWindow`),\n maxOutputTokens: tokenCount(entry.maxOutputTokens, `${where}.maxOutputTokens`),\n ...(images === undefined ? {} : { images }),\n ...(reasoning === undefined ? {} : { reasoning }),\n asOf: date(entry.asOf, `${where}.asOf`),\n sources: parseSources(entry.sources, `${where}.sources`),\n ...(note === undefined ? {} : { note }),\n };\n}\n\n/**\n * Checks a catalog read from JSON and returns it typed. Throws a `GatewayError` with code `invalid_catalog` that\n * names the first bad field, such as a negative rate, a missing source URL or two entries for one model.\n */\nexport function parseCatalog(value: unknown): PriceCatalog {\n const catalog = objectAt(value, \"the catalog\");\n if (!Array.isArray(catalog.models)) fail(\"models\", \"must be an array\");\n const models = catalog.models.map((entry, i) => parseEntry(entry, `models[${i}]`));\n const seen = new Set<string>();\n for (const { provider, id } of models) {\n // A plain `provider/id` join would collide, because both may contain \"/\".\n const key = JSON.stringify([provider, id]);\n if (seen.has(key)) fail(\"models\", `lists ${provider}/${id} twice`);\n seen.add(key);\n }\n return { models };\n}\n\n/** The catalog that ships with the gateway. `createModel()` uses it unless you pass your own. */\nexport const defaultCatalog: PriceCatalog = parseCatalog(shipped);\n\n/** The entry for one model, or `undefined` when the catalog doesn't list it. */\nexport function findCatalogEntry(catalog: PriceCatalog, provider: string, id: string): CatalogEntry | undefined {\n return catalog.models.find((m) => m.provider === provider && m.id === id);\n}\n\nconst DAY_MS = 86_400_000;\n\n/**\n * The entries whose `asOf` date is more than `maxAgeDays` days before `now`. Prices change often, so check a catalog\n * you maintain with this before each release.\n */\nexport function staleCatalogEntries(catalog: PriceCatalog, now: Date, maxAgeDays = 90): CatalogEntry[] {\n return catalog.models.filter((entry) => now.getTime() - Date.parse(`${entry.asOf}T00:00:00Z`) > maxAgeDays * DAY_MS);\n}\n"]}
|