@tanstack/ai-mistral 0.3.4 → 0.4.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.
Files changed (42) hide show
  1. package/dist/esm/adapters/text.d.ts +2 -2
  2. package/dist/esm/adapters/text.js +16 -12
  3. package/dist/esm/adapters/text.js.map +1 -1
  4. package/dist/esm/index.d.ts +2 -2
  5. package/dist/esm/index.js +2 -2
  6. package/dist/esm/model-meta.d.ts +71 -0
  7. package/dist/esm/model-meta.js +335 -242
  8. package/dist/esm/model-meta.js.map +1 -1
  9. package/dist/esm/tools/function-tool.d.ts +4 -5
  10. package/dist/esm/tools/function-tool.js +7 -8
  11. package/dist/esm/tools/function-tool.js.map +1 -1
  12. package/dist/esm/tools/function-tool.test.d.ts +1 -0
  13. package/dist/esm/utils/client.d.ts +12 -0
  14. package/dist/esm/utils/client.js +9 -5
  15. package/dist/esm/utils/client.js.map +1 -1
  16. package/dist/esm/utils/schema-converter.d.ts +15 -15
  17. package/dist/esm/utils/schema-converter.js +173 -50
  18. package/dist/esm/utils/schema-converter.js.map +1 -1
  19. package/dist/esm/utils/schema-converter.test.d.ts +1 -0
  20. package/dist/esm/utils/tool-input-normalizer.d.ts +8 -0
  21. package/dist/esm/utils/tool-input-normalizer.js +34 -0
  22. package/dist/esm/utils/tool-input-normalizer.js.map +1 -0
  23. package/dist/esm/utils/tool-input-normalizer.test.d.ts +1 -0
  24. package/dist/esm/vertex/auth.d.ts +29 -0
  25. package/dist/esm/vertex/auth.js +62 -0
  26. package/dist/esm/vertex/auth.js.map +1 -0
  27. package/dist/esm/vertex/index.d.ts +12 -0
  28. package/dist/esm/vertex/index.js +26 -0
  29. package/dist/esm/vertex/index.js.map +1 -0
  30. package/package.json +16 -4
  31. package/src/adapters/text.ts +40 -20
  32. package/src/index.ts +6 -1
  33. package/src/model-meta.ts +70 -0
  34. package/src/tools/function-tool.test.ts +32 -0
  35. package/src/tools/function-tool.ts +11 -11
  36. package/src/utils/client.ts +41 -6
  37. package/src/utils/schema-converter.test.ts +256 -0
  38. package/src/utils/schema-converter.ts +251 -88
  39. package/src/utils/tool-input-normalizer.test.ts +50 -0
  40. package/src/utils/tool-input-normalizer.ts +42 -0
  41. package/src/vertex/auth.ts +154 -0
  42. package/src/vertex/index.ts +50 -0
@@ -1,13 +1,12 @@
1
- import { makeMistralStructuredOutputCompatible } from "../utils/schema-converter.js";
1
+ import { makeMistralStructuredOutputCompatibleWithMap } from "../utils/schema-converter.js";
2
2
  //#region src/tools/function-tool.ts
3
3
  /**
4
4
  * Converts a standard Tool to Mistral ChatCompletionTool format.
5
5
  *
6
- * Tool schemas are already converted to JSON Schema in the ai layer.
7
- * We apply Mistral-specific transformations for strict mode:
8
- * - All properties in required array
9
- * - Optional fields made nullable
10
- * - additionalProperties: false
6
+ * Tool schemas are already JSON Schema in the ai layer. When the schema can
7
+ * be inverted, rewrite it for strict mode (required, nullable optionals,
8
+ * `additionalProperties: false`) and set `strict: true`. Otherwise leave the
9
+ * schema intact and set `strict: false`.
11
10
  */
