8
const MAX_NODE_DEPTH = 512;
9
const CYCLE_BREAK_SENTINEL = { type: 'object', additionalProperties: true } as const;
10
11
+/** Keywords whose value is a single subschema. */
12
+const SCHEMA_KEYWORDS = new Set([
13
+ 'additionalItems',
14
+ 'additionalProperties',
15
+ 'contains',
16
+ 'contentSchema',
17
+ 'else',
18
+ 'if',
19
+ 'not',
20
+ 'propertyNames',
21
+ 'then',
22
+ 'unevaluatedItems',
23
+ 'unevaluatedProperties',
24
+]);
25
+/** Keywords whose value is an array of subschemas. */
26
+const SCHEMA_ARRAY_KEYWORDS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
27
+/** Keywords whose value is a map from name to subschema. */
28
+const SCHEMA_MAP_KEYWORDS = new Set([
29
+ '$defs',
30
+ 'definitions',
31
+ 'dependentSchemas',
32
+ 'patternProperties',
33
+ 'properties',
34
+]);
35
+/** Keywords whose values are instance data, never subschemas. */
36
+const INSTANCE_VALUE_KEYWORDS = new Set(['const', 'default', 'enum', 'examples']);
37
+
38
/**
39
* In-band hint attached to the cycle-break sentinel when lenient mode
40
* substitutes it for a dangling `$ref`. Makes the degradation visible to
299
export function ensureObjectTypeOnProperties<T = unknown>(schema: T): T {
300
type WalkMode = 'schema' | 'schema-array' | 'schema-map' | 'dependencies-map' | 'value';
301
275
- const schemaKeywords = new Set([
276
- 'additionalItems',
277
- 'additionalProperties',
278
- 'contains',
279
- 'contentSchema',
280
- 'else',
281
- 'if',
282
- 'not',
283
- 'propertyNames',
284
- 'then',
285
- 'unevaluatedItems',
286
- 'unevaluatedProperties',
287
- ]);
288
- const schemaArrayKeywords = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
289
- const schemaMapKeywords = new Set([
290
- '$defs',
291
- 'definitions',
292
- 'dependentSchemas',
293
- 'patternProperties',
294
- 'properties',
295
- ]);
296
-
302
function walk(value: unknown, mode: WalkMode, depth = 0): unknown {
303
if (depth > MAX_NODE_DEPTH) {
304
throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
319
} else if (mode === 'dependencies-map') {
320
childMode = Array.isArray(child) ? 'value' : 'schema';
321
} else if (mode === 'schema') {
317
- if (schemaMapKeywords.has(key)) {
322
+ if (SCHEMA_MAP_KEYWORDS.has(key)) {
323
childMode = 'schema-map';
319
- } else if (schemaArrayKeywords.has(key) || (key === 'items' && Array.isArray(child))) {
324
+ } else if (SCHEMA_ARRAY_KEYWORDS.has(key) || (key === 'items' && Array.isArray(child))) {
325
childMode = 'schema-array';
321
- } else if (schemaKeywords.has(key) || key === 'items') {
326
+ } else if (SCHEMA_KEYWORDS.has(key) || key === 'items') {
327
childMode = 'schema';
328
} else if (key === 'dependencies') {
329
childMode = 'dependencies-map';
361
export function deduplicateJsonSchemaRequiredArrays<T = unknown>(schema: T): T {
362
const seenSchemaValues = new WeakMap<object, unknown>();
363
const seenInstanceValues = new WeakMap<object, unknown>();
359
- const instanceValueKeywords = new Set(['const', 'default', 'enum', 'examples']);
364
365
function walk(value: unknown, isSchema: boolean, depth = 0): unknown {
366
if (depth > MAX_NODE_DEPTH) {
395
value:
396
isSchema && key === 'required' && Array.isArray(child)
397
? [...new Set(walk(child, false, depth + 1) as unknown[])]
394
- : walk(child, isSchema && !instanceValueKeywords.has(key), depth + 1),
398
+ : walk(child, isSchema && !INSTANCE_VALUE_KEYWORDS.has(key), depth + 1),
399
writable: true,
400
});
401
}
502
}
503
504
/**
501
- * Reason recorded when strict normalization changes a schema node.
505
+ * Reason recorded when strict normalization rewrites a schema node. Every
506
+ * rewrite is lossless: the model can still express the same values.
507
*
503
- * - `nullable-type-converted` — a `type` array containing `'null'` became an
504
- * `anyOf` with an explicit `{ type: 'null' }` branch.
505
- * - `multi-type-converted` — a `type` array without `'null'` (e.g.
506
- * `['string', 'number']`) became equivalent `anyOf` branches.
507
- * - `annotation-keyword-stripped` — an annotation-only keyword (`examples`,
508
- * `default`) that strict mode rejects was removed.
509
- * - `non-required-property-dropped` — a property not listed in `required`
510
- * was removed from its parent object.
508
+ * - `optional-property-nullable` — a property missing from `required` was
509
+ * added to it and widened to accept `null`, the emulation of optional
510
+ * fields that OpenAI structured outputs document.
511
+ * - `unsupported-keyword-stripped` — an annotation keyword the API rejects
512
+ * (`default`, `examples`) was removed.
513
+ * - `one-of-converted` — `oneOf` (unsupported) became `anyOf`.
514
*/
515
export type StrictSchemaChangeReason =
513
- | 'nullable-type-converted'
514
- | 'multi-type-converted'
515
- | 'annotation-keyword-stripped'
516
- | 'non-required-property-dropped';
516
+ 'optional-property-nullable' | 'unsupported-keyword-stripped' | 'one-of-converted';
517
518
-/** A single structural change applied by {@link toStrictJsonSchema}. */
518
+/** A single lossless rewrite applied by {@link toStrictJsonSchema}. */
519
export interface StrictSchemaChange {
520
/** Path to the changed node relative to the root, e.g. `properties.cfg.items`. */
521
path: string;
524
detail?: string;
525
}
526
527
-/** Result of {@link toStrictJsonSchema}: the normalized schema plus a change log. */
528
-export interface StrictJsonSchemaResult<T = unknown> {
529
- schema: T;
527
+/**
528
+ * A schema construct strict structured outputs cannot express. Rewriting it
529
+ * would change what the tool accepts, so it is reported instead; providers
530
+ * send such a tool without strict mode.
531
+ */
532
+export interface StrictSchemaIncompatibility {
533
+ /** Path to the offending node relative to the root. */
534
+ path: string;
535
+ /** The keyword (or `$ref`) that has no strict-mode equivalent. */
536
+ keyword: string;
537
+ detail: string;
538
+}
539
+
540
+/** Result of {@link toStrictJsonSchema}. */
541
+export interface StrictJsonSchemaResult {
542
+ /**
543
+ * The strict schema. Only usable when `unsupported` is empty; otherwise it
544
+ * is best-effort and the original schema should be sent without strict mode.
545
+ */
546
+ schema: Record<string, unknown>;
547
+ /**
548
+ * The dereferenced input the rewrite was computed from. Optionality is
549
+ * decided against this schema, so it is what `omitNullToolArguments` needs.
550
+ */
551
+ source: Record<string, unknown>;
552
+ /** Lossless rewrites, capped at 50 entries; see `totalChanges`. */
553
changes: StrictSchemaChange[];
554
+ totalChanges: number;
555
+ /** Constructs strict mode cannot express. Non-empty means "do not use `schema`". */
556
+ unsupported: StrictSchemaIncompatibility[];
557
}
558
559
const MAX_STRICT_CHANGES = 50;
561
/** Annotation-only keywords OpenAI structured outputs rejects; safe to strip. */
562
const STRICT_STRIP_KEYWORDS = new Set(['examples', 'default']);
563
538
-/** Keywords whose values are literal data, not schemas — never recursed as schemas. */
539
-const STRICT_INSTANCE_VALUE_KEYWORDS = new Set(['const', 'enum']);
540
-
541
-const STRICT_SCHEMA_SINGLE_KEYS = new Set([
542
- 'additionalItems',
543
- 'additionalProperties',
544
- 'contains',
545
- 'contentSchema',
546
- 'else',
547
- 'if',
548
- 'not',
549
- 'propertyNames',
550
- 'then',
551
- 'unevaluatedItems',
552
- 'unevaluatedProperties',
553
-]);
554
-const STRICT_SCHEMA_ARRAY_KEYS = new Set(['allOf', 'anyOf', 'oneOf', 'prefixItems']);
555
-const STRICT_SCHEMA_MAP_KEYS = new Set([
556
- '$defs',
557
- 'definitions',
558
- 'dependentSchemas',
559
- 'patternProperties',
560
- 'properties',
561
-]);
564
+/** Keywords OpenAI structured outputs reject and that have no lossless rewrite. */
565
+const STRICT_UNSUPPORTED_KEYWORDS = ['allOf', 'prefixItems'];
566
567
type StrictWalkMode = 'schema' | 'schema-array' | 'schema-map' | 'value';
568
569
+const joinPath = (parent: string, key: string): string => (parent ? `${parent}.${key}` : key);
570
+
571
/**
566
- * Normalizes a JSON Schema for OpenAI structured outputs (`strict: true`),
567
- * which requires every object node to declare all of its properties in
568
- * `required`, set `additionalProperties: false`, use only supported keywords,
569
- * and express nullable / multi-typed fields via `anyOf`.
570
- *
571
- * The top-level `removeNonRequiredProperties` only handled the root object,
572
- * so nested objects, composition branches and array items passed through
573
- * untouched and the API rejected the whole request. This function applies the
574
- * same contract at every depth:
572
+ * Widens a property schema so that `null` is an accepted value, without
573
+ * placing `type` beside `anyOf` (the API rejects that combination).
574
+ */
575
+function widenToNullable(node: Record<string, unknown>): Record<string, unknown> {
576
+ if (Array.isArray(node.anyOf)) {
577
+ const alreadyNullable = node.anyOf.some(
578
+ branch => isPlainObject(branch) && branch.type === 'null'
579
+ );
580
+ return alreadyNullable ? node : { ...node, anyOf: [...node.anyOf, { type: 'null' }] };
581
+ }
582
+ if (typeof node.type === 'string') {
583
+ return node.type === 'null' ? node : { ...node, type: [node.type, 'null'] };
584
+ }
585
+ if (Array.isArray(node.type)) {
586
+ return node.type.includes('null') ? node : { ...node, type: [...node.type, 'null'] };
587
+ }
588
+ // No `type` at all: an empty schema already accepts null; anything else
589
+ // (enum-only, const, composition) is wrapped so the annotation stays outside.
590
+ const { description, title, ...rest } = node;
591
+ if (Object.keys(rest).length === 0) return node;
592
+ return {
593
+ ...(description !== undefined ? { description } : {}),
594
+ ...(title !== undefined ? { title } : {}),
595
+ anyOf: [rest, { type: 'null' }],
596
+ };
597
+}
598
+
599
+/** Whether a (dereferenced) schema node accepts `null` as an instance. */
600
+function schemaAcceptsNull(node: unknown): boolean {
601
+ if (!isPlainObject(node)) return true;
602
+ if (typeof node.type === 'string') return node.type === 'null';
603
+ if (Array.isArray(node.type)) return node.type.includes('null');
604
+ if (Array.isArray(node.enum)) return node.enum.includes(null);
605
+ if ('const' in node) return node.const === null;
606
+ for (const keyword of ['anyOf', 'oneOf']) {
607
+ const branches = node[keyword];
608
+ if (Array.isArray(branches)) return branches.some(schemaAcceptsNull);
609
+ }
610
+ return true;
611
+}
612
+
613
+/**
614
+ * Normalizes a tool parameter schema for OpenAI structured outputs
615
+ * (`strict: true`) at every depth, following the contract OpenAI documents:
616
*
576
- * - Objects with a non-empty `required` keep only those properties
577
- * (matching the established top-level behavior); objects without one keep
578
- * every property but are forced to require them all — dropping everything
579
- * would gut the tool, and leaving optional properties would be rejected.
580
- * - `type` arrays become `anyOf` branches with an explicit `{type:'null'}`
581
- * variant where applicable.
582
- * - Annotation keywords (`examples`, `default`) are stripped.
583
- * - Composition keywords (`anyOf`/`oneOf`/`allOf`), array `items`/
584
- * `prefixItems` and property maps are normalized recursively.
617
+ * - every object lists all of its properties in `required` and sets
618
+ * `additionalProperties: false`;
619
+ * - properties that were optional stay available and are widened to accept
620
+ * `null` (`type: ['string', 'null']`, or an extra `anyOf` branch) — the
621
+ * documented way to emulate optional fields. Nothing is dropped, so the
622
+ * model keeps every parameter it could pass before. A `null` the model
623
+ * sends for such a property means "omitted"; the strict providers drop it
624
+ * before executing the tool (see {@link omitNullToolArguments});
625
+ * - `type` arrays are kept as-is (the API accepts them); `oneOf` becomes
626
+ * `anyOf`; `default` and `examples` are stripped;
627
+ * - constructs strict mode cannot express — objects that accept arbitrary
628
+ * keys (schema-valued or `true` `additionalProperties`, `patternProperties`,
629
+ * property-less free-form objects), `allOf`, `prefixItems`, dangling or
630
+ * cyclic `$ref`s, and a non-object root — are reported in `unsupported`
631
+ * rather than rewritten into something narrower. Callers send such a tool
632
+ * without strict mode.
633
*
586
- * Every structural change is recorded so callers can surface diagnostics
587
- * instead of failing silently. The input is never mutated. Dereference
588
- * `$ref`s first (see {@link dereferenceJsonSchema}) so definitions referenced
589
- * under `$defs` are normalized too, then run
590
- * {@link deduplicateJsonSchemaRequiredArrays} on the result before emitting.
634
+ * The pipeline is `dereferenceJsonSchema` (lenient) → strict rewrite →
635
+ * `deduplicateJsonSchemaRequiredArrays`, the same shape the Anthropic
636
+ * provider uses. The input is never mutated. Every rewrite is recorded in
637
+ * `changes` (capped at 50 entries; `totalChanges` carries the real count).
638
*/
592
-export function toStrictJsonSchema<T = unknown>(schema: T): StrictJsonSchemaResult<T> {
639
+export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
640
const changes: StrictSchemaChange[] = [];
641
+ const unsupported: StrictSchemaIncompatibility[] = [];
642
+ let totalChanges = 0;
643
const recordChange = (change: StrictSchemaChange): void => {
595
- if (changes.length < MAX_STRICT_CHANGES) {
596
- changes.push(change);
597
- }
644
+ totalChanges += 1;
645
+ if (changes.length < MAX_STRICT_CHANGES) changes.push(change);
646
};
647
600
- const joinPath = (parent: string, key: string): string =>
601
- parent ? `${parent}.${key}` : key;
602
-
603
- const splitTypeArray = (node: Record<string, unknown>, path: string): Record<string, unknown> => {
604
- const typeValues = node.type as unknown[];
605
- const branches = typeValues.map(typeValue =>
606
- typeValue === 'null' ? { type: 'null' } : { ...node, type: typeValue }
607
- );
608
- const { type: _droppedType, ...rest } = node;
609
- recordChange({
610
- path,
611
- reason: typeValues.includes('null') ? 'nullable-type-converted' : 'multi-type-converted',
612
- detail: `type [${typeValues.map(String).join(', ')}] converted to anyOf`,
613
- });
614
- return { ...rest, anyOf: branches };
615
- };
648
+ const dereferenced = dereferenceJsonSchema(schema, {
649
+ onUnresolved: 'sentinel',
650
+ onReplace: ref =>
651
+ unsupported.push({
652
+ path: '',
653
+ keyword: '$ref',
654
+ detail: `unresolved $ref "${ref}"`,
655
+ }),
656
+ });
657
658
function walkChildren(
659
node: Record<string, unknown>,
666
let childMode: StrictWalkMode = 'value';
667
if (mode === 'schema-map') {
668
childMode = 'schema';
628
- } else if (mode === 'schema') {
629
- if (!STRICT_INSTANCE_VALUE_KEYWORDS.has(key)) {
630
- if (STRICT_SCHEMA_MAP_KEYS.has(key)) {
631
- childMode = 'schema-map';
632
- } else if (STRICT_SCHEMA_ARRAY_KEYS.has(key) || (key === 'items' && Array.isArray(child))) {
633
- childMode = 'schema-array';
634
- } else if (STRICT_SCHEMA_SINGLE_KEYS.has(key) || key === 'items') {
635
- childMode = 'schema';
636
- }
669
+ } else if (mode === 'schema' && !INSTANCE_VALUE_KEYWORDS.has(key)) {
670
+ if (SCHEMA_MAP_KEYWORDS.has(key)) {
671
+ childMode = 'schema-map';
672
+ } else if (SCHEMA_ARRAY_KEYWORDS.has(key) || (key === 'items' && Array.isArray(child))) {
673
+ childMode = 'schema-array';
674
+ } else if (SCHEMA_KEYWORDS.has(key) || key === 'items') {
675
+ childMode = 'schema';
676
}
677
}
678
679
if (childMode === 'schema-map' && isPlainObject(child)) {
680
const mapClone: Record<string, unknown> = {};
681
for (const [name, subSchema] of Object.entries(child)) {
643
- mapClone[name] = walk(subSchema, 'schema', depth + 1, joinPath(joinPath(path, key), name));
682
+ mapClone[name] = walk(
683
+ subSchema,
684
+ 'schema',
685
+ depth + 1,
686
+ joinPath(joinPath(path, key), name)
687
+ );
688
}
689
clone[key] = mapClone;
690
continue;
702
const itemMode = mode === 'schema-array' ? 'schema' : 'value';
703
return value.map((item, index) => walk(item, itemMode, depth + 1, `${path}[${index}]`));
704
}
661
- if (!isPlainObject(value)) return value;
662
- if (mode === 'value') return value;
663
-
664
- let node: Record<string, unknown> = value;
705
+ if (!isPlainObject(value) || mode === 'value') return value;
706
666
- // Nullable / multi-type arrays must become anyOf before anything else so
667
- // the generated branches flow through the normal recursion below.
668
- if (Array.isArray(node.type)) {
669
- node = splitTypeArray(node, path);
670
- }
671
-
672
- const strippedNode: Record<string, unknown> = {};
673
- for (const [key, child] of Object.entries(node)) {
707
+ const node: Record<string, unknown> = {};
708
+ for (const [key, child] of Object.entries(value)) {
709
if (STRICT_STRIP_KEYWORDS.has(key)) {
710
recordChange({
711
path,
677
- reason: 'annotation-keyword-stripped',
712
+ reason: 'unsupported-keyword-stripped',
713
detail: `keyword "${key}" removed`,
714
});
715
continue;
716
}
682
- strippedNode[key] = child;
717
+ node[key] = child;
718
}
684
- node = strippedNode;
685
-
686
- // Object strictening: complete required, closed additionalProperties.
687
- const hasPropertiesKeyword = isPlainObject(node.properties);
688
- const isObjectNode = hasPropertiesKeyword || node.type === 'object';
689
- if (isObjectNode) {
690
- const properties = hasPropertiesKeyword
691
- ? (node.properties as Record<string, unknown>)
692
- : {};
693
- const declaredRequired = Array.isArray(node.required)
694
- ? node.required.filter((entry): entry is string => typeof entry === 'string')
695
- : [];
696
- const keepOnlyRequired = declaredRequired.length > 0;
697
- const keptKeys = new Set(
698
- keepOnlyRequired ? declaredRequired.filter(key => key in properties) : Object.keys(properties)
699
- );
700
-
701
- const nextProperties: Record<string, unknown> = {};
702
- for (const [name, propertySchema] of Object.entries(properties)) {
703
- if (keptKeys.has(name)) {
704
- nextProperties[name] = walk(
705
- propertySchema,
706
- 'schema',
707
- depth + 1,
708
- joinPath(path, `properties.${name}`)
709
- );
710
- } else {
711
- recordChange({
712
- path: joinPath(path, `properties.${name}`),
713
- reason: 'non-required-property-dropped',
714
- detail: `property "${name}" is not listed in "required"`,
715
- });
716
- }
719
+ if (Array.isArray(node.oneOf) && node.anyOf === undefined) {
720
+ node.anyOf = node.oneOf;
721
+ delete node.oneOf;
722
+ recordChange({ path, reason: 'one-of-converted', detail: 'oneOf became anyOf' });
723
+ }
724
+ for (const keyword of STRICT_UNSUPPORTED_KEYWORDS) {
725
+ if (node[keyword] !== undefined) {
726
+ unsupported.push({
727
+ path,
728
+ keyword,
729
+ detail: `"${keyword}" has no strict-mode equivalent`,
730
+ });
731
}
732
+ }
733
719
- // Recurse into any remaining schema-bearing siblings (e.g. `allOf`,
720
- // `description`) while keeping the four managed keywords authoritative.
721
- const managedKeys = new Set(['type', 'properties', 'required', 'additionalProperties']);
722
- const restNode: Record<string, unknown> = {};
723
- for (const [key, child] of Object.entries(node)) {
724
- if (!managedKeys.has(key)) restNode[key] = child;
725
- }
734
+ const out = walkChildren(node, mode, depth, path);
735
+
736
+ const declaresObjectType =
737
+ out.type === 'object' || (Array.isArray(out.type) && out.type.includes('object'));
738
+ if (!declaresObjectType && !isPlainObject(out.properties)) return out;
739
+
740
+ const properties: Record<string, unknown> = isPlainObject(out.properties)
741
+ ? { ...out.properties }
742
+ : {};
743
+ const declaredRequired = new Set(
744
+ Array.isArray(out.required) ? out.required.filter(entry => typeof entry === 'string') : []
745
+ );
746
+ for (const [name, propertySchema] of Object.entries(properties)) {
747
+ if (declaredRequired.has(name) || !isPlainObject(propertySchema)) continue;
748
+ properties[name] = widenToNullable(propertySchema);
749
+ recordChange({
750
+ path: joinPath(path, `properties.${name}`),
751
+ reason: 'optional-property-nullable',
752
+ detail: `property "${name}" is now required and accepts null`,
753
+ });
754
+ }
755
727
- return {
728
- ...walkChildren(restNode, 'schema', depth, path),
729
- type: 'object',
730
- properties: nextProperties,
731
- required: Object.keys(nextProperties),
732
- additionalProperties: false,
733
- };
756
+ const acceptsDynamicKeys =
757
+ out.additionalProperties === true || isPlainObject(out.additionalProperties);
758
+ if (acceptsDynamicKeys) {
759
+ unsupported.push({
760
+ path,
761
+ keyword: 'additionalProperties',
762
+ detail: 'object accepts arbitrary keys',
763
+ });
764
+ } else if (out.patternProperties !== undefined) {
765
+ unsupported.push({
766
+ path,
767
+ keyword: 'patternProperties',
768
+ detail: 'object accepts pattern-matched keys',
769
+ });
770
+ } else if (Object.keys(properties).length === 0 && out.additionalProperties === undefined) {
771
+ unsupported.push({
772
+ path,
773
+ keyword: 'properties',
774
+ detail: 'free-form object accepts arbitrary keys',
775
+ });
776
}
777
736
- return walkChildren(node, mode, depth, path);
778
+ return {
779
+ ...out,
780
+ ...(out.type === undefined ? { type: 'object' } : {}),
781
+ properties,
782
+ required: Object.keys(properties),
783
+ ...(acceptsDynamicKeys ? {} : { additionalProperties: false }),
784
+ };
785
+ }
786
+
787
+ const normalized = walk(dereferenced, 'schema', 0, '');
788
+ if (!isPlainObject(normalized) || normalized.type !== 'object') {
789
+ unsupported.push({
790
+ path: '',
791
+ keyword: 'type',
792
+ detail: 'root must be a non-nullable object',
793
+ });
794
}
795
739
- const normalized = walk(schema, 'schema', 0, '');
740
- return { schema: normalized as T, changes };
796
+ return {
797
+ schema: deduplicateJsonSchemaRequiredArrays(normalized) as Record<string, unknown>,
798
+ source: dereferenced as Record<string, unknown>,
799
+ changes,
800
+ totalChanges,
801
+ unsupported,
802
+ };
803
+}
804
+
805
+/**
806
+ * Drops `null`-valued arguments that the tool's own schema does not accept,
807
+ * recursively through nested objects and arrays.
808
+ *
809
+ * Strict structured outputs cannot express optional parameters, so
810
+ * {@link toStrictJsonSchema} makes every parameter required and nullable. The
811
+ * model then sends `null` for a parameter it would otherwise have omitted;
812
+ * forwarding that `null` to the tool would fail validation against the tool's
813
+ * real schema, so it is treated as "omitted". A `null` the original schema
814
+ * accepts (a nullable field, an explicit "clear this value") is kept.
815
+ *
816
+ * @param args - Normalized tool arguments.
817
+ * @param schema - The dereferenced tool parameter schema the arguments were
818
+ * produced for (`StrictJsonSchemaResult.source`).
819
+ * @returns A new object; the input is not mutated.
820
+ */
821
+export function omitNullToolArguments(
822
+ args: Record<string, unknown>,
823
+ schema: unknown
824
+): Record<string, unknown> {
825
+ return omitNulls(args, schema) as Record<string, unknown>;
826
+}
827
+
828
+function omitNulls(value: unknown, schema: unknown): unknown {
829
+ const node = isPlainObject(schema) ? schema : undefined;
830
+ if (Array.isArray(value)) {
831
+ const items = node && isPlainObject(node.items) ? node.items : undefined;
832
+ return value.map(item => omitNulls(item, items));
833
+ }
834
+ if (!isPlainObject(value)) return value;
835
+
836
+ const properties = node && isPlainObject(node.properties) ? node.properties : {};
837
+ const clone: Record<string, unknown> = {};
838
+ for (const [key, child] of Object.entries(value)) {
839
+ const propertySchema = properties[key];
840
+ if (child === null) {
841
+ if (propertySchema === undefined || schemaAcceptsNull(propertySchema)) clone[key] = child;
842
+ continue;
843
+ }
844
+ clone[key] = omitNulls(child, propertySchema);
845
+ }
846
+ return clone;
847
}