@tanstack/openai-base 0.10.6 → 0.10.7
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/dist/esm/tools/shell-tool.js +19 -0
- package/dist/esm/tools/shell-tool.js.map +1 -1
- package/dist/esm/utils/schema-converter.d.ts +1 -1
- package/dist/esm/utils/schema-converter.js +27 -12
- package/dist/esm/utils/schema-converter.js.map +1 -1
- package/package.json +3 -3
- package/src/adapters/chat-completions-tool-converter.test.ts +58 -0
- package/src/tools/shell-tool.ts +27 -0
- package/src/utils/schema-converter.ts +32 -14
|
@@ -1,6 +1,24 @@
|
|
|
1
1
|
import { getOpenAIProviderToolMetadata, openAIProviderTool } from "./openai-provider-tool.js";
|
|
2
2
|
//#region src/tools/shell-tool.ts
|
|
3
3
|
/**
|
|
4
|
+
* Validate skill references carried by a shell `environment`. Previously the
|
|
5
|
+
* factory validated nothing, so a malformed `skill_id` surfaced as an unframed
|
|
6
|
+
* provider 400. Only `skill_reference` entries carry a `skill_id`; inline and
|
|
7
|
+
* local skills are shaped differently and left untouched.
|
|
8
|
+
*
|
|
9
|
+
* ponytail: OpenAI documents no client-checkable count cap for shell skills
|
|
10
|
+
* (unlike Anthropic's 8), so we validate `skill_id` format only and do not
|
|
11
|
+
* fabricate a `SkillLimitError` count limit. Add one here if OpenAI publishes a cap.
|
|
12
|
+
*/
|
|
13
|
+
function validateShellEnvironment(environment) {
|
|
14
|
+
const skills = environment && "skills" in environment ? environment.skills : void 0;
|
|
15
|
+
if (!skills) return;
|
|
16
|
+
for (const skill of skills) if ("skill_id" in skill) {
|
|
17
|
+
const id = skill.skill_id;
|
|
18
|
+
if (id.length < 1 || id.length > 64) throw new Error("skill_id must be between 1 and 64 characters.");
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
4
22
|
* Converts a standard Tool to OpenAI ShellTool format, preserving any
|
|
5
23
|
* `environment` (container config + skills) stored in metadata.
|
|
6
24
|
*/
|
|
@@ -18,6 +36,7 @@ function convertShellToolToAdapterFormat(tool) {
|
|
|
18
36
|
* re-wrap this in their own package.
|
|
19
37
|
*/
|
|
20
38
|
function shellTool(config = {}) {
|
|
39
|
+
validateShellEnvironment(config.environment);
|
|
21
40
|
return openAIProviderTool({
|
|
22
41
|
name: "shell",
|
|
23
42
|
description: "Execute shell commands",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-tool.js","names":[],"sources":["../../../src/tools/shell-tool.ts"],"sourcesContent":["import {\n getOpenAIProviderToolMetadata,\n openAIProviderTool,\n} from './openai-provider-tool'\nimport type { FunctionShellTool as ShellToolConfig } from 'openai/resources/responses/responses'\nimport type { Tool } from '@tanstack/ai'\n\nexport type { ShellToolConfig }\n\n/** @deprecated Renamed to `ShellToolConfig`. Will be removed in a future release. */\nexport type ShellTool = ShellToolConfig\n\n/**\n * Config accepted by {@link shellTool}. `environment` mirrors the OpenAI\n * Responses API shell tool environment (e.g. `container_auto` + `skills`).\n * Typed via indexed access so it tracks the installed SDK without naming the\n * union members directly.\n */\nexport interface ShellToolFactoryConfig {\n environment?: NonNullable<ShellToolConfig['environment']>\n}\n\n/**\n * Converts a standard Tool to OpenAI ShellTool format, preserving any\n * `environment` (container config + skills) stored in metadata.\n */\nexport function convertShellToolToAdapterFormat(tool: Tool): ShellToolConfig {\n const metadata = (getOpenAIProviderToolMetadata(tool) ??\n {}) as ShellToolFactoryConfig\n return {\n type: 'shell',\n ...(metadata.environment !== undefined && {\n environment: metadata.environment,\n }),\n }\n}\n\n/**\n * Creates a standard Tool from ShellTool parameters.\n *\n * Base (non-branded) factory. Providers that need branded return types should\n * re-wrap this in their own package.\n */\nexport function shellTool(config: ShellToolFactoryConfig = {}): Tool {\n return openAIProviderTool(\n {\n name: 'shell',\n description: 'Execute shell commands',\n metadata: {\n ...(config.environment !== undefined && {\n environment: config.environment,\n }),\n },\n },\n 'shell',\n )\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"shell-tool.js","names":[],"sources":["../../../src/tools/shell-tool.ts"],"sourcesContent":["import {\n getOpenAIProviderToolMetadata,\n openAIProviderTool,\n} from './openai-provider-tool'\nimport type { FunctionShellTool as ShellToolConfig } from 'openai/resources/responses/responses'\nimport type { Tool } from '@tanstack/ai'\n\nexport type { ShellToolConfig }\n\n/** @deprecated Renamed to `ShellToolConfig`. Will be removed in a future release. */\nexport type ShellTool = ShellToolConfig\n\n/**\n * Config accepted by {@link shellTool}. `environment` mirrors the OpenAI\n * Responses API shell tool environment (e.g. `container_auto` + `skills`).\n * Typed via indexed access so it tracks the installed SDK without naming the\n * union members directly.\n */\nexport interface ShellToolFactoryConfig {\n environment?: NonNullable<ShellToolConfig['environment']>\n}\n\n/**\n * Validate skill references carried by a shell `environment`. Previously the\n * factory validated nothing, so a malformed `skill_id` surfaced as an unframed\n * provider 400. Only `skill_reference` entries carry a `skill_id`; inline and\n * local skills are shaped differently and left untouched.\n *\n * ponytail: OpenAI documents no client-checkable count cap for shell skills\n * (unlike Anthropic's 8), so we validate `skill_id` format only and do not\n * fabricate a `SkillLimitError` count limit. Add one here if OpenAI publishes a cap.\n */\nfunction validateShellEnvironment(\n environment: ShellToolFactoryConfig['environment'],\n): void {\n const skills =\n environment && 'skills' in environment ? environment.skills : undefined\n if (!skills) return\n for (const skill of skills) {\n if ('skill_id' in skill) {\n const id = skill.skill_id\n if (id.length < 1 || id.length > 64) {\n throw new Error('skill_id must be between 1 and 64 characters.')\n }\n }\n }\n}\n\n/**\n * Converts a standard Tool to OpenAI ShellTool format, preserving any\n * `environment` (container config + skills) stored in metadata.\n */\nexport function convertShellToolToAdapterFormat(tool: Tool): ShellToolConfig {\n const metadata = (getOpenAIProviderToolMetadata(tool) ??\n {}) as ShellToolFactoryConfig\n return {\n type: 'shell',\n ...(metadata.environment !== undefined && {\n environment: metadata.environment,\n }),\n }\n}\n\n/**\n * Creates a standard Tool from ShellTool parameters.\n *\n * Base (non-branded) factory. Providers that need branded return types should\n * re-wrap this in their own package.\n */\nexport function shellTool(config: ShellToolFactoryConfig = {}): Tool {\n validateShellEnvironment(config.environment)\n return openAIProviderTool(\n {\n name: 'shell',\n description: 'Execute shell commands',\n metadata: {\n ...(config.environment !== undefined && {\n environment: config.environment,\n }),\n },\n },\n 'shell',\n )\n}\n"],"mappings":";;;;;;;;;;;;AAgCA,SAAS,yBACP,aACM;CACN,MAAM,SACJ,eAAe,YAAY,cAAc,YAAY,SAAS,KAAA;CAChE,IAAI,CAAC,QAAQ;CACb,KAAK,MAAM,SAAS,QAClB,IAAI,cAAc,OAAO;EACvB,MAAM,KAAK,MAAM;EACjB,IAAI,GAAG,SAAS,KAAK,GAAG,SAAS,IAC/B,MAAM,IAAI,MAAM,+CAA+C;CAEnE;AAEJ;;;;;AAMA,SAAgB,gCAAgC,MAA6B;CAC3E,MAAM,WAAY,8BAA8B,IAAI,KAClD,CAAC;CACH,OAAO;EACL,MAAM;EACN,GAAI,SAAS,gBAAgB,KAAA,KAAa,EACxC,aAAa,SAAS,YACxB;CACF;AACF;;;;;;;AAQA,SAAgB,UAAU,SAAiC,CAAC,GAAS;CACnE,yBAAyB,OAAO,WAAW;CAC3C,OAAO,mBACL;EACE,MAAM;EACN,aAAa;EACb,UAAU,EACR,GAAI,OAAO,gBAAgB,KAAA,KAAa,EACtC,aAAa,OAAO,YACtB,EACF;CACF,GACA,OACF;AACF"}
|
|
@@ -37,7 +37,7 @@ export declare function makeStructuredOutputCompatibleWithMap(schema: Record<str
|
|
|
37
37
|
* sent with `strict: false`. Two ways that happens:
|
|
38
38
|
*
|
|
39
39
|
* 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in
|
|
40
|
-
* the tree (`oneOf`/`allOf`/`not`/`$ref`/`$defs`).
|
|
40
|
+
* the tree (`oneOf`/`allOf`/`not`/`prefixItems`/`$ref`/`$defs`).
|
|
41
41
|
* 2. It contains a *typeless* schema node — a property/items/anyOf entry with
|
|
42
42
|
* no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`
|
|
43
43
|
* produces. Strict mode rejects typeless schemas.
|
|
@@ -74,6 +74,8 @@ function makeStructuredOutputCompatibleWithMap(schema, originalRequired) {
|
|
|
74
74
|
* emit these.
|
|
75
75
|
*
|
|
76
76
|
* - `oneOf` / `allOf` / `not` — combinator keywords strict mode rejects
|
|
77
|
+
* - `prefixItems` — 2020-12 tuple keyword. openai-node's strict transform
|
|
78
|
+
* rejects it, so we send those tools with `strict: false` instead
|
|
77
79
|
* - `$ref` / `$defs` / `definitions` — references and definition pools whose
|
|
78
80
|
* object subschemas escape the `additionalProperties: false` normalization
|
|
79
81
|
* strict mode requires
|
|
@@ -82,6 +84,7 @@ var STRICT_UNSUPPORTED_KEYWORDS = [
|
|
|
82
84
|
"oneOf",
|
|
83
85
|
"allOf",
|
|
84
86
|
"not",
|
|
87
|
+
"prefixItems",
|
|
85
88
|
"$ref",
|
|
86
89
|
"$defs",
|
|
87
90
|
"definitions"
|
|
@@ -109,7 +112,7 @@ var TYPE_INDICATOR_KEYWORDS = [
|
|
|
109
112
|
* sent with `strict: false`. Two ways that happens:
|
|
110
113
|
*
|
|
111
114
|
* 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in
|
|
112
|
-
* the tree (`oneOf`/`allOf`/`not`/`$ref`/`$defs`).
|
|
115
|
+
* the tree (`oneOf`/`allOf`/`not`/`prefixItems`/`$ref`/`$defs`).
|
|
113
116
|
* 2. It contains a *typeless* schema node — a property/items/anyOf entry with
|
|
114
117
|
* no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`
|
|
115
118
|
* produces. Strict mode rejects typeless schemas.
|
|
@@ -224,13 +227,10 @@ function coerceStrictSchema(schema, originalRequired) {
|
|
|
224
227
|
prop = nested.schema;
|
|
225
228
|
childMap = nested.nullWideningMap;
|
|
226
229
|
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
227
|
-
} else if (isSchemaObject(prop) && prop.type === "array"
|
|
228
|
-
const nested = coerceStrictSchema(prop
|
|
229
|
-
prop =
|
|
230
|
-
|
|
231
|
-
items: nested.schema
|
|
232
|
-
};
|
|
233
|
-
childMap = nested.nullWideningMap ? { items: nested.nullWideningMap } : void 0;
|
|
230
|
+
} else if (isSchemaObject(prop) && prop.type === "array") {
|
|
231
|
+
const nested = coerceStrictSchema(prop, []);
|
|
232
|
+
prop = nested.schema;
|
|
233
|
+
childMap = nested.nullWideningMap;
|
|
234
234
|
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
235
235
|
} else if (isSchemaObject(prop) && prop.anyOf) {
|
|
236
236
|
const nested = coerceStrictSchema(prop, prop.required || []);
|
|
@@ -277,10 +277,25 @@ function coerceStrictSchema(schema, originalRequired) {
|
|
|
277
277
|
if (Object.keys(propertyMaps).length > 0) nullWideningMap.properties = propertyMaps;
|
|
278
278
|
}
|
|
279
279
|
if (result.type === "array" && result.items) {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
280
|
+
if (Array.isArray(result.items)) {
|
|
281
|
+
const itemMaps = [];
|
|
282
|
+
result.items = result.items.map((item) => {
|
|
283
|
+
if (!isSchemaObject(item)) {
|
|
284
|
+
itemMaps.push({});
|
|
285
|
+
return item;
|
|
286
|
+
}
|
|
287
|
+
const nested = coerceStrictSchema(item, item.required || []);
|
|
288
|
+
itemMaps.push(nested.nullWideningMap ?? {});
|
|
289
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
290
|
+
return nested.schema;
|
|
291
|
+
});
|
|
292
|
+
if (itemMaps.some((map) => Object.keys(map).length > 0)) nullWideningMap.items = itemMaps;
|
|
293
|
+
} else {
|
|
294
|
+
const nested = coerceStrictSchema(result.items, result.items.required || []);
|
|
295
|
+
result.items = nested.schema;
|
|
296
|
+
if (nested.nullWideningMap) nullWideningMap.items = nested.nullWideningMap;
|
|
297
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
298
|
+
}
|
|
284
299
|
}
|
|
285
300
|
if (result.anyOf && Array.isArray(result.anyOf)) {
|
|
286
301
|
const variants = result.anyOf.map((variant) => coerceStrictSchema(variant, variant.required || []));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-converter.js","names":[],"sources":["../../../src/utils/schema-converter.ts"],"sourcesContent":["import type { NullWideningMap } from '@tanstack/ai-utils'\n\n/**\n * String `format` values accepted by OpenAI's strict Structured Outputs subset.\n * Any other format (e.g. \"uri\", \"uri-reference\", \"regex\") causes the API to\n * reject the whole request with `400 ... '<format>' is not a valid format`.\n * MCP servers and hand-written tools routinely declare such formats, so we strip\n * the unsupported ones before sending. See:\n * https://platform.openai.com/docs/guides/structured-outputs#supported-properties\n */\nconst SUPPORTED_STRING_FORMATS = new Set([\n 'date-time',\n 'time',\n 'date',\n 'duration',\n 'email',\n 'hostname',\n 'ipv4',\n 'ipv6',\n 'uuid',\n])\n\n/**\n * Recursively drop JSON-Schema `format` keywords whose value isn't in OpenAI's\n * strict-mode allowlist. Pure — returns a fresh tree and never mutates `node`,\n * so the caller's original tool definition is left intact.\n *\n * A property *named* `format` always has a schema (object/boolean) value, never\n * a bare string, so it is preserved and recursed into; only the `format`\n * *keyword* (whose value is a string) is subject to removal.\n */\nexport function stripUnsupportedFormats(node: any): any {\n if (Array.isArray(node)) return node.map(stripUnsupportedFormats)\n if (node === null || typeof node !== 'object') return node\n\n const out: Record<string, any> = {}\n for (const [key, value] of Object.entries(node)) {\n if (\n key === 'format' &&\n typeof value === 'string' &&\n !SUPPORTED_STRING_FORMATS.has(value)\n ) {\n continue\n }\n out[key] = stripUnsupportedFormats(value)\n }\n return out\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n * - String `format` keywords must be from a fixed allowlist (others are stripped)\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nexport function makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): Record<string, any> {\n return makeStructuredOutputCompatibleWithMap(schema, originalRequired).schema\n}\n\nexport interface StructuredOutputCompatibility {\n schema: Record<string, any>\n nullWideningMap: NullWideningMap | undefined\n}\n\ninterface CoercedStrictSchema extends StructuredOutputCompatibility {\n hasUntrackableAnyOfWidening: boolean\n}\n\n/**\n * Strict-schema conversion plus an exact map of the nullability introduced by\n * that conversion. Consumers can pass provider output through\n * `undoNullWidening` before validating it against the original schema.\n */\nexport function makeStructuredOutputCompatibleWithMap(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): StructuredOutputCompatibility {\n const { schema: strictSchema, nullWideningMap } = coerceStrictSchema(\n schema,\n originalRequired,\n )\n return {\n schema: stripUnsupportedFormats(strictSchema),\n nullWideningMap,\n }\n}\n\n/**\n * JSON-Schema keywords outside OpenAI's strict Structured Outputs subset. A\n * schema using any of these can't be coerced into a strict-valid shape, and\n * sending it with `strict: true` makes the API reject the ENTIRE request\n * (e.g. `400 Invalid schema ... 'additionalProperties' is required to be ...`).\n * Tools with such schemas are emitted with `strict: false` instead (see the\n * tool converters) so they remain callable. MCP servers (e.g. Notion) routinely\n * emit these.\n *\n * - `oneOf` / `allOf` / `not` — combinator keywords strict mode rejects\n * - `$ref` / `$defs` / `definitions` — references and definition pools whose\n * object subschemas escape the `additionalProperties: false` normalization\n * strict mode requires\n */\nconst STRICT_UNSUPPORTED_KEYWORDS: ReadonlyArray<string> = [\n 'oneOf',\n 'allOf',\n 'not',\n '$ref',\n '$defs',\n 'definitions',\n]\n\n/**\n * Keys that give a schema node a resolvable type under OpenAI's strict subset.\n * A schema-position node carrying none of these is *typeless* (e.g. the empty\n * `{}` that `z.any()` / `z.unknown()` emit). Strict mode requires every schema\n * to declare a type, so a typeless node 400s the whole request — such tools\n * must be sent with `strict: false` instead. (`oneOf`/`allOf`/`$ref` count as\n * type indicators here even though they're independently strict-unsupported;\n * the keyword check below already rejects them.)\n */\nconst TYPE_INDICATOR_KEYWORDS: ReadonlyArray<string> = [\n 'type',\n 'enum',\n 'const',\n 'anyOf',\n 'oneOf',\n 'allOf',\n '$ref',\n]\n\n/**\n * Returns `false` when `schema` cannot be made strict-compatible and must be\n * sent with `strict: false`. Two ways that happens:\n *\n * 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in\n * the tree (`oneOf`/`allOf`/`not`/`$ref`/`$defs`).\n * 2. It contains a *typeless* schema node — a property/items/anyOf entry with\n * no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`\n * produces. Strict mode rejects typeless schemas.\n * 3. It contains an open object schema. OpenAI strict mode requires objects to\n * set `additionalProperties: false`, which would change the semantics of a\n * free-form map rather than merely normalizing it.\n * 4. An `anyOf` variant itself needs null widening. The inverse map is\n * intentionally schema-blind, so it cannot select a variant without risking\n * removal of a genuine nullable value accepted by another variant.\n *\n * Conservative by design: for (1) keywords are matched as object keys, so a\n * property literally named e.g. `oneOf` also trips it. That only costs that one\n * tool its strict mode, which is strictly safer than a false \"compatible\"\n * verdict that 400s the whole request.\n */\nexport function isStrictModeCompatible(schema: unknown): boolean {\n return (\n !containsStrictUnsupportedKeyword(schema) &&\n !containsTypelessSchema(schema) &&\n !containsOpenObject(schema) &&\n !containsUntrackableAnyOfWidening(schema)\n )\n}\n\n/**\n * Reports strict conversions whose synthesized nulls cannot be represented by\n * the schema-blind inverse map. Optional `anyOf` wrappers remain supported:\n * only widening introduced inside one of their variants triggers fallback.\n */\nfunction containsUntrackableAnyOfWidening(schema: unknown): boolean {\n if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {\n return false\n }\n return coerceStrictSchema(schema as Record<string, any>)\n .hasUntrackableAnyOfWidening\n}\n\n/**\n * Reports object schemas that cannot be closed without changing their input\n * semantics. Objects with `properties` and no explicit\n * `additionalProperties` are safe because `coerceStrictSchema` closes them.\n */\nfunction containsOpenObject(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsOpenObject)\n }\n if (node === null || typeof node !== 'object') return false\n\n const schema = node as Record<string, unknown>\n const type = schema['type']\n const isObjectSchema =\n type === 'object' || (Array.isArray(type) && type.includes('object'))\n\n if (isObjectSchema) {\n if (\n 'additionalProperties' in schema &&\n schema['additionalProperties'] !== false\n ) {\n return true\n }\n\n const properties = schema['properties']\n const hasProperties =\n properties !== null &&\n typeof properties === 'object' &&\n !Array.isArray(properties)\n if (!hasProperties && schema['additionalProperties'] !== false) {\n return true\n }\n }\n\n return Object.values(schema).some(containsOpenObject)\n}\n\nfunction containsStrictUnsupportedKeyword(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsStrictUnsupportedKeyword)\n }\n if (node === null || typeof node !== 'object') return false\n for (const [key, value] of Object.entries(node)) {\n if (STRICT_UNSUPPORTED_KEYWORDS.includes(key)) return true\n if (containsStrictUnsupportedKeyword(value)) return true\n }\n return false\n}\n\n/** A schema-position node that declares no type and so 400s strict mode. */\nfunction isTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n // JSON Schema permits bare boolean nodes; malformed inputs may contain\n // other primitives. OpenAI's strict subset requires a declared type, so\n // preserve the containing tool by sending it in non-strict mode.\n return true\n }\n return !TYPE_INDICATOR_KEYWORDS.some((key) => key in node)\n}\n\n/**\n * Walks the genuine schema positions (property values, `items`, `anyOf`\n * variants) and reports whether any is typeless. Unlike the keyword walk this\n * must respect structure: an empty `{}` is only a problem at a schema position,\n * not e.g. an empty `properties` map.\n */\nfunction containsTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n return false\n }\n const schema = node as Record<string, any>\n\n const children: Array<unknown> = []\n if (schema.properties && typeof schema.properties === 'object') {\n children.push(...Object.values(schema.properties))\n }\n if (schema.items !== undefined) {\n children.push(\n ...(Array.isArray(schema.items) ? schema.items : [schema.items]),\n )\n }\n if (Array.isArray(schema.anyOf)) {\n children.push(...schema.anyOf)\n }\n\n return children.some(\n (child) => isTypelessSchema(child) || containsTypelessSchema(child),\n )\n}\n\n/**\n * Strict-mode structural rewrite (required widening, nullability,\n * additionalProperties). Kept private so the public entry point can apply the\n * format-stripping pass exactly once over the fully-rewritten tree.\n */\nfunction pruneMap(map: NullWideningMap): NullWideningMap | undefined {\n return Object.keys(map).length > 0 ? map : undefined\n}\n\nfunction isSchemaObject(schema: unknown): schema is Record<string, any> {\n return typeof schema === 'object' && schema !== null && !Array.isArray(schema)\n}\n\n/** Whether every active JSON Schema constraint at this node admits null. */\nfunction acceptsNull(schema: unknown): boolean {\n if (schema === true) return true\n if (!isSchemaObject(schema)) return false\n\n if ('const' in schema && schema.const !== null) return false\n if (Array.isArray(schema.enum) && !schema.enum.includes(null)) return false\n\n if (typeof schema.type === 'string' && schema.type !== 'null') return false\n if (Array.isArray(schema.type) && !schema.type.includes('null')) return false\n\n if (\n Array.isArray(schema.anyOf) &&\n !schema.anyOf.some((variant: unknown) => acceptsNull(variant))\n ) {\n return false\n }\n\n return true\n}\n\nfunction coerceStrictSchema(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): CoercedStrictSchema {\n const result = { ...schema }\n const nullWideningMap: NullWideningMap = {}\n let hasUntrackableAnyOfWidening = false\n const required =\n originalRequired ??\n (Array.isArray(result['required']) ? result['required'] : [])\n\n if (result.type === 'object' && result.properties) {\n const properties = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n const propertyMaps: Record<string, NullWideningMap> = {}\n\n for (const propName of allPropertyNames) {\n let prop = properties[propName]\n const wasOptional = !required.includes(propName)\n let childMap: NullWideningMap | undefined\n let widenedHere = false\n\n // Step 1: Recurse into nested structures\n if (isSchemaObject(prop) && prop.type === 'object' && prop.properties) {\n const nested = coerceStrictSchema(prop, prop.required || [])\n prop = nested.schema\n childMap = nested.nullWideningMap\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.type === 'array' && prop.items) {\n const nested = coerceStrictSchema(prop.items, prop.items.required || [])\n prop = {\n ...prop,\n items: nested.schema,\n }\n childMap = nested.nullWideningMap\n ? { items: nested.nullWideningMap }\n : undefined\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.anyOf) {\n const nested = coerceStrictSchema(prop, prop.required || [])\n prop = nested.schema\n childMap = nested.nullWideningMap\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n // Step 2: Apply null-widening for optional properties (after recursion)\n if (wasOptional) {\n const originallyAcceptedNull = acceptsNull(prop)\n\n // `type: [..., 'null']` alone does not make null valid when an enum or\n // const still excludes it; strict decoding would be forced to emit the\n // original literal instead of the synthetic omission marker.\n if (isSchemaObject(prop) && 'const' in prop && prop.const !== null) {\n const { const: constValue, ...withoutConst } = prop\n prop = { ...withoutConst, enum: [constValue, null] }\n } else if (\n isSchemaObject(prop) &&\n Array.isArray(prop.enum) &&\n !prop.enum.includes(null)\n ) {\n prop = { ...prop, enum: [...prop.enum, null] }\n }\n\n if (isSchemaObject(prop) && prop.anyOf) {\n // A genuine null branch can use type, enum, or const. Only add a\n // provider omission marker when the original union rejected null.\n if (!acceptsNull(prop)) {\n prop = { ...prop, anyOf: [...prop.anyOf, { type: 'null' }] }\n }\n } else if (\n isSchemaObject(prop) &&\n prop.type &&\n !Array.isArray(prop.type)\n ) {\n prop = { ...prop, type: [prop.type, 'null'] }\n } else if (\n isSchemaObject(prop) &&\n Array.isArray(prop.type) &&\n !prop.type.includes('null')\n ) {\n prop = { ...prop, type: [...prop.type, 'null'] }\n }\n\n widenedHere = !originallyAcceptedNull && acceptsNull(prop)\n }\n\n properties[propName] = prop\n if (childMap || widenedHere) {\n propertyMaps[propName] = {\n ...(childMap ?? {}),\n ...(widenedHere ? { widened: true } : {}),\n }\n }\n }\n\n result.properties = properties\n result.required = allPropertyNames\n result.additionalProperties = false\n if (Object.keys(propertyMaps).length > 0) {\n nullWideningMap.properties = propertyMaps\n }\n }\n\n if (result.type === 'array' && result.items) {\n const nested = coerceStrictSchema(result.items, result.items.required || [])\n result.items = nested.schema\n if (nested.nullWideningMap) {\n nullWideningMap.items = nested.nullWideningMap\n }\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n }\n\n if (result.anyOf && Array.isArray(result.anyOf)) {\n const variants = result.anyOf.map((variant) =>\n coerceStrictSchema(variant, variant.required || []),\n )\n result.anyOf = variants.map((variant) => variant.schema)\n hasUntrackableAnyOfWidening ||= variants.some(\n (variant) =>\n variant.nullWideningMap !== undefined ||\n variant.hasUntrackableAnyOfWidening,\n )\n }\n\n if (result.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n return {\n schema: result,\n nullWideningMap: pruneMap(nullWideningMap),\n hasUntrackableAnyOfWidening,\n }\n}\n"],"mappings":";;;;;;;;;AAUA,IAAM,2CAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAWD,SAAgB,wBAAwB,MAAgB;CACtD,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,KAAK,IAAI,uBAAuB;CAChE,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU,OAAO;CAEtD,MAAM,MAA2B,CAAC;CAClC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;EAC/C,IACE,QAAQ,YACR,OAAO,UAAU,YACjB,CAAC,yBAAyB,IAAI,KAAK,GAEnC;EAEF,IAAI,OAAO,wBAAwB,KAAK;CAC1C;CACA,OAAO;AACT;;;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MAAM;IAAE;IAGjD,cAAc,CAAC,0BAA0B,YAAY,IAAI;GAC3D;GAEA,WAAW,YAAY;GACvB,IAAI,YAAY,aACd,aAAa,YAAY;IACvB,GAAI,YAAY,CAAC;IACjB,GAAI,cAAc,EAAE,SAAS,KAAK,IAAI,CAAC;GACzC;EAEJ;EAEA,OAAO,aAAa;EACpB,OAAO,WAAW;EAClB,OAAO,uBAAuB;EAC9B,IAAI,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS,GACrC,gBAAgB,aAAa;CAEjC;CAEA,IAAI,OAAO,SAAS,WAAW,OAAO,OAAO;EAC3C,MAAM,SAAS,mBAAmB,OAAO,OAAO,OAAO,MAAM,YAAY,CAAC,CAAC;EAC3E,OAAO,QAAQ,OAAO;EACtB,IAAI,OAAO,iBACT,gBAAgB,QAAQ,OAAO;EAEjC,gCAAgC,OAAO;CACzC;CAEA,IAAI,OAAO,SAAS,MAAM,QAAQ,OAAO,KAAK,GAAG;EAC/C,MAAM,WAAW,OAAO,MAAM,KAAK,YACjC,mBAAmB,SAAS,QAAQ,YAAY,CAAC,CAAC,CACpD;EACA,OAAO,QAAQ,SAAS,KAAK,YAAY,QAAQ,MAAM;EACvD,gCAAgC,SAAS,MACtC,YACC,QAAQ,oBAAoB,KAAA,KAC5B,QAAQ,2BACZ;CACF;CAEA,IAAI,OAAO,OACT,MAAM,IAAI,MACR,0KACF;CAGF,OAAO;EACL,QAAQ;EACR,iBAAiB,SAAS,eAAe;EACzC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"schema-converter.js","names":[],"sources":["../../../src/utils/schema-converter.ts"],"sourcesContent":["import type { NullWideningMap } from '@tanstack/ai-utils'\n\n/**\n * String `format` values accepted by OpenAI's strict Structured Outputs subset.\n * Any other format (e.g. \"uri\", \"uri-reference\", \"regex\") causes the API to\n * reject the whole request with `400 ... '<format>' is not a valid format`.\n * MCP servers and hand-written tools routinely declare such formats, so we strip\n * the unsupported ones before sending. See:\n * https://platform.openai.com/docs/guides/structured-outputs#supported-properties\n */\nconst SUPPORTED_STRING_FORMATS = new Set([\n 'date-time',\n 'time',\n 'date',\n 'duration',\n 'email',\n 'hostname',\n 'ipv4',\n 'ipv6',\n 'uuid',\n])\n\n/**\n * Recursively drop JSON-Schema `format` keywords whose value isn't in OpenAI's\n * strict-mode allowlist. Pure — returns a fresh tree and never mutates `node`,\n * so the caller's original tool definition is left intact.\n *\n * A property *named* `format` always has a schema (object/boolean) value, never\n * a bare string, so it is preserved and recursed into; only the `format`\n * *keyword* (whose value is a string) is subject to removal.\n */\nexport function stripUnsupportedFormats(node: any): any {\n if (Array.isArray(node)) return node.map(stripUnsupportedFormats)\n if (node === null || typeof node !== 'object') return node\n\n const out: Record<string, any> = {}\n for (const [key, value] of Object.entries(node)) {\n if (\n key === 'format' &&\n typeof value === 'string' &&\n !SUPPORTED_STRING_FORMATS.has(value)\n ) {\n continue\n }\n out[key] = stripUnsupportedFormats(value)\n }\n return out\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n * - String `format` keywords must be from a fixed allowlist (others are stripped)\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nexport function makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): Record<string, any> {\n return makeStructuredOutputCompatibleWithMap(schema, originalRequired).schema\n}\n\nexport interface StructuredOutputCompatibility {\n schema: Record<string, any>\n nullWideningMap: NullWideningMap | undefined\n}\n\ninterface CoercedStrictSchema extends StructuredOutputCompatibility {\n hasUntrackableAnyOfWidening: boolean\n}\n\n/**\n * Strict-schema conversion plus an exact map of the nullability introduced by\n * that conversion. Consumers can pass provider output through\n * `undoNullWidening` before validating it against the original schema.\n */\nexport function makeStructuredOutputCompatibleWithMap(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): StructuredOutputCompatibility {\n const { schema: strictSchema, nullWideningMap } = coerceStrictSchema(\n schema,\n originalRequired,\n )\n return {\n schema: stripUnsupportedFormats(strictSchema),\n nullWideningMap,\n }\n}\n\n/**\n * JSON-Schema keywords outside OpenAI's strict Structured Outputs subset. A\n * schema using any of these can't be coerced into a strict-valid shape, and\n * sending it with `strict: true` makes the API reject the ENTIRE request\n * (e.g. `400 Invalid schema ... 'additionalProperties' is required to be ...`).\n * Tools with such schemas are emitted with `strict: false` instead (see the\n * tool converters) so they remain callable. MCP servers (e.g. Notion) routinely\n * emit these.\n *\n * - `oneOf` / `allOf` / `not` — combinator keywords strict mode rejects\n * - `prefixItems` — 2020-12 tuple keyword. openai-node's strict transform\n * rejects it, so we send those tools with `strict: false` instead\n * - `$ref` / `$defs` / `definitions` — references and definition pools whose\n * object subschemas escape the `additionalProperties: false` normalization\n * strict mode requires\n */\nconst STRICT_UNSUPPORTED_KEYWORDS: ReadonlyArray<string> = [\n 'oneOf',\n 'allOf',\n 'not',\n 'prefixItems',\n '$ref',\n '$defs',\n 'definitions',\n]\n\n/**\n * Keys that give a schema node a resolvable type under OpenAI's strict subset.\n * A schema-position node carrying none of these is *typeless* (e.g. the empty\n * `{}` that `z.any()` / `z.unknown()` emit). Strict mode requires every schema\n * to declare a type, so a typeless node 400s the whole request — such tools\n * must be sent with `strict: false` instead. (`oneOf`/`allOf`/`$ref` count as\n * type indicators here even though they're independently strict-unsupported;\n * the keyword check below already rejects them.)\n */\nconst TYPE_INDICATOR_KEYWORDS: ReadonlyArray<string> = [\n 'type',\n 'enum',\n 'const',\n 'anyOf',\n 'oneOf',\n 'allOf',\n '$ref',\n]\n\n/**\n * Returns `false` when `schema` cannot be made strict-compatible and must be\n * sent with `strict: false`. Two ways that happens:\n *\n * 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in\n * the tree (`oneOf`/`allOf`/`not`/`prefixItems`/`$ref`/`$defs`).\n * 2. It contains a *typeless* schema node — a property/items/anyOf entry with\n * no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`\n * produces. Strict mode rejects typeless schemas.\n * 3. It contains an open object schema. OpenAI strict mode requires objects to\n * set `additionalProperties: false`, which would change the semantics of a\n * free-form map rather than merely normalizing it.\n * 4. An `anyOf` variant itself needs null widening. The inverse map is\n * intentionally schema-blind, so it cannot select a variant without risking\n * removal of a genuine nullable value accepted by another variant.\n *\n * Conservative by design: for (1) keywords are matched as object keys, so a\n * property literally named e.g. `oneOf` also trips it. That only costs that one\n * tool its strict mode, which is strictly safer than a false \"compatible\"\n * verdict that 400s the whole request.\n */\nexport function isStrictModeCompatible(schema: unknown): boolean {\n return (\n !containsStrictUnsupportedKeyword(schema) &&\n !containsTypelessSchema(schema) &&\n !containsOpenObject(schema) &&\n !containsUntrackableAnyOfWidening(schema)\n )\n}\n\n/**\n * Reports strict conversions whose synthesized nulls cannot be represented by\n * the schema-blind inverse map. Optional `anyOf` wrappers remain supported:\n * only widening introduced inside one of their variants triggers fallback.\n */\nfunction containsUntrackableAnyOfWidening(schema: unknown): boolean {\n if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {\n return false\n }\n return coerceStrictSchema(schema as Record<string, any>)\n .hasUntrackableAnyOfWidening\n}\n\n/**\n * Reports object schemas that cannot be closed without changing their input\n * semantics. Objects with `properties` and no explicit\n * `additionalProperties` are safe because `coerceStrictSchema` closes them.\n */\nfunction containsOpenObject(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsOpenObject)\n }\n if (node === null || typeof node !== 'object') return false\n\n const schema = node as Record<string, unknown>\n const type = schema['type']\n const isObjectSchema =\n type === 'object' || (Array.isArray(type) && type.includes('object'))\n\n if (isObjectSchema) {\n if (\n 'additionalProperties' in schema &&\n schema['additionalProperties'] !== false\n ) {\n return true\n }\n\n const properties = schema['properties']\n const hasProperties =\n properties !== null &&\n typeof properties === 'object' &&\n !Array.isArray(properties)\n if (!hasProperties && schema['additionalProperties'] !== false) {\n return true\n }\n }\n\n return Object.values(schema).some(containsOpenObject)\n}\n\nfunction containsStrictUnsupportedKeyword(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsStrictUnsupportedKeyword)\n }\n if (node === null || typeof node !== 'object') return false\n for (const [key, value] of Object.entries(node)) {\n if (STRICT_UNSUPPORTED_KEYWORDS.includes(key)) return true\n if (containsStrictUnsupportedKeyword(value)) return true\n }\n return false\n}\n\n/** A schema-position node that declares no type and so 400s strict mode. */\nfunction isTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n // JSON Schema permits bare boolean nodes; malformed inputs may contain\n // other primitives. OpenAI's strict subset requires a declared type, so\n // preserve the containing tool by sending it in non-strict mode.\n return true\n }\n return !TYPE_INDICATOR_KEYWORDS.some((key) => key in node)\n}\n\n/**\n * Walks the genuine schema positions (property values, `items`, `anyOf`\n * variants) and reports whether any is typeless. Unlike the keyword walk this\n * must respect structure: an empty `{}` is only a problem at a schema position,\n * not e.g. an empty `properties` map.\n */\nfunction containsTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n return false\n }\n const schema = node as Record<string, any>\n\n const children: Array<unknown> = []\n if (schema.properties && typeof schema.properties === 'object') {\n children.push(...Object.values(schema.properties))\n }\n if (schema.items !== undefined) {\n children.push(\n ...(Array.isArray(schema.items) ? schema.items : [schema.items]),\n )\n }\n if (Array.isArray(schema.anyOf)) {\n children.push(...schema.anyOf)\n }\n\n return children.some(\n (child) => isTypelessSchema(child) || containsTypelessSchema(child),\n )\n}\n\n/**\n * Strict-mode structural rewrite (required widening, nullability,\n * additionalProperties). Kept private so the public entry point can apply the\n * format-stripping pass exactly once over the fully-rewritten tree.\n */\nfunction pruneMap(map: NullWideningMap): NullWideningMap | undefined {\n return Object.keys(map).length > 0 ? map : undefined\n}\n\nfunction isSchemaObject(schema: unknown): schema is Record<string, any> {\n return typeof schema === 'object' && schema !== null && !Array.isArray(schema)\n}\n\n/** Whether every active JSON Schema constraint at this node admits null. */\nfunction acceptsNull(schema: unknown): boolean {\n if (schema === true) return true\n if (!isSchemaObject(schema)) return false\n\n if ('const' in schema && schema.const !== null) return false\n if (Array.isArray(schema.enum) && !schema.enum.includes(null)) return false\n\n if (typeof schema.type === 'string' && schema.type !== 'null') return false\n if (Array.isArray(schema.type) && !schema.type.includes('null')) return false\n\n if (\n Array.isArray(schema.anyOf) &&\n !schema.anyOf.some((variant: unknown) => acceptsNull(variant))\n ) {\n return false\n }\n\n return true\n}\n\nfunction coerceStrictSchema(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): CoercedStrictSchema {\n const result = { ...schema }\n const nullWideningMap: NullWideningMap = {}\n let hasUntrackableAnyOfWidening = false\n const required =\n originalRequired ??\n (Array.isArray(result['required']) ? result['required'] : [])\n\n if (result.type === 'object' && result.properties) {\n const properties = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n const propertyMaps: Record<string, NullWideningMap> = {}\n\n for (const propName of allPropertyNames) {\n let prop = properties[propName]\n const wasOptional = !required.includes(propName)\n let childMap: NullWideningMap | undefined\n let widenedHere = false\n\n // Step 1: Recurse into nested structures\n if (isSchemaObject(prop) && prop.type === 'object' && prop.properties) {\n const nested = coerceStrictSchema(prop, prop.required || [])\n prop = nested.schema\n childMap = nested.nullWideningMap\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.type === 'array') {\n const nested = coerceStrictSchema(prop, [])\n prop = nested.schema\n childMap = nested.nullWideningMap\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.anyOf) {\n const nested = coerceStrictSchema(prop, prop.required || [])\n prop = nested.schema\n childMap = nested.nullWideningMap\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n // Step 2: Apply null-widening for optional properties (after recursion)\n if (wasOptional) {\n const originallyAcceptedNull = acceptsNull(prop)\n\n // `type: [..., 'null']` alone does not make null valid when an enum or\n // const still excludes it; strict decoding would be forced to emit the\n // original literal instead of the synthetic omission marker.\n if (isSchemaObject(prop) && 'const' in prop && prop.const !== null) {\n const { const: constValue, ...withoutConst } = prop\n prop = { ...withoutConst, enum: [constValue, null] }\n } else if (\n isSchemaObject(prop) &&\n Array.isArray(prop.enum) &&\n !prop.enum.includes(null)\n ) {\n prop = { ...prop, enum: [...prop.enum, null] }\n }\n\n if (isSchemaObject(prop) && prop.anyOf) {\n // A genuine null branch can use type, enum, or const. Only add a\n // provider omission marker when the original union rejected null.\n if (!acceptsNull(prop)) {\n prop = { ...prop, anyOf: [...prop.anyOf, { type: 'null' }] }\n }\n } else if (\n isSchemaObject(prop) &&\n prop.type &&\n !Array.isArray(prop.type)\n ) {\n prop = { ...prop, type: [prop.type, 'null'] }\n } else if (\n isSchemaObject(prop) &&\n Array.isArray(prop.type) &&\n !prop.type.includes('null')\n ) {\n prop = { ...prop, type: [...prop.type, 'null'] }\n }\n\n widenedHere = !originallyAcceptedNull && acceptsNull(prop)\n }\n\n properties[propName] = prop\n if (childMap || widenedHere) {\n propertyMaps[propName] = {\n ...(childMap ?? {}),\n ...(widenedHere ? { widened: true } : {}),\n }\n }\n }\n\n result.properties = properties\n result.required = allPropertyNames\n result.additionalProperties = false\n if (Object.keys(propertyMaps).length > 0) {\n nullWideningMap.properties = propertyMaps\n }\n }\n\n if (result.type === 'array' && result.items) {\n if (Array.isArray(result.items)) {\n const itemMaps: Array<NullWideningMap> = []\n result.items = result.items.map((item) => {\n if (!isSchemaObject(item)) {\n itemMaps.push({})\n return item\n }\n const nested = coerceStrictSchema(item, item.required || [])\n itemMaps.push(nested.nullWideningMap ?? {})\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n return nested.schema\n })\n if (itemMaps.some((map) => Object.keys(map).length > 0)) {\n nullWideningMap.items = itemMaps\n }\n } else {\n const nested = coerceStrictSchema(\n result.items,\n result.items.required || [],\n )\n result.items = nested.schema\n if (nested.nullWideningMap) {\n nullWideningMap.items = nested.nullWideningMap\n }\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n }\n }\n\n if (result.anyOf && Array.isArray(result.anyOf)) {\n const variants = result.anyOf.map((variant) =>\n coerceStrictSchema(variant, variant.required || []),\n )\n result.anyOf = variants.map((variant) => variant.schema)\n hasUntrackableAnyOfWidening ||= variants.some(\n (variant) =>\n variant.nullWideningMap !== undefined ||\n variant.hasUntrackableAnyOfWidening,\n )\n }\n\n if (result.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n return {\n schema: result,\n nullWideningMap: pruneMap(nullWideningMap),\n hasUntrackableAnyOfWidening,\n }\n}\n"],"mappings":";;;;;;;;;AAUA,IAAM,2CAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAWD,SAAgB,wBAAwB,MAAgB;CACtD,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,KAAK,IAAI,uBAAuB;CAChE,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU,OAAO;CAEtD,MAAM,MAA2B,CAAC;CAClC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;EAC/C,IACE,QAAQ,YACR,OAAO,UAAU,YACjB,CAAC,yBAAyB,IAAI,KAAK,GAEnC;EAEF,IAAI,OAAO,wBAAwB,KAAK;CAC1C;CACA,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,+BACd,QACA,kBACqB;CACrB,OAAO,sCAAsC,QAAQ,gBAAgB,CAAC,CAAC;AACzE;;;;;;AAgBA,SAAgB,sCACd,QACA,kBAC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ai-base",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.7",
|
|
4
4
|
"description": "Shared OpenAI SDK base adapters for TanStack AI providers using Chat Completions and Responses APIs.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -47,13 +47,13 @@
|
|
|
47
47
|
"@tanstack/ai-utils": "^0.4.0"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@tanstack/ai": "^0.
|
|
50
|
+
"@tanstack/ai": "^0.51.0"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@vitest/coverage-v8": "4.1.10",
|
|
54
54
|
"vite": "^8.2.1",
|
|
55
55
|
"zod": "^4.2.0",
|
|
56
|
-
"@tanstack/ai": "0.
|
|
56
|
+
"@tanstack/ai": "0.51.0"
|
|
57
57
|
},
|
|
58
58
|
"scripts": {
|
|
59
59
|
"build": "vite build",
|
|
@@ -17,6 +17,27 @@ describe('chat-completions tool converter', () => {
|
|
|
17
17
|
expect(out.function.strict).toBe(false)
|
|
18
18
|
expect(out.function.parameters).toEqual(booleanSchemaTool.inputSchema)
|
|
19
19
|
})
|
|
20
|
+
|
|
21
|
+
it('keeps draft-07 tuple items as an array in strict mode', () => {
|
|
22
|
+
const out = convertFunctionToolToChatCompletionsFormat(bboxTupleTool)
|
|
23
|
+
|
|
24
|
+
expect(out.function.strict).toBe(true)
|
|
25
|
+
expect(out.function.parameters).toMatchObject({
|
|
26
|
+
properties: {
|
|
27
|
+
bbox: {
|
|
28
|
+
type: 'array',
|
|
29
|
+
items: bboxItems,
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('falls back from strict mode when prefixItems is present', () => {
|
|
36
|
+
const out = convertFunctionToolToChatCompletionsFormat(prefixItemsTool)
|
|
37
|
+
|
|
38
|
+
expect(out.function.strict).toBe(false)
|
|
39
|
+
expect(out.function.parameters).toEqual(prefixItemsTool.inputSchema)
|
|
40
|
+
})
|
|
20
41
|
})
|
|
21
42
|
|
|
22
43
|
const booleanSchemaInput = {
|
|
@@ -32,6 +53,43 @@ const booleanSchemaTool = {
|
|
|
32
53
|
inputSchema: booleanSchemaInput,
|
|
33
54
|
} satisfies Tool
|
|
34
55
|
|
|
56
|
+
const bboxItems = [
|
|
57
|
+
{ type: 'number', minimum: -180 },
|
|
58
|
+
{ type: 'number', minimum: -90 },
|
|
59
|
+
{ type: 'number', maximum: 180 },
|
|
60
|
+
{ type: 'number', maximum: 90 },
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
const bboxTupleTool: Tool = {
|
|
64
|
+
name: 'set_bbox',
|
|
65
|
+
description: 'Set a bounding box',
|
|
66
|
+
inputSchema: {
|
|
67
|
+
type: 'object',
|
|
68
|
+
properties: {
|
|
69
|
+
bbox: {
|
|
70
|
+
type: 'array',
|
|
71
|
+
items: bboxItems,
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
required: ['bbox'],
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const prefixItemsTool: Tool = {
|
|
79
|
+
name: 'set_pair',
|
|
80
|
+
description: 'Set a prefix-item pair',
|
|
81
|
+
inputSchema: {
|
|
82
|
+
type: 'object',
|
|
83
|
+
properties: {
|
|
84
|
+
pair: {
|
|
85
|
+
type: 'array',
|
|
86
|
+
prefixItems: [{ type: 'string' }, { type: 'number' }],
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
required: ['pair'],
|
|
90
|
+
},
|
|
91
|
+
}
|
|
92
|
+
|
|
35
93
|
const anyOfOptionalVariantTool: Tool = {
|
|
36
94
|
name: 'store_variant',
|
|
37
95
|
description: 'Store a union variant',
|
package/src/tools/shell-tool.ts
CHANGED
|
@@ -20,6 +20,32 @@ export interface ShellToolFactoryConfig {
|
|
|
20
20
|
environment?: NonNullable<ShellToolConfig['environment']>
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/**
|
|
24
|
+
* Validate skill references carried by a shell `environment`. Previously the
|
|
25
|
+
* factory validated nothing, so a malformed `skill_id` surfaced as an unframed
|
|
26
|
+
* provider 400. Only `skill_reference` entries carry a `skill_id`; inline and
|
|
27
|
+
* local skills are shaped differently and left untouched.
|
|
28
|
+
*
|
|
29
|
+
* ponytail: OpenAI documents no client-checkable count cap for shell skills
|
|
30
|
+
* (unlike Anthropic's 8), so we validate `skill_id` format only and do not
|
|
31
|
+
* fabricate a `SkillLimitError` count limit. Add one here if OpenAI publishes a cap.
|
|
32
|
+
*/
|
|
33
|
+
function validateShellEnvironment(
|
|
34
|
+
environment: ShellToolFactoryConfig['environment'],
|
|
35
|
+
): void {
|
|
36
|
+
const skills =
|
|
37
|
+
environment && 'skills' in environment ? environment.skills : undefined
|
|
38
|
+
if (!skills) return
|
|
39
|
+
for (const skill of skills) {
|
|
40
|
+
if ('skill_id' in skill) {
|
|
41
|
+
const id = skill.skill_id
|
|
42
|
+
if (id.length < 1 || id.length > 64) {
|
|
43
|
+
throw new Error('skill_id must be between 1 and 64 characters.')
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
23
49
|
/**
|
|
24
50
|
* Converts a standard Tool to OpenAI ShellTool format, preserving any
|
|
25
51
|
* `environment` (container config + skills) stored in metadata.
|
|
@@ -42,6 +68,7 @@ export function convertShellToolToAdapterFormat(tool: Tool): ShellToolConfig {
|
|
|
42
68
|
* re-wrap this in their own package.
|
|
43
69
|
*/
|
|
44
70
|
export function shellTool(config: ShellToolFactoryConfig = {}): Tool {
|
|
71
|
+
validateShellEnvironment(config.environment)
|
|
45
72
|
return openAIProviderTool(
|
|
46
73
|
{
|
|
47
74
|
name: 'shell',
|
|
@@ -104,6 +104,8 @@ export function makeStructuredOutputCompatibleWithMap(
|
|
|
104
104
|
* emit these.
|
|
105
105
|
*
|
|
106
106
|
* - `oneOf` / `allOf` / `not` — combinator keywords strict mode rejects
|
|
107
|
+
* - `prefixItems` — 2020-12 tuple keyword. openai-node's strict transform
|
|
108
|
+
* rejects it, so we send those tools with `strict: false` instead
|
|
107
109
|
* - `$ref` / `$defs` / `definitions` — references and definition pools whose
|
|
108
110
|
* object subschemas escape the `additionalProperties: false` normalization
|
|
109
111
|
* strict mode requires
|
|
@@ -112,6 +114,7 @@ const STRICT_UNSUPPORTED_KEYWORDS: ReadonlyArray<string> = [
|
|
|
112
114
|
'oneOf',
|
|
113
115
|
'allOf',
|
|
114
116
|
'not',
|
|
117
|
+
'prefixItems',
|
|
115
118
|
'$ref',
|
|
116
119
|
'$defs',
|
|
117
120
|
'definitions',
|
|
@@ -141,7 +144,7 @@ const TYPE_INDICATOR_KEYWORDS: ReadonlyArray<string> = [
|
|
|
141
144
|
* sent with `strict: false`. Two ways that happens:
|
|
142
145
|
*
|
|
143
146
|
* 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in
|
|
144
|
-
* the tree (`oneOf`/`allOf`/`not`/`$ref`/`$defs`).
|
|
147
|
+
* the tree (`oneOf`/`allOf`/`not`/`prefixItems`/`$ref`/`$defs`).
|
|
145
148
|
* 2. It contains a *typeless* schema node — a property/items/anyOf entry with
|
|
146
149
|
* no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`
|
|
147
150
|
* produces. Strict mode rejects typeless schemas.
|
|
@@ -331,15 +334,10 @@ function coerceStrictSchema(
|
|
|
331
334
|
prop = nested.schema
|
|
332
335
|
childMap = nested.nullWideningMap
|
|
333
336
|
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
|
|
334
|
-
} else if (isSchemaObject(prop) && prop.type === 'array'
|
|
335
|
-
const nested = coerceStrictSchema(prop
|
|
336
|
-
prop =
|
|
337
|
-
...prop,
|
|
338
|
-
items: nested.schema,
|
|
339
|
-
}
|
|
337
|
+
} else if (isSchemaObject(prop) && prop.type === 'array') {
|
|
338
|
+
const nested = coerceStrictSchema(prop, [])
|
|
339
|
+
prop = nested.schema
|
|
340
340
|
childMap = nested.nullWideningMap
|
|
341
|
-
? { items: nested.nullWideningMap }
|
|
342
|
-
: undefined
|
|
343
341
|
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
|
|
344
342
|
} else if (isSchemaObject(prop) && prop.anyOf) {
|
|
345
343
|
const nested = coerceStrictSchema(prop, prop.required || [])
|
|
@@ -411,12 +409,32 @@ function coerceStrictSchema(
|
|
|
411
409
|
}
|
|
412
410
|
|
|
413
411
|
if (result.type === 'array' && result.items) {
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
412
|
+
if (Array.isArray(result.items)) {
|
|
413
|
+
const itemMaps: Array<NullWideningMap> = []
|
|
414
|
+
result.items = result.items.map((item) => {
|
|
415
|
+
if (!isSchemaObject(item)) {
|
|
416
|
+
itemMaps.push({})
|
|
417
|
+
return item
|
|
418
|
+
}
|
|
419
|
+
const nested = coerceStrictSchema(item, item.required || [])
|
|
420
|
+
itemMaps.push(nested.nullWideningMap ?? {})
|
|
421
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
|
|
422
|
+
return nested.schema
|
|
423
|
+
})
|
|
424
|
+
if (itemMaps.some((map) => Object.keys(map).length > 0)) {
|
|
425
|
+
nullWideningMap.items = itemMaps
|
|
426
|
+
}
|
|
427
|
+
} else {
|
|
428
|
+
const nested = coerceStrictSchema(
|
|
429
|
+
result.items,
|
|
430
|
+
result.items.required || [],
|
|
431
|
+
)
|
|
432
|
+
result.items = nested.schema
|
|
433
|
+
if (nested.nullWideningMap) {
|
|
434
|
+
nullWideningMap.items = nested.nullWideningMap
|
|
435
|
+
}
|
|
436
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
|
|
418
437
|
}
|
|
419
|
-
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
|
|
420
438
|
}
|
|
421
439
|
|
|
422
440
|
if (result.anyOf && Array.isArray(result.anyOf)) {
|