12
11
  function convertFunctionToolToAdapterFormat(tool) {
13
12
  const baseSchema = tool.inputSchema ?? {
@@ -19,14 +18,14 @@ function convertFunctionToolToAdapterFormat(tool) {
19
18
  ...baseSchema,
20
19
  properties: {}
21
20
  } : { ...baseSchema };
22
- const jsonSchema = makeMistralStructuredOutputCompatible(inputSchema, inputSchema.required || []);
21
+ const { schema: jsonSchema, strict } = makeMistralStructuredOutputCompatibleWithMap(inputSchema, inputSchema.required || []);
23
22
  return {
24
23
  type: "function",
25
24
  function: {
26
25
  name: tool.name,
27
26
  description: tool.description,
28
27
  parameters: jsonSchema,
29
- strict: true
28
+ strict
30
29
  }
31
30
  };
32
31
  }
@@ -1 +1 @@
1
- {"version":3,"file":"function-tool.js","names":[],"sources":["../../../src/tools/function-tool.ts"],"sourcesContent":["import { makeMistralStructuredOutputCompatible } from '../utils/schema-converter'\nimport type { JSONSchema, Tool } from '@tanstack/ai'\nimport type { ChatCompletionTool } from '../message-types'\n\nexport type FunctionTool = ChatCompletionTool\n\n/**\n * Converts a standard Tool to Mistral ChatCompletionTool format.\n *\n * Tool schemas are already converted to JSON Schema in the ai layer.\n * We apply Mistral-specific transformations for strict mode:\n * - All properties in required array\n * - Optional fields made nullable\n * - additionalProperties: false\n */\nexport function convertFunctionToolToAdapterFormat(tool: Tool): FunctionTool {\n const baseSchema = (tool.inputSchema ?? {\n type: 'object',\n properties: {},\n required: [],\n }) as JSONSchema\n\n const inputSchema: JSONSchema =\n baseSchema.type === 'object' && !baseSchema.properties\n ? { ...baseSchema, properties: {} }\n : { ...baseSchema }\n\n const jsonSchema = makeMistralStructuredOutputCompatible(\n inputSchema,\n inputSchema.required || [],\n )\n\n return {\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n strict: true,\n },\n } satisfies FunctionTool\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,mCAAmC,MAA0B;CAC3E,MAAM,aAAc,KAAK,eAAe;EACtC,MAAM;EACN,YAAY,CAAC;EACb,UAAU,CAAC;CACb;CAEA,MAAM,cACJ,WAAW,SAAS,YAAY,CAAC,WAAW,aACxC;EAAE,GAAG;EAAY,YAAY,CAAC;CAAE,IAChC,EAAE,GAAG,WAAW;CAEtB,MAAM,aAAa,sCACjB,aACA,YAAY,YAAY,CAAC,CAC3B;CAEA,OAAO;EACL,MAAM;EACN,UAAU;GACR,MAAM,KAAK;GACX,aAAa,KAAK;GAClB,YAAY;GACZ,QAAQ;EACV;CACF;AACF"}
1
+ {"version":3,"file":"function-tool.js","names":[],"sources":["../../../src/tools/function-tool.ts"],"sourcesContent":["import { makeMistralStructuredOutputCompatibleWithMap } from '../utils/schema-converter'\nimport type { JSONSchema, Tool } from '@tanstack/ai'\nimport type { ChatCompletionTool } from '../message-types'\n\nexport type FunctionTool = ChatCompletionTool\n\n/**\n * Converts a standard Tool to Mistral ChatCompletionTool format.\n *\n * Tool schemas are already JSON Schema in the ai layer. When the schema can\n * be inverted, rewrite it for strict mode (required, nullable optionals,\n * `additionalProperties: false`) and set `strict: true`. Otherwise leave the\n * schema intact and set `strict: false`.\n */\nexport function convertFunctionToolToAdapterFormat(tool: Tool): FunctionTool {\n const baseSchema = (tool.inputSchema ?? {\n type: 'object',\n properties: {},\n required: [],\n }) as JSONSchema\n\n const inputSchema: JSONSchema =\n baseSchema.type === 'object' && !baseSchema.properties\n ? { ...baseSchema, properties: {} }\n : { ...baseSchema }\n\n const { schema: jsonSchema, strict } =\n makeMistralStructuredOutputCompatibleWithMap(\n inputSchema,\n inputSchema.required || [],\n )\n\n return {\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n strict,\n },\n } satisfies FunctionTool\n}\n"],"mappings":";;;;;;;;;;AAcA,SAAgB,mCAAmC,MAA0B;CAC3E,MAAM,aAAc,KAAK,eAAe;EACtC,MAAM;EACN,YAAY,CAAC;EACb,UAAU,CAAC;CACb;CAEA,MAAM,cACJ,WAAW,SAAS,YAAY,CAAC,WAAW,aACxC;EAAE,GAAG;EAAY,YAAY,CAAC;CAAE,IAChC,EAAE,GAAG,WAAW;CAEtB,MAAM,EAAE,QAAQ,YAAY,WAC1B,6CACE,aACA,YAAY,YAAY,CAAC,CAC3B;CAEF,OAAO;EACL,MAAM;EACN,UAAU;GACR,MAAM,KAAK;GACX,aAAa,KAAK;GAClB,YAAY;GACZ;EACF;CACF;AACF"}
@@ -0,0 +1 @@
1
+ export {};
@@ -8,6 +8,18 @@ export interface MistralClientConfig {
8
8
  timeoutMs?: number;
9
9
  /** Optional default headers to include with every request. */
10
10
  defaultHeaders?: Record<string, string>;
11
+ /**
12
+ * Optional Google / Vertex access token. When set, it replaces
13
+ * `apiKey` on the Authorization header.
14
+ */
15
+ getAccessToken?: () => Promise<string>;
16
+ /**
17
+ * Optional chat completions URL. Vertex uses this for
18
+ * `:rawPredict` and `:streamRawPredict`.
19
+ */
20
+ resolveRequestUrl?: (stream: boolean) => string;
21
+ /** Optional model id sent on the wire. Vertex uses publisher model ids. */
22
+ requestModel?: string;
11
23
  }
12
24
  /**
13
25
  * Creates a Mistral SDK client instance.
@@ -4,13 +4,17 @@ import { HTTPClient, Mistral } from "@mistralai/mistralai";
4
4
  * Creates a Mistral SDK client instance.
5
5
  */
6
6
  function createMistralClient(config) {
7
- const { apiKey, serverURL, timeoutMs, defaultHeaders } = config;
7
+ const { apiKey, serverURL, timeoutMs, defaultHeaders, getAccessToken, resolveRequestUrl } = config;
8
+ const needsHook = defaultHeaders !== void 0 && Object.keys(defaultHeaders).length > 0 || getAccessToken !== void 0 || resolveRequestUrl !== void 0;
8
9
  let httpClient;
9
- if (defaultHeaders && Object.keys(defaultHeaders).length > 0) {
10
+ if (needsHook) {
10
11
  httpClient = new HTTPClient();
11
- httpClient.addHook("beforeRequest", (req) => {
12
- for (const [key, value] of Object.entries(defaultHeaders)) req.headers.set(key, value);
13
- return req;
12
+ httpClient.addHook("beforeRequest", async (req) => {
13
+ const nextUrl = resolveRequestUrl === void 0 ? req.url : resolveRequestUrl(false);
14
+ const next = new Request(nextUrl, req);
15
+ if (defaultHeaders) for (const [key, value] of Object.entries(defaultHeaders)) next.headers.set(key, value);
16
+ if (getAccessToken !== void 0) next.headers.set("Authorization", `Bearer ${await getAccessToken()}`);
17
+ return next;
14
18
  });
15
19
  }
16
20
  return new Mistral({
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../../src/utils/client.ts"],"sourcesContent":["import { HTTPClient, Mistral } from '@mistralai/mistralai'\n\nexport interface MistralClientConfig {\n /** Mistral API key. */\n apiKey: string\n\n /** Optional server URL override. */\n serverURL?: string\n\n /** Optional request timeout (ms). */\n timeoutMs?: number\n\n /** Optional default headers to include with every request. */\n defaultHeaders?: Record<string, string>\n}\n\n/**\n * Creates a Mistral SDK client instance.\n */\nexport function createMistralClient(config: MistralClientConfig): Mistral {\n const { apiKey, serverURL, timeoutMs, defaultHeaders } = config\n\n let httpClient: HTTPClient | undefined\n if (defaultHeaders && Object.keys(defaultHeaders).length > 0) {\n httpClient = new HTTPClient()\n httpClient.addHook('beforeRequest', (req) => {\n for (const [key, value] of Object.entries(defaultHeaders)) {\n req.headers.set(key, value)\n }\n return req\n })\n }\n\n return new Mistral({\n apiKey,\n ...(serverURL !== undefined ? { serverURL } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n ...(httpClient !== undefined ? { httpClient } : {}),\n })\n}\n\n/**\n * Gets Mistral API key from environment variables.\n * @throws Error if MISTRAL_API_KEY is not found\n */\nexport function getMistralApiKeyFromEnv(): string {\n let key: string | undefined\n\n if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {\n key = process.env.MISTRAL_API_KEY\n } else {\n const g = globalThis as { window?: { env?: Record<string, string> } }\n key = g.window?.env?.MISTRAL_API_KEY\n }\n\n if (!key) {\n throw new Error(\n 'MISTRAL_API_KEY is required. In Node.js set it as an environment variable; in browser environments inject it via window.env.MISTRAL_API_KEY or use the factory function with an explicit API key.',\n )\n }\n\n return key\n}\n\n/**\n * Generates a unique ID with a prefix.\n */\nexport function generateId(prefix: string): string {\n return `${prefix}-${crypto.randomUUID()}`\n}\n"],"mappings":";;;;;AAmBA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,EAAE,QAAQ,WAAW,WAAW,mBAAmB;CAEzD,IAAI;CACJ,IAAI,kBAAkB,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,GAAG;EAC5D,aAAa,IAAI,WAAW;EAC5B,WAAW,QAAQ,kBAAkB,QAAQ;GAC3C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACtD,IAAI,QAAQ,IAAI,KAAK,KAAK;GAE5B,OAAO;EACT,CAAC;CACH;CAEA,OAAO,IAAI,QAAQ;EACjB;EACA,GAAI,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC;EAC/C,GAAI,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC;EAC/C,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;CACnD,CAAC;AACH;;;;;AAMA,SAAgB,0BAAkC;CAChD,IAAI;CAEJ,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,QAAQ,aAC3D,MAAM,QAAQ,IAAI;MAGlB,MAAM,WAAE,QAAQ,KAAK;CAGvB,IAAI,CAAC,KACH,MAAM,IAAI,MACR,mMACF;CAGF,OAAO;AACT;;;;AAKA,SAAgB,WAAW,QAAwB;CACjD,OAAO,GAAG,OAAO,GAAG,OAAO,WAAW;AACxC"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../../src/utils/client.ts"],"sourcesContent":["import { HTTPClient, Mistral } from '@mistralai/mistralai'\n\nexport interface MistralClientConfig {\n /** Mistral API key. */\n apiKey: string\n\n /** Optional server URL override. */\n serverURL?: string\n\n /** Optional request timeout (ms). */\n timeoutMs?: number\n\n /** Optional default headers to include with every request. */\n defaultHeaders?: Record<string, string>\n\n /**\n * Optional Google / Vertex access token. When set, it replaces\n * `apiKey` on the Authorization header.\n */\n getAccessToken?: () => Promise<string>\n\n /**\n * Optional chat completions URL. Vertex uses this for\n * `:rawPredict` and `:streamRawPredict`.\n */\n resolveRequestUrl?: (stream: boolean) => string\n\n /** Optional model id sent on the wire. Vertex uses publisher model ids. */\n requestModel?: string\n}\n\n/**\n * Creates a Mistral SDK client instance.\n */\nexport function createMistralClient(config: MistralClientConfig): Mistral {\n const {\n apiKey,\n serverURL,\n timeoutMs,\n defaultHeaders,\n getAccessToken,\n resolveRequestUrl,\n } = config\n\n const needsHook =\n (defaultHeaders !== undefined && Object.keys(defaultHeaders).length > 0) ||\n getAccessToken !== undefined ||\n resolveRequestUrl !== undefined\n\n let httpClient: HTTPClient | undefined\n if (needsHook) {\n httpClient = new HTTPClient()\n httpClient.addHook('beforeRequest', async (req) => {\n const nextUrl =\n resolveRequestUrl === undefined ? req.url : resolveRequestUrl(false)\n const next = new Request(nextUrl, req)\n if (defaultHeaders) {\n for (const [key, value] of Object.entries(defaultHeaders)) {\n next.headers.set(key, value)\n }\n }\n if (getAccessToken !== undefined) {\n next.headers.set('Authorization', `Bearer ${await getAccessToken()}`)\n }\n return next\n })\n }\n\n return new Mistral({\n apiKey,\n ...(serverURL !== undefined ? { serverURL } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n ...(httpClient !== undefined ? { httpClient } : {}),\n })\n}\n\n/**\n * Gets Mistral API key from environment variables.\n * @throws Error if MISTRAL_API_KEY is not found\n */\nexport function getMistralApiKeyFromEnv(): string {\n let key: string | undefined\n\n if (typeof process !== 'undefined' && typeof process.env !== 'undefined') {\n key = process.env.MISTRAL_API_KEY\n } else {\n const g = globalThis as { window?: { env?: Record<string, string> } }\n key = g.window?.env?.MISTRAL_API_KEY\n }\n\n if (!key) {\n throw new Error(\n 'MISTRAL_API_KEY is required. In Node.js set it as an environment variable; in browser environments inject it via window.env.MISTRAL_API_KEY or use the factory function with an explicit API key.',\n )\n }\n\n return key\n}\n\n/**\n * Generates a unique ID with a prefix.\n */\nexport function generateId(prefix: string): string {\n return `${prefix}-${crypto.randomUUID()}`\n}\n"],"mappings":";;;;;AAkCA,SAAgB,oBAAoB,QAAsC;CACxE,MAAM,EACJ,QACA,WACA,WACA,gBACA,gBACA,sBACE;CAEJ,MAAM,YACH,mBAAmB,KAAA,KAAa,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,KACtE,mBAAmB,KAAA,KACnB,sBAAsB,KAAA;CAExB,IAAI;CACJ,IAAI,WAAW;EACb,aAAa,IAAI,WAAW;EAC5B,WAAW,QAAQ,iBAAiB,OAAO,QAAQ;GACjD,MAAM,UACJ,sBAAsB,KAAA,IAAY,IAAI,MAAM,kBAAkB,KAAK;GACrE,MAAM,OAAO,IAAI,QAAQ,SAAS,GAAG;GACrC,IAAI,gBACF,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,cAAc,GACtD,KAAK,QAAQ,IAAI,KAAK,KAAK;GAG/B,IAAI,mBAAmB,KAAA,GACrB,KAAK,QAAQ,IAAI,iBAAiB,UAAU,MAAM,eAAe,GAAG;GAEtE,OAAO;EACT,CAAC;CACH;CAEA,OAAO,IAAI,QAAQ;EACjB;EACA,GAAI,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC;EAC/C,GAAI,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC;EAC/C,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;CACnD,CAAC;AACH;;;;;AAMA,SAAgB,0BAAkC;CAChD,IAAI;CAEJ,IAAI,OAAO,YAAY,eAAe,OAAO,QAAQ,QAAQ,aAC3D,MAAM,QAAQ,IAAI;MAGlB,MAAM,WAAE,QAAQ,KAAK;CAGvB,IAAI,CAAC,KACH,MAAM,IAAI,MACR,mMACF;CAGF,OAAO;AACT;;;;AAKA,SAAgB,WAAW,QAAwB;CACjD,OAAO,GAAG,OAAO,GAAG,OAAO,WAAW;AACxC"}
@@ -1,18 +1,18 @@
1
+ import { NullWideningMap } from '@tanstack/ai-utils';
2
+ interface MistralStructuredOutputCompatibility {
3
+ schema: Record<string, any>;
4
+ nullWideningMap: NullWideningMap | undefined;
5
+ strict: boolean;
6
+ }
1
7
  /**
2
- * Recursively transform null values to undefined in an object.
8
+ * Convert a schema for Mistral strict mode and record how to invert it.
3
9
  *
4
- * This is needed because Mistral's structured output may require optional
5
- * fields to be declared nullable. When Mistral returns null for optional
6
- * fields, we convert them back to undefined to match the original Zod schema.
10
+ * Outcomes:
11
+ * - `strict: true` — rewritten schema (`required` closed, optionals null-widened).
12
+ * `nullWideningMap` marks synthesized optional nulls only; already-nullable
13
+ * fields and enum/const repairs on required nodes are unmarked.
14
+ * - `strict: false` — original schema, no map. Used when `oneOf`/`allOf`/`not`/
15
+ * `$ref`/`$defs` appear, or an `anyOf` branch would need a branch-dependent map.
7
16
  */
8
- export declare function transformNullsToUndefined<T>(obj: T): T;
9
- /**
10
- * Transform a JSON schema to be compatible with Mistral's structured output
11
- * requirements when `strict: true` is used.
12
- *
13
- * Mistral (in strict mode) requires:
14
- * - All properties must be in the `required` array
15
- * - Optional fields should have null added to their type union
16
- * - additionalProperties must be false for objects
17
- */
18
- export declare function makeMistralStructuredOutputCompatible(schema: Record<string, any>, originalRequired?: Array<string>): Record<string, any>;
17
+ export declare function makeMistralStructuredOutputCompatibleWithMap(schema: Record<string, any>, originalRequired?: Array<string>): MistralStructuredOutputCompatibility;
18
+ export {};
@@ -1,77 +1,200 @@
1
1
  //#region src/utils/schema-converter.ts
2
2
  /**
3
- * Recursively transform null values to undefined in an object.
3
+ * Convert a schema for Mistral strict mode and record how to invert it.
4
4
  *
5
- * This is needed because Mistral's structured output may require optional
6
- * fields to be declared nullable. When Mistral returns null for optional
7
- * fields, we convert them back to undefined to match the original Zod schema.
5
+ * Outcomes:
6
+ * - `strict: true` — rewritten schema (`required` closed, optionals null-widened).
7
+ * `nullWideningMap` marks synthesized optional nulls only; already-nullable
8
+ * fields and enum/const repairs on required nodes are unmarked.
9
+ * - `strict: false` — original schema, no map. Used when `oneOf`/`allOf`/`not`/
10
+ * `$ref`/`$defs` appear, or an `anyOf` branch would need a branch-dependent map.
8
11
  */
9
- function transformNullsToUndefined(obj) {
10
- if (obj === null) return;
11
- if (Array.isArray(obj)) return obj.map((item) => transformNullsToUndefined(item));
12
- if (typeof obj === "object" && Object.getPrototypeOf(obj) === Object.prototype) {
13
- const result = {};
14
- for (const [key, value] of Object.entries(obj)) result[key] = transformNullsToUndefined(value);
15
- return result;
12
+ function makeMistralStructuredOutputCompatibleWithMap(schema, originalRequired = []) {
13
+ if (containsUnsupportedStrictKeyword(schema)) return {
14
+ schema,
15
+ nullWideningMap: void 0,
16
+ strict: false
17
+ };
18
+ const converted = coerceMistralStrictSchema(schema, originalRequired);
19
+ if (converted.hasUntrackableAnyOfWidening) return {
20
+ schema,
21
+ nullWideningMap: void 0,
22
+ strict: false
23
+ };
24
+ return {
25
+ schema: converted.schema,
26
+ nullWideningMap: converted.nullWideningMap,
27
+ strict: true
28
+ };
29
+ }
30
+ var UNSUPPORTED_STRICT_KEYWORDS = [
31
+ "oneOf",
32
+ "allOf",
33
+ "not",
34
+ "$ref",
35
+ "$defs",
36
+ "definitions"
37
+ ];
38
+ /**
39
+ * Tree-wide key scan for `oneOf`/`allOf`/`not`/`$ref`/`$defs`/`definitions`.
40
+ * Conservative: a property literally named e.g. `oneOf` also trips fallback.
41
+ * `anyOf` is handled separately in the coerce walk.
42
+ */
43
+ function containsUnsupportedStrictKeyword(node) {
44
+ if (Array.isArray(node)) return node.some(containsUnsupportedStrictKeyword);
45
+ if (!isSchemaObject(node)) return false;
46
+ return Object.entries(node).some(([key, value]) => UNSUPPORTED_STRICT_KEYWORDS.includes(key) || containsUnsupportedStrictKeyword(value));
47
+ }
48
+ function pruneMap(map) {
49
+ return Object.keys(map).length > 0 ? map : void 0;
50
+ }
51
+ function isSchemaObject(schema) {
52
+ return typeof schema === "object" && schema !== null && !Array.isArray(schema);
53
+ }
54
+ function coerceArrayItems(items) {
55
+ if (Array.isArray(items)) {
56
+ const converted = items.map((item) => isSchemaObject(item) ? coerceMistralStrictSchema(item, item.required || []) : {
57
+ schema: item,
58
+ nullWideningMap: void 0,
59
+ hasUntrackableAnyOfWidening: false
60
+ });
61
+ const itemMaps = converted.map((item) => item.nullWideningMap);
62
+ return {
63
+ schema: converted.map((item) => item.schema),
64
+ itemMap: itemMaps.some(Boolean) ? itemMaps.map((map) => map ?? {}) : void 0,
65
+ hasUntrackableAnyOfWidening: converted.some((item) => item.hasUntrackableAnyOfWidening)
66
+ };
16
67
  }
17
- return obj;
68
+ if (isSchemaObject(items)) {
69
+ const converted = coerceMistralStrictSchema(items, items.required || []);
70
+ return {
71
+ schema: converted.schema,
72
+ itemMap: converted.nullWideningMap,
73
+ hasUntrackableAnyOfWidening: converted.hasUntrackableAnyOfWidening
74
+ };
75
+ }
76
+ return {
77
+ schema: items,
78
+ itemMap: void 0,
79
+ hasUntrackableAnyOfWidening: false
80
+ };
81
+ }
82
+ function schemaTypeIncludes(schema, typeName) {
83
+ return schema.type === typeName || Array.isArray(schema.type) && schema.type.includes(typeName);
84
+ }
85
+ function admitNullInEnumOrConst(prop) {
86
+ if ("const" in prop && prop.const !== null) {
87
+ const { const: constValue, ...withoutConst } = prop;
88
+ return {
89
+ ...withoutConst,
90
+ enum: [constValue, null]
91
+ };
92
+ }
93
+ if (Array.isArray(prop.enum) && !prop.enum.includes(null)) return {
94
+ ...prop,
95
+ enum: [...prop.enum, null]
96
+ };
97
+ return prop;
18
98
  }
19
99
  /**
20
- * Transform a JSON schema to be compatible with Mistral's structured output
21
- * requirements when `strict: true` is used.
22
- *
23
- * Mistral (in strict mode) requires:
24
- * - All properties must be in the `required` array
25
- * - Optional fields should have null added to their type union
26
- * - additionalProperties must be false for objects
100
+ * True when `type`/`enum`/`const`/`anyOf` already admit null. `oneOf`/`allOf`/
101
+ * `not` are not inspected — callers must reject those first.
27
102
  */
28
- function makeMistralStructuredOutputCompatible(schema, originalRequired = []) {
103
+ function acceptsNull(schema) {
104
+ if (schema === true) return true;
105
+ if (!isSchemaObject(schema)) return false;
106
+ if ("const" in schema && schema.const !== null) return false;
107
+ if (Array.isArray(schema.enum) && !schema.enum.includes(null)) return false;
108
+ if (typeof schema.type === "string" && schema.type !== "null") return false;
109
+ if (Array.isArray(schema.type) && !schema.type.includes("null")) return false;
110
+ if (Array.isArray(schema.anyOf) && !schema.anyOf.some((variant) => acceptsNull(variant))) return false;
111
+ return true;
112
+ }
113
+ function coerceMistralStrictSchema(schema, originalRequired) {
29
114
  const result = { ...schema };
30
- if (result.type === "object") {
115
+ const nullWideningMap = {};
116
+ let hasUntrackableAnyOfWidening = false;
117
+ if (schemaTypeIncludes(result, "object")) {
31
118
  if (!result.properties) result.properties = {};
32
119
  const properties = { ...result.properties };
33
120
  const allPropertyNames = Object.keys(properties);
121
+ const propertyMaps = {};
34
122
  for (const propName of allPropertyNames) {
35
- const prop = properties[propName];
123
+ let prop = properties[propName];
36
124
  const wasOptional = !originalRequired.includes(propName);
37
- if (prop.type === "object" && prop.properties) {
38
- const converted = makeMistralStructuredOutputCompatible(prop, prop.required || []);
39
- if (wasOptional) properties[propName] = {
40
- ...converted,
41
- type: Array.isArray(converted.type) ? converted.type.includes("null") ? converted.type : [...converted.type, "null"] : [converted.type, "null"]
42
- };
43
- else properties[propName] = converted;
44
- } else if (prop.type === "array" && prop.items) {
45
- const converted = {
46
- ...prop,
47
- items: makeMistralStructuredOutputCompatible(prop.items, prop.items.required || [])
48
- };
49
- if (wasOptional) properties[propName] = {
50
- ...converted,
51
- type: Array.isArray(converted.type) ? converted.type.includes("null") ? converted.type : [...converted.type, "null"] : [converted.type, "null"]
52
- };
53
- else properties[propName] = converted;
54
- } else if (wasOptional) {
55
- if (prop.type && !Array.isArray(prop.type)) properties[propName] = {
125
+ let childMap;
126
+ let widenedHere = false;
127
+ if (isSchemaObject(prop) && schemaTypeIncludes(prop, "object") && prop.properties) {
128
+ const converted = coerceMistralStrictSchema(prop, prop.required || []);
129
+ prop = converted.schema;
130
+ childMap = converted.nullWideningMap;
131
+ hasUntrackableAnyOfWidening ||= converted.hasUntrackableAnyOfWidening;
132
+ } else if (isSchemaObject(prop) && schemaTypeIncludes(prop, "array") && prop.items != null) {
133
+ const convertedItems = coerceArrayItems(prop.items);
134
+ prop = {
56
135
  ...prop,
57
- type: [prop.type, "null"]
136
+ items: convertedItems.schema
58
137
  };
59
- else if (Array.isArray(prop.type) && !prop.type.includes("null")) properties[propName] = {
60
- ...prop,
61
- type: [...prop.type, "null"]
62
- };
63
- else if (!prop.type) properties[propName] = { anyOf: [prop, { type: "null" }] };
138
+ if (convertedItems.itemMap) childMap = { items: convertedItems.itemMap };
139
+ hasUntrackableAnyOfWidening ||= convertedItems.hasUntrackableAnyOfWidening;
140
+ } else if (isSchemaObject(prop) && Array.isArray(prop.anyOf)) {
141
+ const converted = coerceMistralStrictSchema(prop, prop.required || []);
142
+ prop = converted.schema;
143
+ childMap = converted.nullWideningMap;
144
+ hasUntrackableAnyOfWidening ||= converted.hasUntrackableAnyOfWidening;
145
+ }
146
+ if (!acceptsNull(prop)) {
147
+ if (wasOptional) {
148
+ if (isSchemaObject(prop)) prop = admitNullInEnumOrConst(prop);
149
+ if (isSchemaObject(prop) && prop.type && !Array.isArray(prop.type)) prop = {
150
+ ...prop,
151
+ type: [prop.type, "null"]
152
+ };
153
+ else if (isSchemaObject(prop) && Array.isArray(prop.type) && !prop.type.includes("null")) prop = {
154
+ ...prop,
155
+ type: [...prop.type, "null"]
156
+ };
157
+ else if (!isSchemaObject(prop) || !prop.type) prop = { anyOf: [prop, { type: "null" }] };
158
+ widenedHere = true;
159
+ } else if (isSchemaObject(prop) && schemaTypeIncludes(prop, "null")) prop = admitNullInEnumOrConst(prop);
64
160
  }
161
+ properties[propName] = prop;
162
+ if (childMap || widenedHere) propertyMaps[propName] = {
163
+ ...childMap ?? {},
164
+ ...widenedHere ? { widened: true } : {}
165
+ };
65
166
  }
66
167
  result.properties = properties;
67
168
  if (allPropertyNames.length > 0) result.required = allPropertyNames;
68
169
  else delete result.required;
69
170
  result.additionalProperties = false;
171
+ if (Object.keys(propertyMaps).length > 0) nullWideningMap.properties = propertyMaps;
172
+ }
173
+ if (schemaTypeIncludes(result, "array") && result.items != null) {
174
+ const convertedItems = coerceArrayItems(result.items);
175
+ result.items = convertedItems.schema;
176
+ if (convertedItems.itemMap) nullWideningMap.items = convertedItems.itemMap;
177
+ hasUntrackableAnyOfWidening ||= convertedItems.hasUntrackableAnyOfWidening;
178
+ }
179
+ if (Array.isArray(result.anyOf)) {
180
+ const variants = result.anyOf.map((variant) => {
181
+ if (!isSchemaObject(variant)) return {
182
+ schema: variant,
183
+ nullWideningMap: void 0,
184
+ hasUntrackableAnyOfWidening: false
185
+ };
186
+ return coerceMistralStrictSchema(variant, variant.required || []);
187
+ });
188
+ result.anyOf = variants.map((variant) => variant.schema);
189
+ hasUntrackableAnyOfWidening ||= variants.some((variant) => variant.nullWideningMap !== void 0 || variant.hasUntrackableAnyOfWidening);
70
190
  }
71
- if (result.type === "array" && result.items) result.items = makeMistralStructuredOutputCompatible(result.items, result.items.required || []);
72
- return result;
191
+ return {
192
+ schema: result,
193
+ nullWideningMap: pruneMap(nullWideningMap),
194
+ hasUntrackableAnyOfWidening
195
+ };
73
196
  }
74
197
  //#endregion
75
- export { makeMistralStructuredOutputCompatible, transformNullsToUndefined };
198
+ export { makeMistralStructuredOutputCompatibleWithMap };
76
199
 
77
200
  //# sourceMappingURL=schema-converter.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-converter.js","names":[],"sources":["../../../src/utils/schema-converter.ts"],"sourcesContent":["/**\n * Recursively transform null values to undefined in an object.\n *\n * This is needed because Mistral's structured output may require optional\n * fields to be declared nullable. When Mistral returns null for optional\n * fields, we convert them back to undefined to match the original Zod schema.\n */\nexport function transformNullsToUndefined<T>(obj: T): T {\n if (obj === null) {\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- generic T has no structural overlap with undefined; null→undefined conversion is this function's documented contract\n return undefined as unknown as T\n }\n\n if (Array.isArray(obj)) {\n // Preserve array length and indices — converting null elements to\n // undefined slots rather than dropping them. `Array<T | null>` schemas\n // depend on positional alignment.\n // oxlint-disable-next-line eslint-js/no-restricted-syntax -- the mapped array (unknown[]) has no structural overlap with generic T; positional null→undefined transform preserves the array shape T describes\n return obj.map((item) => transformNullsToUndefined(item)) as unknown as T\n }\n\n if (\n typeof obj === 'object' &&\n Object.getPrototypeOf(obj) === Object.prototype\n ) {\n // Preserve every key — `null` values become `undefined` values, but the\n // key itself is not removed. Schemas distinguishing absent vs explicit\n // null rely on this.\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n result[key] = transformNullsToUndefined(value)\n }\n return result as T\n }\n\n return obj\n}\n\n/**\n * Transform a JSON schema to be compatible with Mistral's structured output\n * requirements when `strict: true` is used.\n *\n * Mistral (in strict mode) 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 */\nexport function makeMistralStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired: Array<string> = [],\n): Record<string, any> {\n const result = { ...schema }\n\n if (result.type === 'object') {\n if (!result.properties) {\n result.properties = {}\n }\n const properties = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n\n for (const propName of allPropertyNames) {\n const prop = properties[propName]\n const wasOptional = !originalRequired.includes(propName)\n\n if (prop.type === 'object' && prop.properties) {\n const converted = makeMistralStructuredOutputCompatible(\n prop,\n prop.required || [],\n )\n if (wasOptional) {\n properties[propName] = {\n ...converted,\n type: Array.isArray(converted.type)\n ? converted.type.includes('null')\n ? converted.type\n : [...converted.type, 'null']\n : [converted.type, 'null'],\n }\n } else {\n properties[propName] = converted\n }\n } else if (prop.type === 'array' && prop.items) {\n const converted = {\n ...prop,\n items: makeMistralStructuredOutputCompatible(\n prop.items,\n prop.items.required || [],\n ),\n }\n if (wasOptional) {\n properties[propName] = {\n ...converted,\n type: Array.isArray(converted.type)\n ? converted.type.includes('null')\n ? converted.type\n : [...converted.type, 'null']\n : [converted.type, 'null'],\n }\n } else {\n properties[propName] = converted\n }\n } else if (wasOptional) {\n if (prop.type && !Array.isArray(prop.type)) {\n properties[propName] = {\n ...prop,\n type: [prop.type, 'null'],\n }\n } else if (Array.isArray(prop.type) && !prop.type.includes('null')) {\n properties[propName] = {\n ...prop,\n type: [...prop.type, 'null'],\n }\n } else if (!prop.type) {\n properties[propName] = { anyOf: [prop, { type: 'null' }] }\n }\n }\n }\n\n result.properties = properties\n if (allPropertyNames.length > 0) {\n result.required = allPropertyNames\n } else {\n delete result.required\n }\n result.additionalProperties = false\n }\n\n if (result.type === 'array' && result.items) {\n result.items = makeMistralStructuredOutputCompatible(\n result.items,\n result.items.required || [],\n )\n }\n\n return result\n}\n"],"mappings":";;;;;;;;AAOA,SAAgB,0BAA6B,KAAW;CACtD,IAAI,QAAQ,MAEV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ACV,CAAC,GAAG,UAAU,MAAM,MAAM,IAC5B,CAAC,UAAU,MAAM,MAAM;IAC7B;SAEA,WAAW,YAAY;GAE3B,OAAO,IAAI,aAAa;IACtB,IAAI,KAAK,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAAI,GACvC,WAAW,YAAY;KACrB,GAAG;KACH,MAAM,CAAC,KAAK,MAAM,MAAM;IAC1B;SACK,IAAI,MAAM,QAAQ,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS,MAAM,GAC/D,WAAW,YAAY;KACrB,GAAG;KACH,MAAM,CAAC,GAAG,KAAK,MAAM,MAAM;IAC7B;SACK,IAAI,CAAC,KAAK,MACf,WAAW,YAAY,EAAE,OAAO,CAAC,MAAM,EAAE,MAAM,OAAO,CAAC,EAAE;GAE7D;EACF;EAEA,OAAO,aAAa;EACpB,IAAI,iBAAiB,SAAS,GAC5B,OAAO,WAAW;OAElB,OAAO,OAAO;EAEhB,OAAO,uBAAuB;CAChC;CAEA,IAAI,OAAO,SAAS,WAAW,OAAO,OACpC,OAAO,QAAQ,sCACb,OAAO,OACP,OAAO,MAAM,YAAY,CAAC,CAC5B;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"schema-converter.js","names":[],"sources":["../../../src/utils/schema-converter.ts"],"sourcesContent":["import type { NullWideningMap } from '@tanstack/ai-utils'\n\ninterface MistralStructuredOutputCompatibility {\n schema: Record<string, any>\n nullWideningMap: NullWideningMap | undefined\n strict: boolean\n}\n\n/**\n * Convert a schema for Mistral strict mode and record how to invert it.\n *\n * Outcomes:\n * - `strict: true` — rewritten schema (`required` closed, optionals null-widened).\n * `nullWideningMap` marks synthesized optional nulls only; already-nullable\n * fields and enum/const repairs on required nodes are unmarked.\n * - `strict: false` — original schema, no map. Used when `oneOf`/`allOf`/`not`/\n * `$ref`/`$defs` appear, or an `anyOf` branch would need a branch-dependent map.\n */\nexport function makeMistralStructuredOutputCompatibleWithMap(\n schema: Record<string, any>,\n originalRequired: Array<string> = [],\n): MistralStructuredOutputCompatibility {\n if (containsUnsupportedStrictKeyword(schema)) {\n return { schema, nullWideningMap: undefined, strict: false }\n }\n\n const converted = coerceMistralStrictSchema(schema, originalRequired)\n if (converted.hasUntrackableAnyOfWidening) {\n return { schema, nullWideningMap: undefined, strict: false }\n }\n\n return {\n schema: converted.schema,\n nullWideningMap: converted.nullWideningMap,\n strict: true,\n }\n}\n\ninterface CoercedMistralStrictSchema {\n schema: Record<string, any>\n nullWideningMap: NullWideningMap | undefined\n hasUntrackableAnyOfWidening: boolean\n}\n\nconst UNSUPPORTED_STRICT_KEYWORDS: ReadonlyArray<string> = [\n 'oneOf',\n 'allOf',\n 'not',\n '$ref',\n '$defs',\n 'definitions',\n]\n\n/**\n * Tree-wide key scan for `oneOf`/`allOf`/`not`/`$ref`/`$defs`/`definitions`.\n * Conservative: a property literally named e.g. `oneOf` also trips fallback.\n * `anyOf` is handled separately in the coerce walk.\n */\nfunction containsUnsupportedStrictKeyword(node: unknown): boolean {\n if (Array.isArray(node)) return node.some(containsUnsupportedStrictKeyword)\n if (!isSchemaObject(node)) return false\n\n return Object.entries(node).some(\n ([key, value]) =>\n UNSUPPORTED_STRICT_KEYWORDS.includes(key) ||\n containsUnsupportedStrictKeyword(value),\n )\n}\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\nfunction coerceArrayItems(items: unknown): {\n schema: unknown\n itemMap: NullWideningMap | Array<NullWideningMap> | undefined\n hasUntrackableAnyOfWidening: boolean\n} {\n if (Array.isArray(items)) {\n const converted = items.map((item) =>\n isSchemaObject(item)\n ? coerceMistralStrictSchema(item, item.required || [])\n : {\n schema: item,\n nullWideningMap: undefined,\n hasUntrackableAnyOfWidening: false,\n },\n )\n const itemMaps = converted.map((item) => item.nullWideningMap)\n return {\n schema: converted.map((item) => item.schema),\n itemMap: itemMaps.some(Boolean)\n ? itemMaps.map((map) => map ?? {})\n : undefined,\n hasUntrackableAnyOfWidening: converted.some(\n (item) => item.hasUntrackableAnyOfWidening,\n ),\n }\n }\n\n if (isSchemaObject(items)) {\n const converted = coerceMistralStrictSchema(items, items.required || [])\n return {\n schema: converted.schema,\n itemMap: converted.nullWideningMap,\n hasUntrackableAnyOfWidening: converted.hasUntrackableAnyOfWidening,\n }\n }\n\n return {\n schema: items,\n itemMap: undefined,\n hasUntrackableAnyOfWidening: false,\n }\n}\n\nfunction schemaTypeIncludes(\n schema: Record<string, any>,\n typeName: string,\n): boolean {\n return (\n schema.type === typeName ||\n (Array.isArray(schema.type) && schema.type.includes(typeName))\n )\n}\n\nfunction admitNullInEnumOrConst(\n prop: Record<string, any>,\n): Record<string, any> {\n if ('const' in prop && prop.const !== null) {\n const { const: constValue, ...withoutConst } = prop\n return { ...withoutConst, enum: [constValue, null] }\n }\n if (Array.isArray(prop.enum) && !prop.enum.includes(null)) {\n return { ...prop, enum: [...prop.enum, null] }\n }\n return prop\n}\n\n/**\n * True when `type`/`enum`/`const`/`anyOf` already admit null. `oneOf`/`allOf`/\n * `not` are not inspected — callers must reject those first.\n */\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 coerceMistralStrictSchema(\n schema: Record<string, any>,\n originalRequired: Array<string>,\n): CoercedMistralStrictSchema {\n const result = { ...schema }\n const nullWideningMap: NullWideningMap = {}\n let hasUntrackableAnyOfWidening = false\n\n if (schemaTypeIncludes(result, 'object')) {\n if (!result.properties) {\n result.properties = {}\n }\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 = !originalRequired.includes(propName)\n let childMap: NullWideningMap | undefined\n let widenedHere = false\n\n if (\n isSchemaObject(prop) &&\n schemaTypeIncludes(prop, 'object') &&\n prop.properties\n ) {\n const converted = coerceMistralStrictSchema(prop, prop.required || [])\n prop = converted.schema\n childMap = converted.nullWideningMap\n hasUntrackableAnyOfWidening ||= converted.hasUntrackableAnyOfWidening\n } else if (\n isSchemaObject(prop) &&\n schemaTypeIncludes(prop, 'array') &&\n prop.items != null\n ) {\n const convertedItems = coerceArrayItems(prop.items)\n prop = {\n ...prop,\n items: convertedItems.schema,\n }\n if (convertedItems.itemMap) {\n childMap = { items: convertedItems.itemMap }\n }\n hasUntrackableAnyOfWidening ||=\n convertedItems.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && Array.isArray(prop.anyOf)) {\n const converted = coerceMistralStrictSchema(prop, prop.required || [])\n prop = converted.schema\n childMap = converted.nullWideningMap\n hasUntrackableAnyOfWidening ||= converted.hasUntrackableAnyOfWidening\n }\n\n if (!acceptsNull(prop)) {\n if (wasOptional) {\n if (isSchemaObject(prop)) {\n prop = admitNullInEnumOrConst(prop)\n }\n\n if (isSchemaObject(prop) && prop.type && !Array.isArray(prop.type)) {\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 } else if (!isSchemaObject(prop) || !prop.type) {\n prop = { anyOf: [prop, { type: 'null' }] }\n }\n\n widenedHere = true\n } else if (isSchemaObject(prop) && schemaTypeIncludes(prop, 'null')) {\n prop = admitNullInEnumOrConst(prop)\n }\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 if (allPropertyNames.length > 0) {\n result.required = allPropertyNames\n } else {\n delete result.required\n }\n result.additionalProperties = false\n if (Object.keys(propertyMaps).length > 0) {\n nullWideningMap.properties = propertyMaps\n }\n }\n\n if (schemaTypeIncludes(result, 'array') && result.items != null) {\n const convertedItems = coerceArrayItems(result.items)\n result.items = convertedItems.schema\n if (convertedItems.itemMap) {\n nullWideningMap.items = convertedItems.itemMap\n }\n hasUntrackableAnyOfWidening ||= convertedItems.hasUntrackableAnyOfWidening\n }\n\n if (Array.isArray(result.anyOf)) {\n const variants = result.anyOf.map((variant: unknown) => {\n if (!isSchemaObject(variant)) {\n return {\n schema: variant,\n nullWideningMap: undefined,\n hasUntrackableAnyOfWidening: false,\n }\n }\n return coerceMistralStrictSchema(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 return {\n schema: result,\n nullWideningMap: pruneMap(nullWideningMap),\n hasUntrackableAnyOfWidening,\n }\n}\n"],"mappings":";;;;;;;;;;;AAkBA,SAAgB,6CACd,QACA,mBAAkC,CAAC,GACG;CACtC,IAAI,iCAAiC,MAAM,GACzC,OAAO;EAAE;EAAQ,iBAAiB,KAAA;EAAW,QAAQ;CAAM;CAG7D,MAAM,YAAY,0BAA0B,QAAQ,gBAAgB;CACpE,IAAI,UAAU,6BACZ,OAAO;EAAE;EAAQ,iBAAiB,KAAA;EAAW,QAAQ;CAAM;CAG7D,OAAO;EACL,QAAQ,UAAU;EAClB,iBAAiB,UAAU;EAC3B,QAAQ;CACV;AACF;AAQA,IAAM,8BAAqD;CACzD;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,SAAS,iCAAiC,MAAwB;CAChE,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,KAAK,KAAK,gCA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AO,uBAAuB,IAAI;GAEtC;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,IAAI,iBAAiB,SAAS,GAC5B,OAAO,WAAW;OAElB,OAAO,OAAO;EAEhB,OAAO,uBAAuB;EAC9B,IAAI,OAAO,KAAK,YAAY,CAAC,CAAC,SAAS,GACrC,gBAAgB,aAAa;CAEjC;CAEA,IAAI,mBAAmB,QAAQ,OAAO,KAAK,OAAO,SAAS,MAAM;EAC/D,MAAM,iBAAiB,iBAAiB,OAAO,KAAK;EACpD,OAAO,QAAQ,eAAe;EAC9B,IAAI,eAAe,SACjB,gBAAgB,QAAQ,eAAe;EAEzC,gCAAgC,eAAe;CACjD;CAEA,IAAI,MAAM,QAAQ,OAAO,KAAK,GAAG;EAC/B,MAAM,WAAW,OAAO,MAAM,KAAK,YAAqB;GACtD,IAAI,CAAC,eAAe,OAAO,GACzB,OAAO;IACL,QAAQ;IACR,iBAAiB,KAAA;IACjB,6BAA6B;GAC/B;GAEF,OAAO,0BAA0B,SAAS,QAAQ,YAAY,CAAC,CAAC;EAClE,CAAC;EACD,OAAO,QAAQ,SAAS,KAAK,YAAY,QAAQ,MAAM;EACvD,gCAAgC,SAAS,MACtC,YACC,QAAQ,oBAAoB,KAAA,KAC5B,QAAQ,2BACZ;CACF;CAEA,OAAO;EACL,QAAQ;EACR,iBAAiB,SAAS,eAAe;EACzC;CACF;AACF"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import { Tool } from '@tanstack/ai';
2
+ export type ToolInputNormalizer = (toolName: string, input: unknown) => unknown;
3
+ /**
4
+ * Per-request inverse of Mistral optional-null widening. Recomputes maps from
5
+ * each tool's input schema; duplicate names and non-strict schemas are left
6
+ * untouched so we never guess.
7
+ */
8
+ export declare function createToolInputNormalizer(tools: Array<Tool> | undefined): ToolInputNormalizer;
@@ -0,0 +1,34 @@
1
+ import { makeMistralStructuredOutputCompatibleWithMap } from "./schema-converter.js";
2
+ import { undoNullWidening } from "@tanstack/ai-utils";
3
+ //#region src/utils/tool-input-normalizer.ts
4
+ /**
5
+ * Per-request inverse of Mistral optional-null widening. Recomputes maps from
6
+ * each tool's input schema; duplicate names and non-strict schemas are left
7
+ * untouched so we never guess.
8
+ */
9
+ function createToolInputNormalizer(tools) {
10
+ const maps = /* @__PURE__ */ new Map();
11
+ const seenNames = /* @__PURE__ */ new Set();
12
+ const ambiguousNames = /* @__PURE__ */ new Set();
13
+ for (const tool of tools ?? []) {
14
+ if (ambiguousNames.has(tool.name)) continue;
15
+ if (seenNames.has(tool.name)) {
16
+ maps.delete(tool.name);
17
+ ambiguousNames.add(tool.name);
18
+ continue;
19
+ }
20
+ seenNames.add(tool.name);
21
+ const inputSchema = tool.inputSchema ?? {
22
+ type: "object",
23
+ properties: {},
24
+ required: []
25
+ };
26
+ const { nullWideningMap } = makeMistralStructuredOutputCompatibleWithMap(inputSchema, inputSchema.required || []);
27
+ if (nullWideningMap) maps.set(tool.name, nullWideningMap);
28
+ }
29
+ return (toolName, input) => undoNullWidening(input, maps.get(toolName));
30
+ }
31
+ //#endregion
32
+ export { createToolInputNormalizer };
33
+
34
+ //# sourceMappingURL=tool-input-normalizer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-input-normalizer.js","names":[],"sources":["../../../src/utils/tool-input-normalizer.ts"],"sourcesContent":["import { undoNullWidening } from '@tanstack/ai-utils'\nimport { makeMistralStructuredOutputCompatibleWithMap } from './schema-converter'\nimport type { JSONSchema, Tool } from '@tanstack/ai'\nimport type { NullWideningMap } from '@tanstack/ai-utils'\n\nexport type ToolInputNormalizer = (toolName: string, input: unknown) => unknown\n\n/**\n * Per-request inverse of Mistral optional-null widening. Recomputes maps from\n * each tool's input schema; duplicate names and non-strict schemas are left\n * untouched so we never guess.\n */\nexport function createToolInputNormalizer(\n tools: Array<Tool> | undefined,\n): ToolInputNormalizer {\n const maps = new Map<string, NullWideningMap>()\n const seenNames = new Set<string>()\n const ambiguousNames = new Set<string>()\n\n for (const tool of tools ?? []) {\n if (ambiguousNames.has(tool.name)) continue\n if (seenNames.has(tool.name)) {\n maps.delete(tool.name)\n ambiguousNames.add(tool.name)\n continue\n }\n seenNames.add(tool.name)\n\n const inputSchema = (tool.inputSchema ?? {\n type: 'object',\n properties: {},\n required: [],\n }) as JSONSchema\n const { nullWideningMap } = makeMistralStructuredOutputCompatibleWithMap(\n inputSchema,\n inputSchema.required || [],\n )\n if (nullWideningMap) maps.set(tool.name, nullWideningMap)\n }\n\n return (toolName, input) => undoNullWidening(input, maps.get(toolName))\n}\n"],"mappings":";;;;;;;;AAYA,SAAgB,0BACd,OACqB;CACrB,MAAM,uBAAO,IAAI,IAA6B;CAC9C,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,iCAAiB,IAAI,IAAY;CAEvC,KAAK,MAAM,QAAQ,SAAS,CAAC,GAAG;EAC9B,IAAI,eAAe,IAAI,KAAK,IAAI,GAAG;EACnC,IAAI,UAAU,IAAI,KAAK,IAAI,GAAG;GAC5B,KAAK,OAAO,KAAK,IAAI;GACrB,eAAe,IAAI,KAAK,IAAI;GAC5B;EACF;EACA,UAAU,IAAI,KAAK,IAAI;EAEvB,MAAM,cAAe,KAAK,eAAe;GACvC,MAAM;GACN,YAAY,CAAC;GACb,UAAU,CAAC;EACb;EACA,MAAM,EAAE,oBAAoB,6CAC1B,aACA,YAAY,YAAY,CAAC,CAC3B;EACA,IAAI,iBAAiB,KAAK,IAAI,KAAK,MAAM,eAAe;CAC1D;CAEA,QAAQ,UAAU,UAAU,iBAAiB,OAAO,KAAK,IAAI,QAAQ,CAAC;AACxE"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,29 @@
1
+ export declare class MistralVertexAuthError extends Error {
2
+ constructor(message: string, options?: ErrorOptions);
3
+ }
4
+ export type VertexAuthClient = {
5
+ getRequestHeaders: (url?: string | URL) => Promise<Headers>;
6
+ };
7
+ /**
8
+ * Public Vertex config for Mistral. `project` and `location` match the
9
+ * Gemini Vertex factories so one auth object works for both.
10
+ *
11
+ * Mistral on Vertex is regional only (`us-central1`, `europe-west4`).
12
+ * There is no global endpoint.
13
+ */
14
+ export type MistralVertexConfig = {
15
+ project?: string;
16
+ location?: string;
17
+ /**
18
+ * Override the chat completions URL. When set, the Vertex
19
+ * `:rawPredict` / `:streamRawPredict` rewrite is skipped. Used by e2e.
20
+ */
21
+ resolveRequestUrl?: (stream: boolean) => string;
22
+ getAccessToken?: () => Promise<string>;
23
+ authClient?: VertexAuthClient;
24
+ defaultHeaders?: Record<string, string>;
25
+ };
26
+ export declare function resolveMistralVertexProject(config: MistralVertexConfig): string | undefined;
27
+ export declare function resolveMistralVertexLocation(config: MistralVertexConfig): string;
28
+ export declare function resolveMistralVertexModelUrl(model: string, config: MistralVertexConfig): string;
29
+ export declare function resolveMistralVertexAccessToken(config: MistralVertexConfig): Promise<string>;
@@ -0,0 +1,62 @@
1
+ //#region src/vertex/auth.ts
2
+ var MistralVertexAuthError = class extends Error {
3
+ constructor(message, options) {
4
+ super(message, options);
5
+ this.name = "MistralVertexAuthError";
6
+ }
7
+ };
8
+ var MISTRAL_VERTEX_LOCATIONS = ["us-central1", "europe-west4"];
9
+ function isMistralVertexLocation(location) {
10
+ return MISTRAL_VERTEX_LOCATIONS.includes(location);
11
+ }
12
+ function isMissingGoogleAuthLibrary(error) {
13
+ if (!(error instanceof Error) || !("code" in error)) return false;
14
+ const code = error.code;
15
+ if (code !== "ERR_MODULE_NOT_FOUND" && code !== "MODULE_NOT_FOUND") return false;
16
+ return error.message.includes("google-auth-library");
17
+ }
18
+ function nonEmpty(value) {
19
+ if (value === void 0 || value.length === 0) return;
20
+ return value;
21
+ }
22
+ function readEnv(name) {
23
+ if (typeof process === "undefined" || process.env === void 0) return;
24
+ return nonEmpty(process.env[name]);
25
+ }
26
+ function resolveMistralVertexProject(config) {
27
+ return nonEmpty(config.project) ?? readEnv("GOOGLE_CLOUD_PROJECT") ?? readEnv("GOOGLE_VERTEX_PROJECT");
28
+ }
29
+ function resolveMistralVertexLocation(config) {
30
+ const location = nonEmpty(config.location) ?? readEnv("GOOGLE_CLOUD_LOCATION") ?? readEnv("GOOGLE_VERTEX_LOCATION");
31
+ if (location === void 0) throw new MistralVertexAuthError("Mistral Vertex needs a location. Pass location on the factory, or set GOOGLE_CLOUD_LOCATION or GOOGLE_VERTEX_LOCATION. Use us-central1 or europe-west4.");
32
+ if (!isMistralVertexLocation(location)) throw new MistralVertexAuthError("Mistral Vertex location must be us-central1 or europe-west4. There is no global endpoint.");
33
+ return location;
34
+ }
35
+ function resolveMistralVertexModelUrl(model, config) {
36
+ const project = resolveMistralVertexProject(config);
37
+ if (project === void 0) throw new MistralVertexAuthError("Mistral Vertex needs a project. Pass project on the factory, or set GOOGLE_CLOUD_PROJECT or GOOGLE_VERTEX_PROJECT.");
38
+ const location = resolveMistralVertexLocation(config);
39
+ return `https://${location}-aiplatform.googleapis.com/v1/projects/${project}/locations/${location}/publishers/mistralai/models/${model}`;
40
+ }
41
+ async function resolveMistralVertexAccessToken(config) {
42
+ if (config.getAccessToken !== void 0) return config.getAccessToken();
43
+ if (config.authClient !== void 0) {
44
+ const authorization = (await config.authClient.getRequestHeaders()).get("Authorization");
45
+ if (authorization === null || !authorization.startsWith("Bearer ")) throw new MistralVertexAuthError("Mistral Vertex authClient.getRequestHeaders() must return an Authorization Bearer token.");
46
+ return authorization.slice(7);
47
+ }
48
+ try {
49
+ const { GoogleAuth } = await import("google-auth-library");
50
+ const token = await (await new GoogleAuth({ scopes: ["https://www.googleapis.com/auth/cloud-platform"] }).getClient()).getAccessToken();
51
+ if (token.token === null || token.token === void 0) throw new MistralVertexAuthError("Mistral Vertex could not load a Google access token from Application Default Credentials.");
52
+ return token.token;
53
+ } catch (error) {
54
+ if (error instanceof MistralVertexAuthError) throw error;
55
+ if (isMissingGoogleAuthLibrary(error)) throw new MistralVertexAuthError("Mistral Vertex needs google-auth-library, or pass authClient or getAccessToken. Install google-auth-library next to @tanstack/ai-mistral.");
56
+ throw new MistralVertexAuthError("Mistral Vertex could not load a Google access token from Application Default Credentials.", { cause: error });
57
+ }
58
+ }
59
+ //#endregion
60
+ export { MistralVertexAuthError, resolveMistralVertexAccessToken, resolveMistralVertexLocation, resolveMistralVertexModelUrl, resolveMistralVertexProject };
61
+
62
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","names":[],"sources":["../../../src/vertex/auth.ts"],"sourcesContent":["export class MistralVertexAuthError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options)\n this.name = 'MistralVertexAuthError'\n }\n}\n\nconst MISTRAL_VERTEX_LOCATIONS = ['us-central1', 'europe-west4'] as const\n\nfunction isMistralVertexLocation(\n location: string,\n): location is (typeof MISTRAL_VERTEX_LOCATIONS)[number] {\n return (MISTRAL_VERTEX_LOCATIONS as ReadonlyArray<string>).includes(location)\n}\n\nfunction isMissingGoogleAuthLibrary(error: unknown): boolean {\n if (!(error instanceof Error) || !('code' in error)) {\n return false\n }\n const code = error.code\n if (code !== 'ERR_MODULE_NOT_FOUND' && code !== 'MODULE_NOT_FOUND') {\n return false\n }\n return error.message.includes('google-auth-library')\n}\n\nexport type VertexAuthClient = {\n getRequestHeaders: (url?: string | URL) => Promise<Headers>\n}\n\n/**\n * Public Vertex config for Mistral. `project` and `location` match the\n * Gemini Vertex factories so one auth object works for both.\n *\n * Mistral on Vertex is regional only (`us-central1`, `europe-west4`).\n * There is no global endpoint.\n */\nexport type MistralVertexConfig = {\n project?: string\n location?: string\n /**\n * Override the chat completions URL. When set, the Vertex\n * `:rawPredict` / `:streamRawPredict` rewrite is skipped. Used by e2e.\n */\n resolveRequestUrl?: (stream: boolean) => string\n getAccessToken?: () => Promise<string>\n authClient?: VertexAuthClient\n defaultHeaders?: Record<string, string>\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n if (value === undefined || value.length === 0) {\n return undefined\n }\n return value\n}\n\nfunction readEnv(name: string): string | undefined {\n if (typeof process === 'undefined' || process.env === undefined) {\n return undefined\n }\n return nonEmpty(process.env[name])\n}\n\nexport function resolveMistralVertexProject(\n config: MistralVertexConfig,\n): string | undefined {\n return (\n nonEmpty(config.project) ??\n readEnv('GOOGLE_CLOUD_PROJECT') ??\n readEnv('GOOGLE_VERTEX_PROJECT')\n )\n}\n\nexport function resolveMistralVertexLocation(\n config: MistralVertexConfig,\n): string {\n const location =\n nonEmpty(config.location) ??\n readEnv('GOOGLE_CLOUD_LOCATION') ??\n readEnv('GOOGLE_VERTEX_LOCATION')\n if (location === undefined) {\n throw new MistralVertexAuthError(\n 'Mistral Vertex needs a location. Pass location on the factory, or set GOOGLE_CLOUD_LOCATION or GOOGLE_VERTEX_LOCATION. Use us-central1 or europe-west4.',\n )\n }\n if (!isMistralVertexLocation(location)) {\n throw new MistralVertexAuthError(\n 'Mistral Vertex location must be us-central1 or europe-west4. There is no global endpoint.',\n )\n }\n return location\n}\n\nexport function resolveMistralVertexModelUrl(\n model: string,\n config: MistralVertexConfig,\n): string {\n const project = resolveMistralVertexProject(config)\n if (project === undefined) {\n throw new MistralVertexAuthError(\n 'Mistral Vertex needs a project. Pass project on the factory, or set GOOGLE_CLOUD_PROJECT or GOOGLE_VERTEX_PROJECT.',\n )\n }\n const location = resolveMistralVertexLocation(config)\n return `https://${location}-aiplatform.googleapis.com/v1/projects/${project}/locations/${location}/publishers/mistralai/models/${model}`\n}\n\nexport async function resolveMistralVertexAccessToken(\n config: MistralVertexConfig,\n): Promise<string> {\n if (config.getAccessToken !== undefined) {\n return config.getAccessToken()\n }\n\n if (config.authClient !== undefined) {\n const headers = await config.authClient.getRequestHeaders()\n const authorization = headers.get('Authorization')\n if (authorization === null || !authorization.startsWith('Bearer ')) {\n throw new MistralVertexAuthError(\n 'Mistral Vertex authClient.getRequestHeaders() must return an Authorization Bearer token.',\n )\n }\n return authorization.slice('Bearer '.length)\n }\n\n try {\n const { GoogleAuth } = await import('google-auth-library')\n const auth = new GoogleAuth({\n scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n })\n const client = await auth.getClient()\n const token = await client.getAccessToken()\n if (token.token === null || token.token === undefined) {\n throw new MistralVertexAuthError(\n 'Mistral Vertex could not load a Google access token from Application Default Credentials.',\n )\n }\n return token.token\n } catch (error) {\n if (error instanceof MistralVertexAuthError) {\n throw error\n }\n if (isMissingGoogleAuthLibrary(error)) {\n throw new MistralVertexAuthError(\n 'Mistral Vertex needs google-auth-library, or pass authClient or getAccessToken. Install google-auth-library next to @tanstack/ai-mistral.',\n )\n }\n throw new MistralVertexAuthError(\n 'Mistral Vertex could not load a Google access token from Application Default Credentials.',\n { cause: error },\n )\n }\n}\n"],"mappings":";AAAA,IAAa,yBAAb,cAA4C,MAAM;CAChD,YAAY,SAAiB,SAAwB;EACnD,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;AAEA,IAAM,2BAA2B,CAAC,eAAe,cAAc;AAE/D,SAAS,wBACP,UACuD;CACvD,OAAQ,yBAAmD,SAAS,QAAQ;AAC9E;AAEA,SAAS,2BAA2B,OAAyB;CAC3D,IAAI,EAAE,iBAAiB,UAAU,EAAE,UAAU,QAC3C,OAAO;CAET,MAAM,OAAO,MAAM;CACnB,IAAI,SAAS,0BAA0B,SAAS,oBAC9C,OAAO;CAET,OAAO,MAAM,QAAQ,SAAS,qBAAqB;AACrD;AA0BA,SAAS,SAAS,OAA+C;CAC/D,IAAI,UAAU,KAAA,KAAa,MAAM,WAAW,GAC1C;CAEF,OAAO;AACT;AAEA,SAAS,QAAQ,MAAkC;CACjD,IAAI,OAAO,YAAY,eAAe,QAAQ,QAAQ,KAAA,GACpD;CAEF,OAAO,SAAS,QAAQ,IAAI,KAAK;AACnC;AAEA,SAAgB,4BACd,QACoB;CACpB,OACE,SAAS,OAAO,OAAO,KACvB,QAA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