@composio/core 0.25.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{CustomTool-DZY1yLHN.d.mts → CustomTool-CqPoLUD6.d.mts} +1 -1
- package/dist/{cancellation-D-tMPk48.mjs → cancellation-ZoRh6EJQ.mjs} +54 -2
- package/dist/{composio-B8AENilE.d.mts → composio-BUa10iB3.d.mts} +65 -57
- package/dist/{customTool.types-Bi6-keZC.d.mts → customTool.types-gX421uPT.d.mts} +789 -33
- package/dist/docs/reference/sdk-reference/typescript/composio.mdx +3 -3
- package/dist/docs/reference/sdk-reference/typescript/session.mdx +2 -1
- package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +5 -1
- package/dist/experimental/index.d.mts +2 -2
- package/dist/index.d.mts +18 -13
- package/dist/index.mjs +6787 -6316
- package/dist/{types-BGDMkEUl.d.mts → types-DXxfzBX3.d.mts} +2 -2
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.mjs +1 -1
- package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
- package/package.json +3 -3
- package/src/composio.ts +68 -57
- package/src/lib/toolRouterMcp.ts +2 -0
- package/src/lib/toolRouterParams.ts +26 -3
- package/src/models/ConnectedAccounts.ts +7 -16
- package/src/models/SessionContext.ts +2 -17
- package/src/models/ToolRouter.ts +9 -2
- package/src/models/ToolRouterSession.ts +4 -19
- package/src/models/Tools.ts +1 -4
- package/src/models/Triggers.ts +6 -1
- package/src/services/internal/InternalService.ts +3 -4
- package/src/services/pusher/Pusher.ts +11 -4
- package/src/types/connectedAccountAuthStates.types.ts +2 -1
- package/src/types/requestOptions.types.ts +1 -10
- package/src/types/toolRouter.types.ts +156 -11
- package/src/utils/jsonSchema.ts +76 -4
- package/src/utils/sdk.ts +172 -11
- package/src/utils/toolkitDeprecation.ts +271 -0
- package/src/utils/transformers/connectedAccounts.ts +9 -20
- package/src/utils/transformers/mcp.ts +3 -10
- package/src/utils/transformers/toolRouterResponseTransform.ts +123 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import type { RequestOptions as ClientRequestOptions } from '@composio/client';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Per-request transport options for cancelling an SDK call.
|
|
@@ -38,15 +38,6 @@ export type ComposioRequestOptions = {
|
|
|
38
38
|
signal?: AbortSignal;
|
|
39
39
|
};
|
|
40
40
|
|
|
41
|
-
/**
|
|
42
|
-
* The `@composio/client` per-request transport options, reached via a public
|
|
43
|
-
* method whose only parameter is that type (`tools.retrieveEnum`). The
|
|
44
|
-
* `internal/*` subpath that declares `RequestOptions` is not in the package's
|
|
45
|
-
* `exports`, so we derive it structurally instead of deep-importing it.
|
|
46
|
-
* @internal
|
|
47
|
-
*/
|
|
48
|
-
type ClientRequestOptions = NonNullable<Parameters<ComposioClient['tools']['retrieveEnum']>[0]>;
|
|
49
|
-
|
|
50
41
|
/**
|
|
51
42
|
* Compile-time guards: {@link ComposioRequestOptions} is forwarded verbatim to
|
|
52
43
|
* every `@composio/client` call, so it MUST stay a structural subset of the
|
|
@@ -329,6 +329,75 @@ export const ToolRouterProxyExecuteSchema = z.union([
|
|
|
329
329
|
]);
|
|
330
330
|
export type ToolRouterProxyExecute = z.infer<typeof ToolRouterProxyExecuteSchema>;
|
|
331
331
|
|
|
332
|
+
/** Which tool calls a hook runs on: `'all'`, or only calls to the listed toolkits (including their proxy calls). */
|
|
333
|
+
export const ToolRouterHookAppliesToSchema = z.union([
|
|
334
|
+
z.literal('all'),
|
|
335
|
+
z.object({ toolkits: z.array(z.string()).describe('Toolkit slugs') }).strict(),
|
|
336
|
+
]);
|
|
337
|
+
export type ToolRouterHookAppliesTo = z.infer<typeof ToolRouterHookAppliesToSchema>;
|
|
338
|
+
|
|
339
|
+
/** Blocks a call or result when it matches `condition`, a plain sentence describing what to block. */
|
|
340
|
+
export const ToolRouterHookConditionCheckHandlerSchema = z
|
|
341
|
+
.object({
|
|
342
|
+
type: z.literal('condition_check'),
|
|
343
|
+
condition: z
|
|
344
|
+
.string()
|
|
345
|
+
.describe(
|
|
346
|
+
'What to block, written as a plain sentence. For example: "Sending email to anyone outside example.org".'
|
|
347
|
+
),
|
|
348
|
+
action: z.literal('block'),
|
|
349
|
+
})
|
|
350
|
+
.strict();
|
|
351
|
+
export type ToolRouterHookConditionCheckHandler = z.infer<
|
|
352
|
+
typeof ToolRouterHookConditionCheckHandlerSchema
|
|
353
|
+
>;
|
|
354
|
+
|
|
355
|
+
/** A pre-defined check that blocks results with text that tries to give the agent instructions. */
|
|
356
|
+
export const ToolRouterHookPromptInjectionCheckHandlerSchema = z
|
|
357
|
+
.object({
|
|
358
|
+
type: z.literal('prompt_injection_check'),
|
|
359
|
+
action: z.literal('block'),
|
|
360
|
+
})
|
|
361
|
+
.strict();
|
|
362
|
+
export type ToolRouterHookPromptInjectionCheckHandler = z.infer<
|
|
363
|
+
typeof ToolRouterHookPromptInjectionCheckHandlerSchema
|
|
364
|
+
>;
|
|
365
|
+
|
|
366
|
+
const toolRouterHookIdentityFields = {
|
|
367
|
+
id: z.string().describe('Unique within the session. Shows up in results and logs.'),
|
|
368
|
+
name: z
|
|
369
|
+
.string()
|
|
370
|
+
.optional()
|
|
371
|
+
.describe('A readable name. The agent sees it when this hook blocks a call.'),
|
|
372
|
+
appliesTo: ToolRouterHookAppliesToSchema,
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* A hook on a session's tool calls. A `before_execute` hook can block a call
|
|
377
|
+
* before it runs; an `after_execute` hook can block its result before the
|
|
378
|
+
* agent sees it.
|
|
379
|
+
*/
|
|
380
|
+
export const ToolRouterHookSchema = z.discriminatedUnion('type', [
|
|
381
|
+
z
|
|
382
|
+
.object({
|
|
383
|
+
type: z.literal('before_execute'),
|
|
384
|
+
...toolRouterHookIdentityFields,
|
|
385
|
+
handler: ToolRouterHookConditionCheckHandlerSchema,
|
|
386
|
+
})
|
|
387
|
+
.strict(),
|
|
388
|
+
z
|
|
389
|
+
.object({
|
|
390
|
+
type: z.literal('after_execute'),
|
|
391
|
+
...toolRouterHookIdentityFields,
|
|
392
|
+
handler: z.discriminatedUnion('type', [
|
|
393
|
+
ToolRouterHookConditionCheckHandlerSchema,
|
|
394
|
+
ToolRouterHookPromptInjectionCheckHandlerSchema,
|
|
395
|
+
]),
|
|
396
|
+
})
|
|
397
|
+
.strict(),
|
|
398
|
+
]);
|
|
399
|
+
export type ToolRouterHook = z.infer<typeof ToolRouterHookSchema>;
|
|
400
|
+
|
|
332
401
|
const ToolRouterCreateSessionConfigBaseSchema = z
|
|
333
402
|
.object({
|
|
334
403
|
sessionPreset: z
|
|
@@ -414,6 +483,13 @@ const ToolRouterCreateSessionConfigBaseSchema = z
|
|
|
414
483
|
'Proxy execute configuration for this session; a boolean is shorthand for `{ enable }`. Rejected by the API when enable is false and sandbox.enableProxyExecution is true.'
|
|
415
484
|
),
|
|
416
485
|
|
|
486
|
+
hooks: z
|
|
487
|
+
.array(ToolRouterHookSchema)
|
|
488
|
+
.optional()
|
|
489
|
+
.describe(
|
|
490
|
+
"Hooks that run on this session's tool calls. A hook can block a call before it runs, or block its result before the agent sees it."
|
|
491
|
+
),
|
|
492
|
+
|
|
417
493
|
preload: z
|
|
418
494
|
.object({
|
|
419
495
|
tools: z
|
|
@@ -480,6 +556,7 @@ const ToolRouterCreateSessionConfigBaseSchema = z
|
|
|
480
556
|
config.toolkits !== undefined && 'toolkits',
|
|
481
557
|
config.tools !== undefined && 'tools',
|
|
482
558
|
config.tags !== undefined && 'tags',
|
|
559
|
+
config.hooks !== undefined && 'hooks',
|
|
483
560
|
config.experimental.customTools !== undefined && 'experimental.customTools',
|
|
484
561
|
config.experimental.customToolkits !== undefined && 'experimental.customToolkits',
|
|
485
562
|
].filter((field): field is string => field !== false)
|
|
@@ -525,7 +602,7 @@ export const ToolRouterCreateSessionConfigSchema = z
|
|
|
525
602
|
* @param {SessionPreset} [sessionPreset] - Shortcut that exposes every tool allowed by the session filters directly in session.tools() and the MCP tool list. Disables search, multi-execute, manage-connections, and sandbox by default; explicit overrides for supported fields still win. Without this preset, ToolRouter uses the default configuration with meta tools enabled.
|
|
526
603
|
* @param {ToolRouterToolkitsParamSchema | ToolRouterToolkitsDisabledConfigSchema | ToolRouterToolkitsEnabledConfigSchema} toolkits - The toolkits to use in the tool router session
|
|
527
604
|
* @param {Record<string, ToolRouterToolsParam | ToolRouterConfigTools>} tools - The tools to configure per toolkit (key is toolkit slug)
|
|
528
|
-
* @param {Array<'readOnlyHint' | '
|
|
605
|
+
* @param {Array<'readOnlyHint' | 'createHint' | 'updateHint' | 'destructiveHint'>} tags - Global tags to filter tools by the type of action they take
|
|
529
606
|
* @param {Record<string, string>} authConfigs - The auth configs to use in the tool router session
|
|
530
607
|
* @param {Record<string, string | string[]>} connectedAccounts - The connected accounts to use in the tool router session. A single string is coerced to a single-element array before being sent to the backend.
|
|
531
608
|
* @param {ToolRouterInstant} [instant] - Experimental Instant usage policy. The project must allow Instant usage.
|
|
@@ -544,10 +621,11 @@ export const ToolRouterCreateSessionConfigSchema = z
|
|
|
544
621
|
* @param {boolean} [multiAccount.requireExplicitSelection] - When true, require explicit account selection when multiple accounts are connected
|
|
545
622
|
* @param {boolean | object} [proxyExecute] - Proxy execute configuration for this session. A boolean is shorthand for `{ enable }`.
|
|
546
623
|
* @param {boolean} proxyExecute.enable - `true` exposes the `COMPOSIO_PROXY_EXECUTE` meta tool. `false` also turns off the sandbox `proxy_execute()` helper.
|
|
624
|
+
* @param {ToolRouterHook[]} [hooks] - Hooks that run on this session's tool calls. A `before_execute` hook can block a call before it runs; an `after_execute` hook can block its result before the agent sees it. Cannot be combined with `experimental.sessionConfigId`.
|
|
547
625
|
* @param {object} [preload] - Tools to preload into session.tools() and the MCP tool list
|
|
548
626
|
* @param {string[] | 'all'} [preload.tools] - Tool slugs to preload, or "all" to preload every app tool allowed by the session filters. "all" requires a positive filter such as toolkits, tools, or tags; the backend validates and caps the final tool set.
|
|
549
627
|
* @param {object} [experimental] - Experimental features configuration. Not stable; may change or be removed.
|
|
550
|
-
* @param {string} [experimental.sessionConfigId] - ID of a saved Session config (`sc_…`) to apply at creation; see `composio.sessionConfigs`. Cannot be combined with `toolkits`, `tools`, `tags`, `experimental.customTools` or `experimental.customToolkits`. Per-session fields such as `authConfigs`, `connectedAccounts`, `manageConnections`, `sandbox`, `multiAccount` and `preload` stay allowed.
|
|
628
|
+
* @param {string} [experimental.sessionConfigId] - ID of a saved Session config (`sc_…`) to apply at creation; see `composio.sessionConfigs`. Cannot be combined with `toolkits`, `tools`, `tags`, `hooks`, `experimental.customTools` or `experimental.customToolkits`. Per-session fields such as `authConfigs`, `connectedAccounts`, `manageConnections`, `sandbox`, `multiAccount` and `preload` stay allowed.
|
|
551
629
|
*/
|
|
552
630
|
export type ToolRouterCreateSessionConfig =
|
|
553
631
|
InlineAccessCreateSessionConfig | SavedConfigCreateSessionConfig;
|
|
@@ -565,11 +643,12 @@ type InlineAccessCreateSessionConfig = Omit<ParsedCreateSessionConfig, 'experime
|
|
|
565
643
|
/** Create input that takes its access policy from a saved Session config. */
|
|
566
644
|
type SavedConfigCreateSessionConfig = Omit<
|
|
567
645
|
ParsedCreateSessionConfig,
|
|
568
|
-
'toolkits' | 'tools' | 'tags' | 'experimental'
|
|
646
|
+
'toolkits' | 'tools' | 'tags' | 'hooks' | 'experimental'
|
|
569
647
|
> & {
|
|
570
648
|
toolkits?: never;
|
|
571
649
|
tools?: never;
|
|
572
650
|
tags?: never;
|
|
651
|
+
hooks?: never;
|
|
573
652
|
experimental: Omit<
|
|
574
653
|
ParsedCreateSessionExperimental,
|
|
575
654
|
'sessionConfigId' | 'customTools' | 'customToolkits'
|
|
@@ -745,6 +824,37 @@ export const ToolRouterSessionSearchResponseSchema = z.object({
|
|
|
745
824
|
});
|
|
746
825
|
export type ToolRouterSessionSearchResponse = z.infer<typeof ToolRouterSessionSearchResponseSchema>;
|
|
747
826
|
|
|
827
|
+
// --- Session hook results (camelCase) ---
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* What one session hook decided about a call. `unavailable` means the hook
|
|
831
|
+
* could not be evaluated (for example it timed out); it does not block the
|
|
832
|
+
* call.
|
|
833
|
+
*/
|
|
834
|
+
export const ToolRouterHookResultSchema = z.discriminatedUnion('status', [
|
|
835
|
+
z.object({
|
|
836
|
+
id: z.string().describe('The hook id'),
|
|
837
|
+
status: z.literal('evaluated'),
|
|
838
|
+
outcome: z.enum(['continue', 'block']).describe('What the hook decided'),
|
|
839
|
+
}),
|
|
840
|
+
z.object({
|
|
841
|
+
id: z.string().describe('The hook id'),
|
|
842
|
+
status: z.literal('unavailable'),
|
|
843
|
+
}),
|
|
844
|
+
]);
|
|
845
|
+
export type ToolRouterHookResult = z.infer<typeof ToolRouterHookResultSchema>;
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* Why a session hook blocked a call. `request_blocked`: a `before_execute` hook
|
|
849
|
+
* blocked it and the tool did not run. `response_blocked`: the tool ran and an
|
|
850
|
+
* `after_execute` hook blocked its result.
|
|
851
|
+
*/
|
|
852
|
+
export const ToolRouterBlockReasonSchema = z.object({
|
|
853
|
+
type: z.enum(['request_blocked', 'response_blocked']),
|
|
854
|
+
hookId: z.string(),
|
|
855
|
+
});
|
|
856
|
+
export type ToolRouterBlockReason = z.infer<typeof ToolRouterBlockReasonSchema>;
|
|
857
|
+
|
|
748
858
|
// --- Session execute response schema (camelCase) ---
|
|
749
859
|
|
|
750
860
|
export const ToolRouterSessionExecuteResponseSchema = z.object({
|
|
@@ -752,13 +862,19 @@ export const ToolRouterSessionExecuteResponseSchema = z.object({
|
|
|
752
862
|
error: z.string().nullable(),
|
|
753
863
|
logId: z.string(),
|
|
754
864
|
/**
|
|
755
|
-
* Whether the tool ran and succeeded (`completed`)
|
|
756
|
-
* (`failed`)
|
|
757
|
-
*
|
|
865
|
+
* Whether the tool ran and succeeded (`completed`), ran and failed
|
|
866
|
+
* (`failed`), or was blocked by a session hook (`blocked`). A failed
|
|
867
|
+
* execution can carry a `null` or empty `error`, so read this rather than
|
|
868
|
+
* `error` to tell them apart. A blocked call has empty `data` and the
|
|
869
|
+
* agent-facing message in `error`.
|
|
758
870
|
*/
|
|
759
|
-
resultType: z.enum(['completed', 'failed']),
|
|
871
|
+
resultType: z.enum(['completed', 'failed', 'blocked']),
|
|
760
872
|
/** Actual Instant usage charge when the Session opts into returning it. */
|
|
761
873
|
instantCharge: z.unknown().optional(),
|
|
874
|
+
/** Set when `resultType` is `blocked`: which hook blocked the call, and at which stage. */
|
|
875
|
+
blockReason: ToolRouterBlockReasonSchema.optional(),
|
|
876
|
+
/** Every session hook that applied to this call. Absent when none applied. */
|
|
877
|
+
hookResults: z.array(ToolRouterHookResultSchema).optional(),
|
|
762
878
|
});
|
|
763
879
|
export type ToolRouterSessionExecuteResponse = z.infer<
|
|
764
880
|
typeof ToolRouterSessionExecuteResponseSchema
|
|
@@ -766,7 +882,9 @@ export type ToolRouterSessionExecuteResponse = z.infer<
|
|
|
766
882
|
|
|
767
883
|
// --- Session proxy execute response (matches ToolProxyResponse from client) ---
|
|
768
884
|
|
|
769
|
-
|
|
885
|
+
/** A proxied request that was sent. */
|
|
886
|
+
export interface ToolRouterSessionProxyExecuteCompleted {
|
|
887
|
+
resultType: 'completed';
|
|
770
888
|
/** The HTTP status code returned from the proxied API */
|
|
771
889
|
status: number;
|
|
772
890
|
/** The response data from the proxied API */
|
|
@@ -780,8 +898,28 @@ export interface ToolRouterSessionProxyExecuteResponse {
|
|
|
780
898
|
url: string;
|
|
781
899
|
expiresAt?: string;
|
|
782
900
|
};
|
|
901
|
+
/** Every session hook that applied to this request. Absent when none applied. */
|
|
902
|
+
hookResults?: ToolRouterHookResult[];
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/** A proxied request that a session hook blocked. */
|
|
906
|
+
export interface ToolRouterSessionProxyExecuteBlocked {
|
|
907
|
+
resultType: 'blocked';
|
|
908
|
+
/** Which hook blocked the request, and at which stage. */
|
|
909
|
+
blockReason: ToolRouterBlockReason;
|
|
910
|
+
/** A message for the agent. It names the hook when the hook has a `name`. */
|
|
911
|
+
message: string;
|
|
912
|
+
/** Every session hook that applied to this request. */
|
|
913
|
+
hookResults?: ToolRouterHookResult[];
|
|
783
914
|
}
|
|
784
915
|
|
|
916
|
+
/**
|
|
917
|
+
* Result of `session.proxyExecute()`. Check `resultType` before reading
|
|
918
|
+
* `status`: a request a session hook blocked has no HTTP response.
|
|
919
|
+
*/
|
|
920
|
+
export type ToolRouterSessionProxyExecuteResponse =
|
|
921
|
+
ToolRouterSessionProxyExecuteCompleted | ToolRouterSessionProxyExecuteBlocked;
|
|
922
|
+
|
|
785
923
|
/**
|
|
786
924
|
* Experimental features on a tool router session.
|
|
787
925
|
* Contains features that may be modified or removed in future versions.
|
|
@@ -1096,6 +1234,11 @@ export const ToolRouterUpdateSessionConfigSchema = z
|
|
|
1096
1234
|
.describe(
|
|
1097
1235
|
'Replaces the proxy execute block; a boolean is shorthand for `{ enable }` and `null` removes it'
|
|
1098
1236
|
),
|
|
1237
|
+
hooks: z
|
|
1238
|
+
.array(ToolRouterHookSchema)
|
|
1239
|
+
.nullable()
|
|
1240
|
+
.optional()
|
|
1241
|
+
.describe('Replaces the whole list of hooks; `null` removes every hook'),
|
|
1099
1242
|
preload: z
|
|
1100
1243
|
.object({
|
|
1101
1244
|
tools: z.union([z.array(z.string()), z.literal('all')]).optional(),
|
|
@@ -1136,6 +1279,7 @@ export const ToolRouterUpdateSessionConfigSchema = z
|
|
|
1136
1279
|
config.toolkits !== undefined && 'toolkits',
|
|
1137
1280
|
config.tools !== undefined && 'tools',
|
|
1138
1281
|
config.tags !== undefined && 'tags',
|
|
1282
|
+
config.hooks !== undefined && 'hooks',
|
|
1139
1283
|
].filter((field): field is string => field !== false)
|
|
1140
1284
|
);
|
|
1141
1285
|
}
|
|
@@ -1151,8 +1295,8 @@ export const ToolRouterUpdateSessionConfigSchema = z
|
|
|
1151
1295
|
|
|
1152
1296
|
/**
|
|
1153
1297
|
* Options for `session.update()`. `experimental.sessionConfigId` applies a
|
|
1154
|
-
* saved Session config and cannot be combined with `toolkits`, `tools
|
|
1155
|
-
* `tags` (including `null`).
|
|
1298
|
+
* saved Session config and cannot be combined with `toolkits`, `tools`,
|
|
1299
|
+
* `tags` or `hooks` (including `null`).
|
|
1156
1300
|
*/
|
|
1157
1301
|
export type ToolRouterUpdateSessionConfig =
|
|
1158
1302
|
InlineAccessUpdateSessionConfig | SavedConfigUpdateSessionConfig;
|
|
@@ -1169,11 +1313,12 @@ type InlineAccessUpdateSessionConfig = Omit<ParsedUpdateSessionConfig, 'experime
|
|
|
1169
1313
|
/** Update input that applies a saved Session config. */
|
|
1170
1314
|
type SavedConfigUpdateSessionConfig = Omit<
|
|
1171
1315
|
ParsedUpdateSessionConfig,
|
|
1172
|
-
'toolkits' | 'tools' | 'tags' | 'experimental'
|
|
1316
|
+
'toolkits' | 'tools' | 'tags' | 'hooks' | 'experimental'
|
|
1173
1317
|
> & {
|
|
1174
1318
|
toolkits?: never;
|
|
1175
1319
|
tools?: never;
|
|
1176
1320
|
tags?: never;
|
|
1321
|
+
hooks?: never;
|
|
1177
1322
|
experimental: Omit<ParsedUpdateSessionExperimental, 'sessionConfigId'> & {
|
|
1178
1323
|
sessionConfigId: string;
|
|
1179
1324
|
};
|
package/src/utils/jsonSchema.ts
CHANGED
|
@@ -515,11 +515,17 @@ export function jsonSchemaToZodSchema<T extends z.ZodTypeAny>(
|
|
|
515
515
|
* added to it and widened to accept `null`, the emulation of optional
|
|
516
516
|
* fields that OpenAI structured outputs document.
|
|
517
517
|
* - `unsupported-keyword-stripped` — an annotation keyword the API rejects
|
|
518
|
-
* (`default`, `examples`
|
|
518
|
+
* (`default`, `examples`, or a string `format` outside the accepted list)
|
|
519
|
+
* was removed.
|
|
519
520
|
* - `one-of-converted` — `oneOf` (unsupported) became `anyOf`.
|
|
521
|
+
* - `nullable-converted` — OpenAPI `nullable: true`, which Anthropic rejects
|
|
522
|
+
* on an object, became a `null` member of `type` or a null branch.
|
|
520
523
|
*/
|
|
521
524
|
export type StrictSchemaChangeReason =
|
|
522
|
-
'optional-property-nullable'
|
|
525
|
+
| 'optional-property-nullable'
|
|
526
|
+
| 'unsupported-keyword-stripped'
|
|
527
|
+
| 'one-of-converted'
|
|
528
|
+
| 'nullable-converted';
|
|
523
529
|
|
|
524
530
|
/** A single lossless rewrite applied by {@link toStrictJsonSchema}. */
|
|
525
531
|
export interface StrictSchemaChange {
|
|
@@ -567,6 +573,27 @@ const MAX_STRICT_CHANGES = 50;
|
|
|
567
573
|
/** Annotation-only keywords OpenAI structured outputs rejects; safe to strip. */
|
|
568
574
|
const STRICT_STRIP_KEYWORDS = new Set(['examples', 'default']);
|
|
569
575
|
|
|
576
|
+
/**
|
|
577
|
+
* The `format` values OpenAI structured outputs accepts on a string schema,
|
|
578
|
+
* matched case-sensitively; any other value there is rejected with a 400.
|
|
579
|
+
* Formats on number and integer schemas are not checked.
|
|
580
|
+
*/
|
|
581
|
+
const STRICT_STRING_FORMATS = new Set([
|
|
582
|
+
'date-time',
|
|
583
|
+
'time',
|
|
584
|
+
'date',
|
|
585
|
+
'duration',
|
|
586
|
+
'email',
|
|
587
|
+
'hostname',
|
|
588
|
+
'ipv4',
|
|
589
|
+
'ipv6',
|
|
590
|
+
'uuid',
|
|
591
|
+
]);
|
|
592
|
+
|
|
593
|
+
/** Whether a `type` value admits strings; an absent `type` admits every type. */
|
|
594
|
+
const admitsString = (type: unknown): boolean =>
|
|
595
|
+
type === undefined || type === 'string' || (Array.isArray(type) && type.includes('string'));
|
|
596
|
+
|
|
570
597
|
/** Keywords OpenAI structured outputs reject and that have no lossless rewrite. */
|
|
571
598
|
const STRICT_UNSUPPORTED_KEYWORDS = [
|
|
572
599
|
'allOf',
|
|
@@ -676,6 +703,11 @@ function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown
|
|
|
676
703
|
* the one it was given: the rewrite types every node that declares
|
|
677
704
|
* `properties` as an object, so such a node stops accepting null.
|
|
678
705
|
*
|
|
706
|
+
* `followRefs: false` makes every `$ref` reject null without resolving it.
|
|
707
|
+
* Folding `nullable` needs that, because a `$ref` can lead back to the node
|
|
708
|
+
* being folded, whose source still accepts null. It costs at most a
|
|
709
|
+
* redundant null branch.
|
|
710
|
+
*
|
|
679
711
|
* One check serves a whole document, and an answer is computed once per node.
|
|
680
712
|
* A reference cycle never yields a null by itself, so a node met again while
|
|
681
713
|
* it is being evaluated counts as rejecting. An answer that leans on that is
|
|
@@ -690,7 +722,8 @@ function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown
|
|
|
690
722
|
*/
|
|
691
723
|
function createNullCheck(
|
|
692
724
|
root: Record<string, unknown>,
|
|
693
|
-
strictOutput = false
|
|
725
|
+
strictOutput = false,
|
|
726
|
+
followRefs = true
|
|
694
727
|
): (schema: unknown) => boolean {
|
|
695
728
|
// Markers for what an answer leans on, besides the depth of a node on the path.
|
|
696
729
|
const NOTHING = MAX_NULL_CHECK_DEPTH + 1;
|
|
@@ -769,12 +802,16 @@ function createNullCheck(
|
|
|
769
802
|
};
|
|
770
803
|
|
|
771
804
|
const keywordsAccept = (node: Record<string, unknown>): boolean => {
|
|
805
|
+
// OpenAPI `nullable: true` admits null whatever the other keywords say,
|
|
806
|
+
// as the Zod conversion reads it.
|
|
807
|
+
if (node.nullable === true) return true;
|
|
772
808
|
if (typeof node.type === 'string' && node.type !== 'null') return false;
|
|
773
809
|
if (Array.isArray(node.type) && !node.type.includes('null')) return false;
|
|
774
810
|
if (strictOutput && !('type' in node) && isPlainObject(node.properties)) return false;
|
|
775
811
|
if (Array.isArray(node.enum) && !node.enum.includes(null)) return false;
|
|
776
812
|
if ('const' in node && node.const !== null) return false;
|
|
777
813
|
if ('$ref' in node) {
|
|
814
|
+
if (!followRefs) return false;
|
|
778
815
|
const resolution =
|
|
779
816
|
typeof node.$ref === 'string' ? tryResolvePointer(root, node.$ref) : undefined;
|
|
780
817
|
if (resolution === undefined || resolution.kind === 'unresolved') return false;
|
|
@@ -811,7 +848,9 @@ function createNullCheck(
|
|
|
811
848
|
* sends for such a property means "omitted"; the strict providers drop it
|
|
812
849
|
* before executing the tool (see {@link omitNullToolArguments});
|
|
813
850
|
* - `type` arrays are kept as-is (the API accepts them); `oneOf` becomes
|
|
814
|
-
* `anyOf`; `default` and `
|
|
851
|
+
* `anyOf`; `default`, `examples`, and a string `format` the API does
|
|
852
|
+
* not accept are stripped; OpenAPI `nullable` is stripped too, and a
|
|
853
|
+
* node that set it to `true` is widened to accept `null`;
|
|
815
854
|
* - local `$ref`s into `$defs`/`definitions` are kept (the API supports
|
|
816
855
|
* them, including recursion) and the definitions themselves are
|
|
817
856
|
* normalized; an optional `$ref` property is widened with an `anyOf`
|
|
@@ -841,6 +880,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
841
880
|
|
|
842
881
|
const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
|
|
843
882
|
const acceptsNullInOutput = createNullCheck(root, true);
|
|
883
|
+
const acceptsNullWithoutRefs = createNullCheck(root, true, false);
|
|
844
884
|
|
|
845
885
|
function walkChildren(
|
|
846
886
|
node: Record<string, unknown>,
|
|
@@ -892,6 +932,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
892
932
|
|
|
893
933
|
const node: Record<string, unknown> = {};
|
|
894
934
|
for (const [key, child] of Object.entries(value)) {
|
|
935
|
+
if (key === 'nullable') continue;
|
|
895
936
|
if (STRICT_STRIP_KEYWORDS.has(key)) {
|
|
896
937
|
recordChange({
|
|
897
938
|
path,
|
|
@@ -900,6 +941,19 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
900
941
|
});
|
|
901
942
|
continue;
|
|
902
943
|
}
|
|
944
|
+
if (
|
|
945
|
+
key === 'format' &&
|
|
946
|
+
typeof child === 'string' &&
|
|
947
|
+
!STRICT_STRING_FORMATS.has(child) &&
|
|
948
|
+
admitsString(value.type)
|
|
949
|
+
) {
|
|
950
|
+
recordChange({
|
|
951
|
+
path,
|
|
952
|
+
reason: 'unsupported-keyword-stripped',
|
|
953
|
+
detail: `format "${child}" removed`,
|
|
954
|
+
});
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
903
957
|
setOwn(node, key, child);
|
|
904
958
|
}
|
|
905
959
|
if (Array.isArray(node.oneOf) && node.anyOf === undefined) {
|
|
@@ -932,6 +986,24 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
|
|
|
932
986
|
unsupported.push({ path, keyword: 'properties', detail: 'properties is not an object' });
|
|
933
987
|
}
|
|
934
988
|
|
|
989
|
+
const normalized = normalizeNode(node, mode, depth, path);
|
|
990
|
+
if (!('nullable' in value)) return normalized;
|
|
991
|
+
const widened =
|
|
992
|
+
value.nullable === true ? widenToNullable(normalized, acceptsNullWithoutRefs) : normalized;
|
|
993
|
+
recordChange(
|
|
994
|
+
widened === normalized
|
|
995
|
+
? { path, reason: 'unsupported-keyword-stripped', detail: 'keyword "nullable" removed' }
|
|
996
|
+
: { path, reason: 'nullable-converted', detail: 'nullable became a null type' }
|
|
997
|
+
);
|
|
998
|
+
return widened;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function normalizeNode(
|
|
1002
|
+
node: Record<string, unknown>,
|
|
1003
|
+
mode: StrictWalkMode,
|
|
1004
|
+
depth: number,
|
|
1005
|
+
path: string
|
|
1006
|
+
): Record<string, unknown> {
|
|
935
1007
|
const out = walkChildren(node, mode, depth, path);
|
|
936
1008
|
|
|
937
1009
|
if (typeof node.$ref === 'string') {
|