@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":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAGL,cAAc,EACd,gBAAgB,EAEhB,YAAY,EAEZ,mBAAmB,GACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,aAAa,EAAsC,MAAM,eAAe,CAAC;AAClF,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAwB,UAAU,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAChH,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAyB,cAAc,EAAE,MAAM,aAAa,CAAC;AAClF,OAAO,EACL,mBAAmB,EACnB,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,eAAe,GAGhB,MAAM,YAAY,CAAC;AACpB,OAAO,EAA+B,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAC1F,OAAO,EACL,yBAAyB,EACzB,eAAe,EACf,0BAA0B,EAC1B,uBAAuB,GACxB,MAAM,qBAAqB,CAAC;AAe7B,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAe5D,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC","sourcesContent":["/**\n * `@buildanagent/gateway`: the model gateway's transcript, model spec, stream rule, runtime, price catalog and\n * helpers.\n */\nexport {\n type CatalogEntry,\n type CatalogSources,\n defaultCatalog,\n findCatalogEntry,\n type PriceCatalog,\n parseCatalog,\n type RateTier,\n staleCatalogEntries,\n} from \"./catalog.js\";\nexport { classifyError, type ErrorKind, type FailedRequest } from \"./classify.js\";\nexport { complete } from \"./complete.js\";\nexport { estimateInputTokens, type ProjectedTokens, priceUsage, projectCallCost, projectCost } from \"./cost.js\";\nexport { createModel } from \"./create-model.js\";\nexport { GatewayError, type GatewayErrorCode, isGatewayError } from \"./errors.js\";\nexport {\n assertCanonicalName,\n CANONICAL_TOOL_NAME,\n createToolNameMap,\n isCanonicalName,\n TOOL_NAME_RULES,\n type ToolNameMap,\n type ToolNameRule,\n} from \"./names.js\";\nexport { type ResolvedProviderConfig, resolveProviderConfig } from \"./provider-config.js\";\nexport {\n assertModelRequestAllowed,\n isMockTransport,\n ModelRequestsDisabledError,\n modelRequestsAreAllowed,\n} from \"./request-policy.js\";\nexport type {\n CreateModelOptions,\n DumpedOptions,\n GatewayEvent,\n MiddlewareParams,\n Model,\n ModelCallOptions,\n ModelMiddleware,\n ProviderConfig,\n RequestDump,\n Sleep,\n Transport,\n} from \"./runtime-types.js\";\nexport type { ModelAdapter, ModelEvent, StreamOptions } from \"./spec.js\";\nexport { assertStreamContract, StreamContractError } from \"./stream-contract.js\";\nexport { transformMessages } from \"./transform-messages.js\";\nexport type {\n AssistantMessage,\n ContentBlock,\n Cost,\n Message,\n ModelCaps,\n ModelContent,\n ModelContext,\n ModelErrorCode,\n ModelRef,\n OpaqueToken,\n Usage,\n WireTool,\n} from \"./types.js\";\nexport { addUsage, emptyUsage, totalInput } from \"./usage.js\";\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Middleware composition: the first middleware is outermost (SDK plan §3.2).
|
|
3
|
+
*
|
|
4
|
+
* `transformParams` runs first to last, each seeing the previous one's result. `wrapStream` nests the same way, so the
|
|
5
|
+
* first middleware's wrapper sees every event the inner ones pass on, retries included.
|
|
6
|
+
*/
|
|
7
|
+
import type { GatewayEvent, MiddlewareParams, ModelMiddleware } from "./runtime-types.js";
|
|
8
|
+
/** Applies each middleware's `transformParams` in order. */
|
|
9
|
+
export declare function transformParams(middleware: readonly ModelMiddleware[], params: MiddlewareParams): Promise<MiddlewareParams>;
|
|
10
|
+
/** Nests each middleware's `wrapStream` around `inner`, first outermost, and starts the outermost one. */
|
|
11
|
+
export declare function wrapStream(middleware: readonly ModelMiddleware[], params: MiddlewareParams, inner: () => AsyncIterable<GatewayEvent>): AsyncIterable<GatewayEvent>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Applies each middleware's `transformParams` in order. */
|
|
2
|
+
export async function transformParams(middleware, params) {
|
|
3
|
+
let current = params;
|
|
4
|
+
for (const m of middleware) {
|
|
5
|
+
if (m.transformParams)
|
|
6
|
+
current = await m.transformParams(current);
|
|
7
|
+
}
|
|
8
|
+
return current;
|
|
9
|
+
}
|
|
10
|
+
/** Nests each middleware's `wrapStream` around `inner`, first outermost, and starts the outermost one. */
|
|
11
|
+
export function wrapStream(middleware, params, inner) {
|
|
12
|
+
let next = inner;
|
|
13
|
+
for (const m of [...middleware].reverse()) {
|
|
14
|
+
const wrap = m.wrapStream?.bind(m);
|
|
15
|
+
if (!wrap)
|
|
16
|
+
continue;
|
|
17
|
+
const below = next;
|
|
18
|
+
next = () => wrap({ next: below, context: params.context, options: params.options });
|
|
19
|
+
}
|
|
20
|
+
return next();
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=middleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../src/middleware.ts"],"names":[],"mappings":"AAQA,4DAA4D;AAC5D,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,UAAsC,EACtC,MAAwB;IAExB,IAAI,OAAO,GAAG,MAAM,CAAC;IACrB,KAAK,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC;QAC3B,IAAI,CAAC,CAAC,eAAe;YAAE,OAAO,GAAG,MAAM,CAAC,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,0GAA0G;AAC1G,MAAM,UAAU,UAAU,CACxB,UAAsC,EACtC,MAAwB,EACxB,KAAwC;IAExC,IAAI,IAAI,GAAG,KAAK,CAAC;IACjB,KAAK,MAAM,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG,CAAC,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;QACnC,IAAI,CAAC,IAAI;YAAE,SAAS;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC;QACnB,IAAI,GAAG,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;IACvF,CAAC;IACD,OAAO,IAAI,EAAE,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Middleware composition: the first middleware is outermost (SDK plan §3.2).\n *\n * `transformParams` runs first to last, each seeing the previous one's result. `wrapStream` nests the same way, so the\n * first middleware's wrapper sees every event the inner ones pass on, retries included.\n */\nimport type { GatewayEvent, MiddlewareParams, ModelMiddleware } from \"./runtime-types.js\";\n\n/** Applies each middleware's `transformParams` in order. */\nexport async function transformParams(\n middleware: readonly ModelMiddleware[],\n params: MiddlewareParams,\n): Promise<MiddlewareParams> {\n let current = params;\n for (const m of middleware) {\n if (m.transformParams) current = await m.transformParams(current);\n }\n return current;\n}\n\n/** Nests each middleware's `wrapStream` around `inner`, first outermost, and starts the outermost one. */\nexport function wrapStream(\n middleware: readonly ModelMiddleware[],\n params: MiddlewareParams,\n inner: () => AsyncIterable<GatewayEvent>,\n): AsyncIterable<GatewayEvent> {\n let next = inner;\n for (const m of [...middleware].reverse()) {\n const wrap = m.wrapStream?.bind(m);\n if (!wrap) continue;\n const below = next;\n next = () => wrap({ next: below, context: params.context, options: params.options });\n }\n return next();\n}\n"]}
|
package/dist/names.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The canonical tool-name rule: 1 to 64 ASCII letters, digits, underscores or hyphens. It is the strictest
|
|
3
|
+
* intersection of the first providers' rules, so a canonical name reaches either of them unchanged.
|
|
4
|
+
*/
|
|
5
|
+
export declare const CANONICAL_TOOL_NAME: RegExp;
|
|
6
|
+
/** True when `name` meets the canonical tool-name rule. */
|
|
7
|
+
export declare function isCanonicalName(name: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Throws a `GatewayError` with code `invalid_tool_name` unless `name` meets the canonical rule, 1 to 64 characters
|
|
10
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`. Namespaced names such as `mcp__<server>__<tool>` follow the same rule.
|
|
11
|
+
*/
|
|
12
|
+
export declare function assertCanonicalName(name: string): void;
|
|
13
|
+
/** One wire protocol's rule for tool names, copied from the provider's API reference. */
|
|
14
|
+
export interface ToolNameRule {
|
|
15
|
+
/** The wire protocol the rule belongs to, such as `"anthropic-messages"`. */
|
|
16
|
+
readonly api: string;
|
|
17
|
+
/** The allowed characters, as the body of a regular-expression character class, such as `"A-Za-z0-9_-"`. */
|
|
18
|
+
readonly characters: string;
|
|
19
|
+
/** The longest name the protocol accepts, in characters. */
|
|
20
|
+
readonly maxLength: number;
|
|
21
|
+
/** The API reference page the rule was copied from. */
|
|
22
|
+
readonly source: string;
|
|
23
|
+
/** The date the rule was checked against `source`, as `YYYY-MM-DD`. */
|
|
24
|
+
readonly checkedOn: string;
|
|
25
|
+
}
|
|
26
|
+
/** The tool-name rules of the two first wire protocols, Anthropic Messages and OpenAI Chat Completions. Frozen. */
|
|
27
|
+
export declare const TOOL_NAME_RULES: {
|
|
28
|
+
readonly anthropicMessages: ToolNameRule;
|
|
29
|
+
readonly openaiChat: ToolNameRule;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* A run's map between canonical tool names and one protocol's wire names. `sanitize()` gives the wire name for a
|
|
33
|
+
* tool, and `restore()` turns a wire name the model sent back into the tool's name.
|
|
34
|
+
*
|
|
35
|
+
* No two wire names are equal or differ only in case, because neither first provider says whether tool names are
|
|
36
|
+
* case-sensitive. Of the names passed to `createToolNameMap()` up front, one that meets the rule keeps itself
|
|
37
|
+
* unless it differs only in case from a name that sorts before it. Their wire names depend only on the set of
|
|
38
|
+
* names, not on its order or on the order of `sanitize()` calls. A name that `sanitize()` first sees later keeps
|
|
39
|
+
* itself if it meets the rule and no issued wire name matches it, ignoring case. Otherwise it gets a salted hash
|
|
40
|
+
* suffix: a hash of the name and an attempt counter. Every name keeps its first wire name for the life of the map,
|
|
41
|
+
* because that wire name may already have been sent.
|
|
42
|
+
*/
|
|
43
|
+
export interface ToolNameMap {
|
|
44
|
+
/**
|
|
45
|
+
* The wire name for `name`. A name that meets the rule comes back unchanged unless an issued wire name matches it,
|
|
46
|
+
* ignoring case. Any other name has its disallowed characters replaced by `_`, is cut to fit, and ends in `_` and
|
|
47
|
+
* an 8-digit hex hash. The map first hashes the name alone. If that wire name is taken, it salts the hash with an
|
|
48
|
+
* attempt counter, counting up until the wire name is free, so two names never share a wire name. One map always
|
|
49
|
+
* gives one name the same wire name.
|
|
50
|
+
*/
|
|
51
|
+
sanitize(name: string): string;
|
|
52
|
+
/**
|
|
53
|
+
* The name that the map turned into `wireName`, or `undefined` when the map never issued `wireName`. A tool name
|
|
54
|
+
* the model invented therefore never resolves to a tool, even when it equals a tool's name before sanitising.
|
|
55
|
+
*/
|
|
56
|
+
restore(wireName: string): string | undefined;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* FNV-1a over UTF-16 code units, as 8 hex digits: synchronous and portable, so sanitising needs neither Web Crypto
|
|
60
|
+
* nor a Promise. Internal to the gateway; adapters also use it to fingerprint a conversation.
|
|
61
|
+
*/
|
|
62
|
+
export declare function fnv1a(text: string): string;
|
|
63
|
+
/**
|
|
64
|
+
* Creates the map between canonical names and the wire names of the protocol that `rule` describes. Pass the run's
|
|
65
|
+
* tool names as `names`, so their wire names do not depend on the order the tools are registered or sanitised in.
|
|
66
|
+
* Keep one map for a whole run, so every request sends the same wire names and the prompt cache stays valid.
|
|
67
|
+
*
|
|
68
|
+
* Throws a `GatewayError` with code `invalid_options` when the rule is too short to hold a hash suffix, its
|
|
69
|
+
* characters are not a plain character-class body, or they exclude `_` or a hex digit. In `characters`, a `-` must
|
|
70
|
+
* be the first or last character or join two digits, two lowercase letters or two uppercase letters.
|
|
71
|
+
*/
|
|
72
|
+
export declare function createToolNameMap(rule: ToolNameRule, names?: Iterable<string>): ToolNameMap;
|
package/dist/names.js
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool names: the canonical rule every tool name meets, each wire protocol's own rule, and a reversible map from
|
|
3
|
+
* canonical names to wire names. `names.md` beside this file holds the per-provider table and its sources.
|
|
4
|
+
*/
|
|
5
|
+
import { GatewayError } from "./errors.js";
|
|
6
|
+
/**
|
|
7
|
+
* The canonical tool-name rule: 1 to 64 ASCII letters, digits, underscores or hyphens. It is the strictest
|
|
8
|
+
* intersection of the first providers' rules, so a canonical name reaches either of them unchanged.
|
|
9
|
+
*/
|
|
10
|
+
export const CANONICAL_TOOL_NAME = Object.freeze(/^[A-Za-z0-9_-]{1,64}$/);
|
|
11
|
+
/** True when `name` meets the canonical tool-name rule. */
|
|
12
|
+
export function isCanonicalName(name) {
|
|
13
|
+
return CANONICAL_TOOL_NAME.test(name);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Throws a `GatewayError` with code `invalid_tool_name` unless `name` meets the canonical rule, 1 to 64 characters
|
|
17
|
+
* from `A-Z`, `a-z`, `0-9`, `_` and `-`. Namespaced names such as `mcp__<server>__<tool>` follow the same rule.
|
|
18
|
+
*/
|
|
19
|
+
export function assertCanonicalName(name) {
|
|
20
|
+
if (isCanonicalName(name))
|
|
21
|
+
return;
|
|
22
|
+
const shown = name.length > 80 ? `${JSON.stringify(name.slice(0, 80))}…` : JSON.stringify(name);
|
|
23
|
+
throw new GatewayError("invalid_tool_name", `tool name ${shown} (${name.length} characters) must be 1 to 64 characters from A-Z, a-z, 0-9, _ and -`);
|
|
24
|
+
}
|
|
25
|
+
// Each rule is copied from the provider's own reference, as of November 2026; names.md records the exact wording.
|
|
26
|
+
/** The tool-name rules of the two first wire protocols, Anthropic Messages and OpenAI Chat Completions. Frozen. */
|
|
27
|
+
export const TOOL_NAME_RULES = Object.freeze({
|
|
28
|
+
// Messages API reference, Tool object: `pattern: ^[a-zA-Z0-9_-]{1,128}$`.
|
|
29
|
+
anthropicMessages: Object.freeze({
|
|
30
|
+
api: "anthropic-messages",
|
|
31
|
+
characters: "A-Za-z0-9_-",
|
|
32
|
+
maxLength: 128,
|
|
33
|
+
source: "https://platform.claude.com/docs/en/api/messages/create",
|
|
34
|
+
checkedOn: "2026-11-19",
|
|
35
|
+
}),
|
|
36
|
+
// FunctionDefinition.name: "Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64".
|
|
37
|
+
// OpenAI's TypeScript SDK at v7.49.0 carries the same words in src/resources/shared.ts.
|
|
38
|
+
openaiChat: Object.freeze({
|
|
39
|
+
api: "openai-chat",
|
|
40
|
+
characters: "A-Za-z0-9_-",
|
|
41
|
+
maxLength: 64,
|
|
42
|
+
source: "https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create",
|
|
43
|
+
checkedOn: "2026-11-19",
|
|
44
|
+
}),
|
|
45
|
+
});
|
|
46
|
+
const HASH_SUFFIX_LENGTH = 9; // "_" and 8 hex digits
|
|
47
|
+
const HASH_ALPHABET = "_0123456789abcdef";
|
|
48
|
+
/**
|
|
49
|
+
* FNV-1a over UTF-16 code units, as 8 hex digits: synchronous and portable, so sanitising needs neither Web Crypto
|
|
50
|
+
* nor a Promise. Internal to the gateway; adapters also use it to fingerprint a conversation.
|
|
51
|
+
*/
|
|
52
|
+
export function fnv1a(text) {
|
|
53
|
+
let hash = 0x811c9dc5;
|
|
54
|
+
for (let i = 0; i < text.length; i++) {
|
|
55
|
+
hash ^= text.charCodeAt(i);
|
|
56
|
+
hash = Math.imul(hash, 0x01000193);
|
|
57
|
+
}
|
|
58
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
59
|
+
}
|
|
60
|
+
const isDigit = (c) => c >= "0" && c <= "9";
|
|
61
|
+
const isLower = (c) => c >= "a" && c <= "z";
|
|
62
|
+
const isUpper = (c) => c >= "A" && c <= "Z";
|
|
63
|
+
// A stray "-" silently makes a range, as "9-_" would in "a-z0-9-_", so "-" may only start or end the characters
|
|
64
|
+
// or join two digits, two lowercase letters or two uppercase letters.
|
|
65
|
+
function checkDashes(rule) {
|
|
66
|
+
const chars = rule.characters;
|
|
67
|
+
for (let i = 0; i < chars.length;) {
|
|
68
|
+
const from = chars.charAt(i);
|
|
69
|
+
if (chars.charAt(i + 1) === "-" && i + 2 < chars.length && from !== "-") {
|
|
70
|
+
const to = chars.charAt(i + 2);
|
|
71
|
+
const sameKind = (isDigit(from) && isDigit(to)) || (isLower(from) && isLower(to)) || (isUpper(from) && isUpper(to));
|
|
72
|
+
if (!sameKind) {
|
|
73
|
+
throw new GatewayError("invalid_options", `tool-name rule ${rule.api}: range ${from}-${to} must join two digits or two letters of the same case`);
|
|
74
|
+
}
|
|
75
|
+
i += 3;
|
|
76
|
+
}
|
|
77
|
+
else if (from === "-" && i !== 0 && i !== chars.length - 1) {
|
|
78
|
+
throw new GatewayError("invalid_options", `tool-name rule ${rule.api}: a - outside a range must be the first or last character`);
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
i += 1;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function checkRule(rule) {
|
|
86
|
+
if (!Number.isInteger(rule.maxLength) || rule.maxLength <= HASH_SUFFIX_LENGTH) {
|
|
87
|
+
throw new GatewayError("invalid_options", `tool-name rule ${rule.api}: maxLength must be an integer above 9`);
|
|
88
|
+
}
|
|
89
|
+
// The characters are pasted into a character class, where a leading ^ negates it and a bracket or backslash
|
|
90
|
+
// changes where it ends or what it means, so only plain characters and ranges are accepted.
|
|
91
|
+
if (rule.characters.startsWith("^") || /[[\\\]]/.test(rule.characters)) {
|
|
92
|
+
throw new GatewayError("invalid_options", `tool-name rule ${rule.api}: characters must not start with ^ or contain [, ] or a backslash`);
|
|
93
|
+
}
|
|
94
|
+
checkDashes(rule);
|
|
95
|
+
let valid;
|
|
96
|
+
let invalid;
|
|
97
|
+
let allowed;
|
|
98
|
+
try {
|
|
99
|
+
valid = new RegExp(`^[${rule.characters}]{1,${rule.maxLength}}$`);
|
|
100
|
+
invalid = new RegExp(`[^${rule.characters}]`, "g");
|
|
101
|
+
allowed = new RegExp(`^[${rule.characters}]+$`);
|
|
102
|
+
}
|
|
103
|
+
catch (cause) {
|
|
104
|
+
throw new GatewayError("invalid_options", `tool-name rule ${rule.api}: characters is not a character class`, {
|
|
105
|
+
cause,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
// Every character of a hash suffix must be allowed, whatever the length limit.
|
|
109
|
+
if (!allowed.test(HASH_ALPHABET)) {
|
|
110
|
+
throw new GatewayError("invalid_options", `tool-name rule ${rule.api}: characters must allow _, 0-9 and a-f`);
|
|
111
|
+
}
|
|
112
|
+
return { valid, invalid };
|
|
113
|
+
}
|
|
114
|
+
// Sorting by UTF-16 code units gives one order for a set of names on every runtime.
|
|
115
|
+
function byCodeUnits(a, b) {
|
|
116
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Creates the map between canonical names and the wire names of the protocol that `rule` describes. Pass the run's
|
|
120
|
+
* tool names as `names`, so their wire names do not depend on the order the tools are registered or sanitised in.
|
|
121
|
+
* Keep one map for a whole run, so every request sends the same wire names and the prompt cache stays valid.
|
|
122
|
+
*
|
|
123
|
+
* Throws a `GatewayError` with code `invalid_options` when the rule is too short to hold a hash suffix, its
|
|
124
|
+
* characters are not a plain character-class body, or they exclude `_` or a hex digit. In `characters`, a `-` must
|
|
125
|
+
* be the first or last character or join two digits, two lowercase letters or two uppercase letters.
|
|
126
|
+
*/
|
|
127
|
+
export function createToolNameMap(rule, names = []) {
|
|
128
|
+
const { valid, invalid } = checkRule(rule);
|
|
129
|
+
const toWire = new Map();
|
|
130
|
+
const fromWire = new Map();
|
|
131
|
+
// Issued wire names, lowercased, so no two wire names differ only in case.
|
|
132
|
+
const issuedFolded = new Set();
|
|
133
|
+
const isTaken = (wire) => issuedFolded.has(wire.toLowerCase());
|
|
134
|
+
function hashed(name, attempt) {
|
|
135
|
+
const hash = fnv1a(attempt === 0 ? name : `${name}\u0000${attempt}`);
|
|
136
|
+
return `${name.replace(invalid, "_").slice(0, rule.maxLength - HASH_SUFFIX_LENGTH)}_${hash}`;
|
|
137
|
+
}
|
|
138
|
+
function assign(name, wire) {
|
|
139
|
+
toWire.set(name, wire);
|
|
140
|
+
fromWire.set(wire, name);
|
|
141
|
+
issuedFolded.add(wire.toLowerCase());
|
|
142
|
+
return wire;
|
|
143
|
+
}
|
|
144
|
+
function sanitize(name) {
|
|
145
|
+
const known = toWire.get(name);
|
|
146
|
+
if (known !== undefined)
|
|
147
|
+
return known;
|
|
148
|
+
const meetsRule = valid.test(name);
|
|
149
|
+
if (meetsRule && !isTaken(name))
|
|
150
|
+
return assign(name, name);
|
|
151
|
+
// A name that meets the rule but whose string, ignoring case, was already issued starts salted: the earlier
|
|
152
|
+
// wire name may already have been sent, so it must not move.
|
|
153
|
+
let attempt = meetsRule ? 1 : 0;
|
|
154
|
+
let wire = hashed(name, attempt);
|
|
155
|
+
// A taken wire name belongs to another tool, so salt the hash until it is free.
|
|
156
|
+
while (isTaken(wire))
|
|
157
|
+
wire = hashed(name, ++attempt);
|
|
158
|
+
return assign(name, wire);
|
|
159
|
+
}
|
|
160
|
+
// Names that meet the rule claim themselves first, so a hashed name that collides with one is the one salted. Of
|
|
161
|
+
// names that differ only in case, the first in sorted order claims itself and the others are salted.
|
|
162
|
+
const unique = [...new Set(names)].sort(byCodeUnits);
|
|
163
|
+
for (const name of unique)
|
|
164
|
+
if (valid.test(name) && !isTaken(name))
|
|
165
|
+
assign(name, name);
|
|
166
|
+
for (const name of unique)
|
|
167
|
+
sanitize(name);
|
|
168
|
+
return {
|
|
169
|
+
sanitize,
|
|
170
|
+
restore(wireName) {
|
|
171
|
+
return fromWire.get(wireName);
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
//# sourceMappingURL=names.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"names.js","sourceRoot":"","sources":["../src/names.ts"],"names":[],"mappings":"AAAA;;;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I,CAAC,OAAO,CAAC,IAAI,CAAC;YAAE,OAAO,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC3D,4GAA4G;QAC5G,6DAA6D;QAC7D,IAAI,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAChC,IAAI,IAAI,GAAG,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QACjC,gFAAgF;QAChF,OAAO,OAAO,CAAC,IAAI,CAAC;YAAE,IAAI,GAAG,MAAM,CAAC,IAAI,EAAE,EAAE,OAAO,CAAC,CAAC;QACrD,OAAO,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAC5B,CAAC;IAED,iHAAiH;IACjH,qGAAqG;IACrG,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACrD,KAAK,MAAM,IAAI,IAAI,MAAM;QAAE,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;YAAE,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACtF,KAAK,MAAM,IAAI,IAAI,MAAM;QAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;IAE1C,OAAO;QACL,QAAQ;QACR,OAAO,CAAC,QAAQ;YACd,OAAO,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAChC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Tool names: the canonical rule every tool name meets, each wire protocol's own rule, and a reversible map from\n * canonical names to wire names. `names.md` beside this file holds the per-provider table and its sources.\n */\nimport { GatewayError } from \"./errors.js\";\n\n/**\n * The canonical tool-name rule: 1 to 64 ASCII letters, digits, underscores or hyphens. It is the strictest\n * intersection of the first providers' rules, so a canonical name reaches either of them unchanged.\n */\nexport const CANONICAL_TOOL_NAME: RegExp = Object.freeze(/^[A-Za-z0-9_-]{1,64}$/);\n\n/** True when `name` meets the canonical tool-name rule. */\nexport function isCanonicalName(name: string): boolean {\n return CANONICAL_TOOL_NAME.test(name);\n}\n\n/**\n * Throws a `GatewayError` with code `invalid_tool_name` unless `name` meets the canonical rule, 1 to 64 characters\n * from `A-Z`, `a-z`, `0-9`, `_` and `-`. Namespaced names such as `mcp__<server>__<tool>` follow the same rule.\n */\nexport function assertCanonicalName(name: string): void {\n if (isCanonicalName(name)) return;\n const shown = name.length > 80 ? `${JSON.stringify(name.slice(0, 80))}…` : JSON.stringify(name);\n throw new GatewayError(\n \"invalid_tool_name\",\n `tool name ${shown} (${name.length} characters) must be 1 to 64 characters from A-Z, a-z, 0-9, _ and -`,\n );\n}\n\n/** One wire protocol's rule for tool names, copied from the provider's API reference. */\nexport interface ToolNameRule {\n /** The wire protocol the rule belongs to, such as `\"anthropic-messages\"`. */\n readonly api: string;\n /** The allowed characters, as the body of a regular-expression character class, such as `\"A-Za-z0-9_-\"`. */\n readonly characters: string;\n /** The longest name the protocol accepts, in characters. */\n readonly maxLength: number;\n /** The API reference page the rule was copied from. */\n readonly source: string;\n /** The date the rule was checked against `source`, as `YYYY-MM-DD`. */\n readonly checkedOn: string;\n}\n\n// Each rule is copied from the provider's own reference, as of November 2026; names.md records the exact wording.\n/** The tool-name rules of the two first wire protocols, Anthropic Messages and OpenAI Chat Completions. Frozen. */\nexport const TOOL_NAME_RULES: {\n readonly anthropicMessages: ToolNameRule;\n readonly openaiChat: ToolNameRule;\n} = Object.freeze({\n // Messages API reference, Tool object: `pattern: ^[a-zA-Z0-9_-]{1,128}$`.\n anthropicMessages: Object.freeze({\n api: \"anthropic-messages\",\n characters: \"A-Za-z0-9_-\",\n maxLength: 128,\n source: \"https://platform.claude.com/docs/en/api/messages/create\",\n checkedOn: \"2026-11-19\",\n }),\n // FunctionDefinition.name: \"Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64\".\n // OpenAI's TypeScript SDK at v7.49.0 carries the same words in src/resources/shared.ts.\n openaiChat: Object.freeze({\n api: \"openai-chat\",\n characters: \"A-Za-z0-9_-\",\n maxLength: 64,\n source: \"https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create\",\n checkedOn: \"2026-11-19\",\n }),\n});\n\n/**\n * A run's map between canonical tool names and one protocol's wire names. `sanitize()` gives the wire name for a\n * tool, and `restore()` turns a wire name the model sent back into the tool's name.\n *\n * No two wire names are equal or differ only in case, because neither first provider says whether tool names are\n * case-sensitive. Of the names passed to `createToolNameMap()` up front, one that meets the rule keeps itself\n * unless it differs only in case from a name that sorts before it. Their wire names depend only on the set of\n * names, not on its order or on the order of `sanitize()` calls. A name that `sanitize()` first sees later keeps\n * itself if it meets the rule and no issued wire name matches it, ignoring case. Otherwise it gets a salted hash\n * suffix: a hash of the name and an attempt counter. Every name keeps its first wire name for the life of the map,\n * because that wire name may already have been sent.\n */\nexport interface ToolNameMap {\n /**\n * The wire name for `name`. A name that meets the rule comes back unchanged unless an issued wire name matches it,\n * ignoring case. Any other name has its disallowed characters replaced by `_`, is cut to fit, and ends in `_` and\n * an 8-digit hex hash. The map first hashes the name alone. If that wire name is taken, it salts the hash with an\n * attempt counter, counting up until the wire name is free, so two names never share a wire name. One map always\n * gives one name the same wire name.\n */\n sanitize(name: string): string;\n /**\n * The name that the map turned into `wireName`, or `undefined` when the map never issued `wireName`. A tool name\n * the model invented therefore never resolves to a tool, even when it equals a tool's name before sanitising.\n */\n restore(wireName: string): string | undefined;\n}\n\nconst HASH_SUFFIX_LENGTH = 9; // \"_\" and 8 hex digits\nconst HASH_ALPHABET = \"_0123456789abcdef\";\n\n/**\n * FNV-1a over UTF-16 code units, as 8 hex digits: synchronous and portable, so sanitising needs neither Web Crypto\n * nor a Promise. Internal to the gateway; adapters also use it to fingerprint a conversation.\n */\nexport function fnv1a(text: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < text.length; i++) {\n hash ^= text.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nconst isDigit = (c: string): boolean => c >= \"0\" && c <= \"9\";\nconst isLower = (c: string): boolean => c >= \"a\" && c <= \"z\";\nconst isUpper = (c: string): boolean => c >= \"A\" && c <= \"Z\";\n\n// A stray \"-\" silently makes a range, as \"9-_\" would in \"a-z0-9-_\", so \"-\" may only start or end the characters\n// or join two digits, two lowercase letters or two uppercase letters.\nfunction checkDashes(rule: ToolNameRule): void {\n const chars = rule.characters;\n for (let i = 0; i < chars.length; ) {\n const from = chars.charAt(i);\n if (chars.charAt(i + 1) === \"-\" && i + 2 < chars.length && from !== \"-\") {\n const to = chars.charAt(i + 2);\n const sameKind =\n (isDigit(from) && isDigit(to)) || (isLower(from) && isLower(to)) || (isUpper(from) && isUpper(to));\n if (!sameKind) {\n throw new GatewayError(\n \"invalid_options\",\n `tool-name rule ${rule.api}: range ${from}-${to} must join two digits or two letters of the same case`,\n );\n }\n i += 3;\n } else if (from === \"-\" && i !== 0 && i !== chars.length - 1) {\n throw new GatewayError(\n \"invalid_options\",\n `tool-name rule ${rule.api}: a - outside a range must be the first or last character`,\n );\n } else {\n i += 1;\n }\n }\n}\n\nfunction checkRule(rule: ToolNameRule): { valid: RegExp; invalid: RegExp } {\n if (!Number.isInteger(rule.maxLength) || rule.maxLength <= HASH_SUFFIX_LENGTH) {\n throw new GatewayError(\"invalid_options\", `tool-name rule ${rule.api}: maxLength must be an integer above 9`);\n }\n // The characters are pasted into a character class, where a leading ^ negates it and a bracket or backslash\n // changes where it ends or what it means, so only plain characters and ranges are accepted.\n if (rule.characters.startsWith(\"^\") || /[[\\\\\\]]/.test(rule.characters)) {\n throw new GatewayError(\n \"invalid_options\",\n `tool-name rule ${rule.api}: characters must not start with ^ or contain [, ] or a backslash`,\n );\n }\n checkDashes(rule);\n let valid: RegExp;\n let invalid: RegExp;\n let allowed: RegExp;\n try {\n valid = new RegExp(`^[${rule.characters}]{1,${rule.maxLength}}$`);\n invalid = new RegExp(`[^${rule.characters}]`, \"g\");\n allowed = new RegExp(`^[${rule.characters}]+$`);\n } catch (cause) {\n throw new GatewayError(\"invalid_options\", `tool-name rule ${rule.api}: characters is not a character class`, {\n cause,\n });\n }\n // Every character of a hash suffix must be allowed, whatever the length limit.\n if (!allowed.test(HASH_ALPHABET)) {\n throw new GatewayError(\"invalid_options\", `tool-name rule ${rule.api}: characters must allow _, 0-9 and a-f`);\n }\n return { valid, invalid };\n}\n\n// Sorting by UTF-16 code units gives one order for a set of names on every runtime.\nfunction byCodeUnits(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * Creates the map between canonical names and the wire names of the protocol that `rule` describes. Pass the run's\n * tool names as `names`, so their wire names do not depend on the order the tools are registered or sanitised in.\n * Keep one map for a whole run, so every request sends the same wire names and the prompt cache stays valid.\n *\n * Throws a `GatewayError` with code `invalid_options` when the rule is too short to hold a hash suffix, its\n * characters are not a plain character-class body, or they exclude `_` or a hex digit. In `characters`, a `-` must\n * be the first or last character or join two digits, two lowercase letters or two uppercase letters.\n */\nexport function createToolNameMap(rule: ToolNameRule, names: Iterable<string> = []): ToolNameMap {\n const { valid, invalid } = checkRule(rule);\n const toWire = new Map<string, string>();\n const fromWire = new Map<string, string>();\n // Issued wire names, lowercased, so no two wire names differ only in case.\n const issuedFolded = new Set<string>();\n const isTaken = (wire: string): boolean => issuedFolded.has(wire.toLowerCase());\n\n function hashed(name: string, attempt: number): string {\n const hash = fnv1a(attempt === 0 ? name : `${name}\\u0000${attempt}`);\n return `${name.replace(invalid, \"_\").slice(0, rule.maxLength - HASH_SUFFIX_LENGTH)}_${hash}`;\n }\n\n function assign(name: string, wire: string): string {\n toWire.set(name, wire);\n fromWire.set(wire, name);\n issuedFolded.add(wire.toLowerCase());\n return wire;\n }\n\n function sanitize(name: string): string {\n const known = toWire.get(name);\n if (known !== undefined) return known;\n const meetsRule = valid.test(name);\n if (meetsRule && !isTaken(name)) return assign(name, name);\n // A name that meets the rule but whose string, ignoring case, was already issued starts salted: the earlier\n // wire name may already have been sent, so it must not move.\n let attempt = meetsRule ? 1 : 0;\n let wire = hashed(name, attempt);\n // A taken wire name belongs to another tool, so salt the hash until it is free.\n while (isTaken(wire)) wire = hashed(name, ++attempt);\n return assign(name, wire);\n }\n\n // Names that meet the rule claim themselves first, so a hashed name that collides with one is the one salted. Of\n // names that differ only in case, the first in sorted order claims itself and the others are salted.\n const unique = [...new Set(names)].sort(byCodeUnits);\n for (const name of unique) if (valid.test(name) && !isTaken(name)) assign(name, name);\n for (const name of unique) sanitize(name);\n\n return {\n sanitize,\n restore(wireName) {\n return fromWire.get(wireName);\n },\n };\n}\n"]}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ProviderConfig, Transport } from "./runtime-types.js";
|
|
2
|
+
/** A `ProviderConfig` with every default filled in. */
|
|
3
|
+
export interface ResolvedProviderConfig {
|
|
4
|
+
readonly apiKey: string;
|
|
5
|
+
readonly baseURL: string;
|
|
6
|
+
readonly transport: Transport;
|
|
7
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Checks a provider config and fills in its defaults. Throws a `GatewayError` with code `missing_api_key` when the
|
|
11
|
+
* key is missing or empty, so the adapter factory fails before any request is made.
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolveProviderConfig(config: ProviderConfig, defaults: {
|
|
14
|
+
baseURL: string;
|
|
15
|
+
}): ResolvedProviderConfig;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `resolveProviderConfig()`: the one place adapters read their `ProviderConfig` (SDK decision 13; agent-SDK guide §9).
|
|
3
|
+
* It reads nothing from the environment, so the only key an adapter can send is the one its caller passed.
|
|
4
|
+
*/
|
|
5
|
+
import { GatewayError } from "./errors.js";
|
|
6
|
+
// Looked up on each request, not when the adapter is made, so a fetch installed later (a test guard) still applies.
|
|
7
|
+
const defaultTransport = (request) => globalThis.fetch(request);
|
|
8
|
+
/**
|
|
9
|
+
* Checks a provider config and fills in its defaults. Throws a `GatewayError` with code `missing_api_key` when the
|
|
10
|
+
* key is missing or empty, so the adapter factory fails before any request is made.
|
|
11
|
+
*/
|
|
12
|
+
export function resolveProviderConfig(config, defaults) {
|
|
13
|
+
if (typeof config?.apiKey !== "string" || config.apiKey.trim() === "") {
|
|
14
|
+
throw new GatewayError("missing_api_key", "ProviderConfig.apiKey is missing or empty. Pass the key explicitly; the gateway never reads one from the environment.");
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
apiKey: config.apiKey,
|
|
18
|
+
baseURL: config.baseURL ?? defaults.baseURL,
|
|
19
|
+
transport: config.transport ?? defaultTransport,
|
|
20
|
+
headers: { ...config.headers },
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=provider-config.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-config.js","sourceRoot":"","sources":["../src/provider-config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAW3C,oHAAoH;AACpH,MAAM,gBAAgB,GAAc,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AAE3E;;;GAGG;AACH,MAAM,UAAU,qBAAqB,CAAC,MAAsB,EAAE,QAA6B;IACzF,IAAI,OAAO,MAAM,EAAE,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACtE,MAAM,IAAI,YAAY,CACpB,iBAAiB,EACjB,uHAAuH,CACxH,CAAC;IACJ,CAAC;IACD,OAAO;QACL,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,OAAO,EAAE,MAAM,CAAC,OAAO,IAAI,QAAQ,CAAC,OAAO;QAC3C,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,gBAAgB;QAC/C,OAAO,EAAE,EAAE,GAAG,MAAM,CAAC,OAAO,EAAE;KAC/B,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `resolveProviderConfig()`: the one place adapters read their `ProviderConfig` (SDK decision 13; agent-SDK guide §9).\n * It reads nothing from the environment, so the only key an adapter can send is the one its caller passed.\n */\nimport { GatewayError } from \"./errors.js\";\nimport type { ProviderConfig, Transport } from \"./runtime-types.js\";\n\n/** A `ProviderConfig` with every default filled in. */\nexport interface ResolvedProviderConfig {\n readonly apiKey: string;\n readonly baseURL: string;\n readonly transport: Transport;\n readonly headers: Readonly<Record<string, string>>;\n}\n\n// Looked up on each request, not when the adapter is made, so a fetch installed later (a test guard) still applies.\nconst defaultTransport: Transport = (request) => globalThis.fetch(request);\n\n/**\n * Checks a provider config and fills in its defaults. Throws a `GatewayError` with code `missing_api_key` when the\n * key is missing or empty, so the adapter factory fails before any request is made.\n */\nexport function resolveProviderConfig(config: ProviderConfig, defaults: { baseURL: string }): ResolvedProviderConfig {\n if (typeof config?.apiKey !== \"string\" || config.apiKey.trim() === \"\") {\n throw new GatewayError(\n \"missing_api_key\",\n \"ProviderConfig.apiKey is missing or empty. Pass the key explicitly; the gateway never reads one from the environment.\",\n );\n }\n return {\n apiKey: config.apiKey,\n baseURL: config.baseURL ?? defaults.baseURL,\n transport: config.transport ?? defaultTransport,\n headers: { ...config.headers },\n };\n}\n"]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One attempt of one model call, with `onPayload` and the request dump wired in (agent-SDK guide §2: practitioners
|
|
3
|
+
* ask to see the full request of any step).
|
|
4
|
+
*
|
|
5
|
+
* The gateway hands the adapter its own `onPayload`, which runs the caller's hook and then dumps the body it returns,
|
|
6
|
+
* so the dump shows what was actually sent. An adapter calls `onPayload` once per HTTP request, so an attempt that
|
|
7
|
+
* sends two requests, such as the Anthropic adapter's retry with `drop_block`, is dumped twice, both times with the
|
|
8
|
+
* attempt's number. An adapter with no wire body never calls `onPayload`; its dump, with `body: undefined`, goes out
|
|
9
|
+
* before its first event that is neither `start` nor `warning` instead. An adapter may yield a `start` and a
|
|
10
|
+
* `warning` before it sends, as the Anthropic adapter does with its sampling warnings, so skipping them keeps one
|
|
11
|
+
* dump per HTTP request, with the body. Either way every attempt is dumped before any of its content reaches the
|
|
12
|
+
* caller.
|
|
13
|
+
*/
|
|
14
|
+
import type { ModelCallOptions, RequestDump } from "./runtime-types.js";
|
|
15
|
+
import type { ModelAdapter, ModelEvent } from "./spec.js";
|
|
16
|
+
import type { ModelCaps, ModelContext, ModelRef } from "./types.js";
|
|
17
|
+
/** One model call's request, which every attempt of the call sends again. */
|
|
18
|
+
export interface AttemptRequest {
|
|
19
|
+
readonly adapter: ModelAdapter;
|
|
20
|
+
readonly ref: ModelRef;
|
|
21
|
+
readonly context: ModelContext;
|
|
22
|
+
readonly options: ModelCallOptions;
|
|
23
|
+
/** The model's resolved caps, which every attempt hands the adapter as `options.caps`. */
|
|
24
|
+
readonly caps: ModelCaps;
|
|
25
|
+
readonly onRequest: ((dump: RequestDump) => void) | undefined;
|
|
26
|
+
}
|
|
27
|
+
/** Starts attempt `n` of the request. Each call sends a fresh request to the adapter. */
|
|
28
|
+
export declare function startAttempt(request: AttemptRequest, n: number): AsyncIterable<ModelEvent>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
function dumpedOptions(options) {
|
|
2
|
+
// An untyped caller may still pass `caps`; the dump leaves it out, like the adapter, which gets the resolved caps.
|
|
3
|
+
const { signal: _signal, onPayload: _onPayload, caps: _caps, ...rest } = options;
|
|
4
|
+
return rest;
|
|
5
|
+
}
|
|
6
|
+
async function* dumpBeforeFirstEvent(events, ensureDumped) {
|
|
7
|
+
try {
|
|
8
|
+
for await (const event of events) {
|
|
9
|
+
// `start` and `warning` may come before the adapter builds and sends its body; content never does.
|
|
10
|
+
if (event.type !== "start" && event.type !== "warning")
|
|
11
|
+
ensureDumped();
|
|
12
|
+
yield event;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
finally {
|
|
16
|
+
// An attempt that throws before its first event still leaves a record of what it was asked to send.
|
|
17
|
+
ensureDumped();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** A copy of the dump, or the dump itself when part of it can't be cloned, such as a function in `providerOptions`. */
|
|
21
|
+
function copyOf(dump) {
|
|
22
|
+
try {
|
|
23
|
+
return structuredClone(dump);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return dump;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Starts attempt `n` of the request. Each call sends a fresh request to the adapter. */
|
|
30
|
+
export function startAttempt(request, n) {
|
|
31
|
+
const { adapter, ref, context, options, caps, onRequest } = request;
|
|
32
|
+
let dumped = false;
|
|
33
|
+
const dump = (body) => {
|
|
34
|
+
dumped = true;
|
|
35
|
+
// A copy, so a caller that changes the context after the call can't rewrite what an earlier attempt sent.
|
|
36
|
+
if (onRequest)
|
|
37
|
+
onRequest(copyOf({ attempt: n, model: ref, context, options: dumpedOptions(options), body }));
|
|
38
|
+
};
|
|
39
|
+
const callerHook = options.onPayload;
|
|
40
|
+
const onPayload = (body) => {
|
|
41
|
+
const replaced = callerHook ? callerHook(body) : undefined;
|
|
42
|
+
const sent = replaced === undefined ? body : replaced;
|
|
43
|
+
dump(sent);
|
|
44
|
+
return sent;
|
|
45
|
+
};
|
|
46
|
+
const events = adapter.stream(ref, context, { ...options, caps, onPayload });
|
|
47
|
+
return dumpBeforeFirstEvent(events, () => {
|
|
48
|
+
if (!dumped)
|
|
49
|
+
dump(undefined);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=request-dump.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-dump.js","sourceRoot":"","sources":["../src/request-dump.ts"],"names":[],"mappings":"AA4BA,SAAS,aAAa,CAAC,OAAyB;IAC9C,mHAAmH;IACnH,MAAM,EAA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AG,OAAO,CAAC,SAAS,CAAC;IACrC,MAAM,SAAS,GAAG,CAAC,IAAa,EAAW,EAAE;QAC3C,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC3D,MAAM,IAAI,GAAG,QAAQ,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC;QACtD,IAAI,CAAC,IAAI,CAAC,CAAC;QACX,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IACF,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC,CAAC;IAC7E,OAAO,oBAAoB,CAAC,MAAM,EAAE,GAAG,EAAE;QACvC,IAAI,CAAC,MAAM;YAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * One attempt of one model call, with `onPayload` and the request dump wired in (agent-SDK guide §2: practitioners\n * ask to see the full request of any step).\n *\n * The gateway hands the adapter its own `onPayload`, which runs the caller's hook and then dumps the body it returns,\n * so the dump shows what was actually sent. An adapter calls `onPayload` once per HTTP request, so an attempt that\n * sends two requests, such as the Anthropic adapter's retry with `drop_block`, is dumped twice, both times with the\n * attempt's number. An adapter with no wire body never calls `onPayload`; its dump, with `body: undefined`, goes out\n * before its first event that is neither `start` nor `warning` instead. An adapter may yield a `start` and a\n * `warning` before it sends, as the Anthropic adapter does with its sampling warnings, so skipping them keeps one\n * dump per HTTP request, with the body. Either way every attempt is dumped before any of its content reaches the\n * caller.\n */\nimport type { DumpedOptions, ModelCallOptions, RequestDump } from \"./runtime-types.js\";\nimport type { ModelAdapter, ModelEvent, StreamOptions } from \"./spec.js\";\nimport type { ModelCaps, ModelContext, ModelRef } from \"./types.js\";\n\n/** One model call's request, which every attempt of the call sends again. */\nexport interface AttemptRequest {\n readonly adapter: ModelAdapter;\n readonly ref: ModelRef;\n readonly context: ModelContext;\n readonly options: ModelCallOptions;\n /** The model's resolved caps, which every attempt hands the adapter as `options.caps`. */\n readonly caps: ModelCaps;\n readonly onRequest: ((dump: RequestDump) => void) | undefined;\n}\n\nfunction dumpedOptions(options: ModelCallOptions): DumpedOptions {\n // An untyped caller may still pass `caps`; the dump leaves it out, like the adapter, which gets the resolved caps.\n const { signal: _signal, onPayload: _onPayload, caps: _caps, ...rest } = options as StreamOptions;\n return rest;\n}\n\nasync function* dumpBeforeFirstEvent(events: AsyncIterable<ModelEvent>, ensureDumped: () => void) {\n try {\n for await (const event of events) {\n // `start` and `warning` may come before the adapter builds and sends its body; content never does.\n if (event.type !== \"start\" && event.type !== \"warning\") ensureDumped();\n yield event;\n }\n } finally {\n // An attempt that throws before its first event still leaves a record of what it was asked to send.\n ensureDumped();\n }\n}\n\n/** A copy of the dump, or the dump itself when part of it can't be cloned, such as a function in `providerOptions`. */\nfunction copyOf(dump: RequestDump): RequestDump {\n try {\n return structuredClone(dump);\n } catch {\n return dump;\n }\n}\n\n/** Starts attempt `n` of the request. Each call sends a fresh request to the adapter. */\nexport function startAttempt(request: AttemptRequest, n: number): AsyncIterable<ModelEvent> {\n const { adapter, ref, context, options, caps, onRequest } = request;\n let dumped = false;\n const dump = (body: unknown): void => {\n dumped = true;\n // A copy, so a caller that changes the context after the call can't rewrite what an earlier attempt sent.\n if (onRequest) onRequest(copyOf({ attempt: n, model: ref, context, options: dumpedOptions(options), body }));\n };\n const callerHook = options.onPayload;\n const onPayload = (body: unknown): unknown => {\n const replaced = callerHook ? callerHook(body) : undefined;\n const sent = replaced === undefined ? body : replaced;\n dump(sent);\n return sent;\n };\n const events = adapter.stream(ref, context, { ...options, caps, onPayload });\n return dumpBeforeFirstEvent(events, () => {\n if (!dumped) dump(undefined);\n });\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The process-wide switch behind `allowModelRequests()` (SDK decision 14; SDK plan §5.4).
|
|
3
|
+
*
|
|
4
|
+
* Every adapter calls `assertModelRequestAllowed(transport)` before it sends a request. When tests have turned real
|
|
5
|
+
* requests off, any transport not marked as a mock throws before anything leaves the process.
|
|
6
|
+
*/
|
|
7
|
+
import type { Transport } from "./runtime-types.js";
|
|
8
|
+
/** Turns real model requests on or off for the whole process. Tests turn them off in the shared setup. */
|
|
9
|
+
export declare function setModelRequestsAllowed(allowed: boolean): void;
|
|
10
|
+
export declare function modelRequestsAreAllowed(): boolean;
|
|
11
|
+
/** Marks a transport as an in-process mock, which `allowModelRequests(false)` still lets through. */
|
|
12
|
+
export declare function markMockTransport<T extends Transport>(transport: T): T;
|
|
13
|
+
export declare function isMockTransport(transport: Transport | undefined): boolean;
|
|
14
|
+
export declare class ModelRequestsDisabledError extends Error {
|
|
15
|
+
readonly name = "ModelRequestsDisabledError";
|
|
16
|
+
}
|
|
17
|
+
/** Throws unless real requests are allowed or the transport is a mock. Adapters call it before sending. */
|
|
18
|
+
export declare function assertModelRequestAllowed(transport: Transport | undefined): void;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const MOCK_TRANSPORT = Symbol.for("buildanagent.gateway.mockTransport");
|
|
2
|
+
let modelRequestsAllowed = true;
|
|
3
|
+
/** Turns real model requests on or off for the whole process. Tests turn them off in the shared setup. */
|
|
4
|
+
export function setModelRequestsAllowed(allowed) {
|
|
5
|
+
modelRequestsAllowed = allowed;
|
|
6
|
+
}
|
|
7
|
+
export function modelRequestsAreAllowed() {
|
|
8
|
+
return modelRequestsAllowed;
|
|
9
|
+
}
|
|
10
|
+
/** Marks a transport as an in-process mock, which `allowModelRequests(false)` still lets through. */
|
|
11
|
+
export function markMockTransport(transport) {
|
|
12
|
+
Object.defineProperty(transport, MOCK_TRANSPORT, { value: true });
|
|
13
|
+
return transport;
|
|
14
|
+
}
|
|
15
|
+
export function isMockTransport(transport) {
|
|
16
|
+
return transport !== undefined && transport[MOCK_TRANSPORT] === true;
|
|
17
|
+
}
|
|
18
|
+
export class ModelRequestsDisabledError extends Error {
|
|
19
|
+
name = "ModelRequestsDisabledError";
|
|
20
|
+
}
|
|
21
|
+
/** Throws unless real requests are allowed or the transport is a mock. Adapters call it before sending. */
|
|
22
|
+
export function assertModelRequestAllowed(transport) {
|
|
23
|
+
if (modelRequestsAllowed || isMockTransport(transport))
|
|
24
|
+
return;
|
|
25
|
+
throw new ModelRequestsDisabledError("Model requests are disabled (allowModelRequests(false)); use a mock transport or ScriptedModel in tests.");
|
|
26
|
+
}
|
|
27
|
+
//# sourceMappingURL=request-policy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-policy.js","sourceRoot":"","sources":["../src/request-policy.ts"],"names":[],"mappings":"AAQA,MAAM,cAAc,GAAG,MAAM,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;AAExE,IAAI,oBAAoB,GAAG,IAAI,CAAC;AAEhC,0GAA0G;AAC1G,MAAM,UAAU,uBAAuB,CAAC,OAAgB;IACtD,oBAAoB,GAAG,OAAO,CAAC;AACjC,CAAC;AAED,MAAM,UAAU,uBAAuB;IACrC,OAAO,oBAAoB,CAAC;AAC9B,CAAC;AAED,qGAAqG;AACrG,MAAM,UAAU,iBAAiB,CAAsB,SAAY;IACjE,MAAM,CAAC,cAAc,CAAC,SAAS,EAAE,cAAc,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,SAAgC;IAC9D,OAAO,SAAS,KAAK,SAAS,IAAK,SAAgD,CAAC,cAAc,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC;AAED,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IACjC,IAAI,GAAG,4BAA4B,CAAC;CACvD;AAED,2GAA2G;AAC3G,MAAM,UAAU,yBAAyB,CAAC,SAAgC;IACxE,IAAI,oBAAoB,IAAI,eAAe,CAAC,SAAS,CAAC;QAAE,OAAO;IAC/D,MAAM,IAAI,0BAA0B,CAClC,0GAA0G,CAC3G,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The process-wide switch behind `allowModelRequests()` (SDK decision 14; SDK plan §5.4).\n *\n * Every adapter calls `assertModelRequestAllowed(transport)` before it sends a request. When tests have turned real\n * requests off, any transport not marked as a mock throws before anything leaves the process.\n */\nimport type { Transport } from \"./runtime-types.js\";\n\nconst MOCK_TRANSPORT = Symbol.for(\"buildanagent.gateway.mockTransport\");\n\nlet modelRequestsAllowed = true;\n\n/** Turns real model requests on or off for the whole process. Tests turn them off in the shared setup. */\nexport function setModelRequestsAllowed(allowed: boolean): void {\n modelRequestsAllowed = allowed;\n}\n\nexport function modelRequestsAreAllowed(): boolean {\n return modelRequestsAllowed;\n}\n\n/** Marks a transport as an in-process mock, which `allowModelRequests(false)` still lets through. */\nexport function markMockTransport<T extends Transport>(transport: T): T {\n Object.defineProperty(transport, MOCK_TRANSPORT, { value: true });\n return transport;\n}\n\nexport function isMockTransport(transport: Transport | undefined): boolean {\n return transport !== undefined && (transport as unknown as Record<symbol, unknown>)[MOCK_TRANSPORT] === true;\n}\n\nexport class ModelRequestsDisabledError extends Error {\n override readonly name = \"ModelRequestsDisabledError\";\n}\n\n/** Throws unless real requests are allowed or the transport is a mock. Adapters call it before sending. */\nexport function assertModelRequestAllowed(transport: Transport | undefined): void {\n if (modelRequestsAllowed || isMockTransport(transport)) return;\n throw new ModelRequestsDisabledError(\n \"Model requests are disabled (allowModelRequests(false)); use a mock transport or ScriptedModel in tests.\",\n );\n}\n"]}
|
package/dist/retry.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP retries before any output (SDK decision 4; agent-SDK guide §2).
|
|
3
|
+
*
|
|
4
|
+
* - Only an `error` terminal of kind `retryable` that arrives before any content is retried. Once a block event has
|
|
5
|
+
* been streamed, a retry would replay output the caller has already seen, so the failure is final.
|
|
6
|
+
* - The backoff is exponential (2 s, then 4 s by default, as Vercel's AI SDK) and ends early when the signal aborts.
|
|
7
|
+
* - The caller sees one `start`, then one `retry` event per retry, then the last attempt's events. The final message
|
|
8
|
+
* counts the usage and cost of every attempt, because the provider bills failed attempts too. Each attempt is
|
|
9
|
+
* priced on its own before the sum, because a tiered rate depends on that request's input alone (D4).
|
|
10
|
+
* - A stream that throws is treated like one that ends with an `error` event, so the caller always gets a terminal.
|
|
11
|
+
* - A warning an earlier attempt already streamed, with the same code and message, is not streamed again, because a
|
|
12
|
+
* retry sends the same request and an adapter warns about it each time.
|
|
13
|
+
* - Each wait is capped at 60 s. The provider's retry-after hint isn't used yet: adapters see the response headers,
|
|
14
|
+
* and no event carries a hint to the gateway.
|
|
15
|
+
*/
|
|
16
|
+
import type { GatewayEvent, Sleep } from "./runtime-types.js";
|
|
17
|
+
import type { ModelEvent } from "./spec.js";
|
|
18
|
+
import type { Cost, ModelRef, Usage } from "./types.js";
|
|
19
|
+
/** How many times to retry, how long to wait, and how. */
|
|
20
|
+
export interface RetrySettings {
|
|
21
|
+
readonly retries: number;
|
|
22
|
+
readonly initialDelayMs: number;
|
|
23
|
+
readonly sleep: Sleep;
|
|
24
|
+
/** Prices one attempt's usage; a provider-billed total skips it. */
|
|
25
|
+
readonly price: (usage: Usage) => Cost;
|
|
26
|
+
}
|
|
27
|
+
/** The default `Sleep`: a timer that resolves early, without rejecting, when the signal aborts. */
|
|
28
|
+
export declare const abortableSleep: Sleep;
|
|
29
|
+
/** Runs `attempt(1)`, then retries per `settings`. `attempt(n)` must start a fresh request each time it is called. */
|
|
30
|
+
export declare function withRetries(attempt: (n: number) => AsyncIterable<ModelEvent>, ref: ModelRef, signal: AbortSignal | undefined, settings: RetrySettings): AsyncGenerator<GatewayEvent>;
|