@composio/core 0.22.0 → 0.23.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 (48) hide show
  1. package/dist/{CustomTool-CKBCElpT.d.mts → CustomTool-CnHdegDK.d.mts} +1 -1
  2. package/dist/{CustomTool-B-_VjWpy.mjs → CustomTool-CnJxXr07.mjs} +1 -1
  3. package/dist/{cancellation-DV8CIi52.mjs → cancellation-BQibgpRG.mjs} +166 -34
  4. package/dist/{composio-C-418N1P.d.mts → composio-Dq708dZS.d.mts} +2 -20
  5. package/dist/{customTool.types-CK408sI-.d.mts → customTool.types-B8lVpHOP.d.mts} +21 -64
  6. package/dist/docs/reference/sdk-reference/typescript/logs.mdx +4 -4
  7. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +1 -1
  8. package/dist/docs/reference/sdk-reference/typescript/session.mdx +2 -2
  9. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +2 -2
  10. package/dist/docs/reference/sdk-reference/typescript/usage.mdx +2 -2
  11. package/dist/{errors-Dyiu3ifQ.mjs → errors-BN15NcCW.mjs} +34 -2
  12. package/dist/experimental/index.d.mts +2 -2
  13. package/dist/experimental/index.mjs +1 -1
  14. package/dist/index.d.mts +45 -4
  15. package/dist/index.mjs +1589 -1448
  16. package/dist/platform/node.d.mts +1 -1
  17. package/dist/platform/node.mjs +13 -0
  18. package/dist/platform/workerd.d.mts +1 -1
  19. package/dist/platform/workerd.mjs +3 -0
  20. package/dist/{types-D5A2wzBl.d.mts → types-DuVZKrXO.d.mts} +2 -0
  21. package/dist/{types-RpMRVn4D.d.mts → types-eTw8Yw7Y.d.mts} +2 -2
  22. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  23. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  24. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  25. package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
  26. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  27. package/package.json +7 -4
  28. package/src/errors/ToolRouterErrors.ts +65 -0
  29. package/src/lib/toolRouterParams.ts +4 -14
  30. package/src/models/CustomToolkits.ts +1 -1
  31. package/src/models/RemoteFile.ts +24 -5
  32. package/src/models/SessionContext.ts +24 -4
  33. package/src/models/ToolRouter.ts +2 -4
  34. package/src/models/ToolRouterSession.ts +44 -13
  35. package/src/models/Tools.ts +20 -36
  36. package/src/models/customToolExecution.ts +10 -0
  37. package/src/platform/node.ts +16 -0
  38. package/src/platform/types.ts +3 -0
  39. package/src/platform/workerd.ts +4 -0
  40. package/src/provider/BaseProvider.ts +2 -1
  41. package/src/types/tool.types.ts +5 -0
  42. package/src/types/toolRouter.types.ts +10 -24
  43. package/src/utils/jsonSchema.ts +191 -36
  44. package/src/utils/retries.ts +20 -0
  45. package/src/utils/safePath.ts +135 -54
  46. package/src/utils/session.ts +31 -2
  47. package/src/utils/transformers/toolRouterResponseTransform.ts +64 -25
  48. package/src/utils/transformers/usage.ts +1 -4
@@ -62,7 +62,11 @@ import {
62
62
  import { dereferenceJsonSchema } from '../utils/jsonSchema';
63
63
  import { ComposioRequestOptions } from '../types/requestOptions.types';
64
64
  import { withCancellation } from '../utils/cancellation';
65
- import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
65
+ import { withoutRetries } from '../utils/retries';
66
+ import {
67
+ isExecutionSuccessful,
68
+ transformExecuteResponse,
69
+ } from '../utils/transformers/toolRouterResponseTransform';
66
70
  import { ComposioRequestCancelledError } from '../errors/SDKErrors';
67
71
 
68
72
  const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
@@ -120,11 +124,6 @@ export class Tools<
120
124
  */
121
125
  private readonly warnedAutoUploadDisabledForTool = new Set<string>();
122
126
 
123
- /**
124
- * Lazily-built sibling client with retries disabled; see `clientWithoutRetries`.
125
- */
126
- private clientWithoutRetriesCache?: ComposioClient;
127
-
128
127
  constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
129
128
  if (!client) {
130
129
  throw new Error('ComposioClient is required');
@@ -157,27 +156,6 @@ export class Tools<
157
156
  telemetry.instrument(this, 'Tools');
158
157
  }
159
158
 
160
- /**
161
- * A cached sibling client that never retries requests, mirroring Python's
162
- * `client.without_retries`.
163
- *
164
- * Used for non-idempotent writes (`tools.execute` / `tools.proxy`), where a
165
- * silent retry after a read timeout can duplicate a side effect (e.g. send an
166
- * email twice). Reads keep the default retry behaviour, and so do other writes
167
- * (`toolRouter.session.execute`, auth-config and connected-account mutations):
168
- * the durable fix there is backend-honoured idempotency keys, tracked
169
- * separately.
170
- *
171
- * Cached rather than rebuilt per call because `withOptions` constructs a fresh
172
- * client; its options never change, so one per `Tools` instance suffices.
173
- */
174
- private get clientWithoutRetries(): ComposioClient {
175
- if (!this.clientWithoutRetriesCache) {
176
- this.clientWithoutRetriesCache = this.client.withOptions({ maxRetries: 0 });
177
- }
178
- return this.clientWithoutRetriesCache;
179
- }
180
-
181
159
  /**
182
160
  * Transforms tool data from snake_case API format to camelCase for internal SDK use.
183
161
  *
@@ -1022,9 +1000,7 @@ export class Tools<
1022
1000
  text: body.text,
1023
1001
  };
1024
1002
  const result = await withCancellation(
1025
- // Disable retries: tool execution is a non-idempotent write, and a
1026
- // silent retry after a read timeout can duplicate the side effect.
1027
- () => this.clientWithoutRetries.tools.execute(tool.slug, executeBody, requestOptions),
1003
+ () => this.client.tools.execute(tool.slug, executeBody, withoutRetries(requestOptions)),
1028
1004
  requestOptions?.signal
1029
1005
  );
1030
1006
  // transform the response to the ToolExecuteResponse format
@@ -1254,15 +1230,23 @@ export class Tools<
1254
1230
  }
1255
1231
 
1256
1232
  const response = await withCancellation(
1257
- () => this.client.toolRouter.session.execute(body.sessionId, executePayload, requestOptions),
1233
+ () =>
1234
+ this.client.toolRouter.session.execute(
1235
+ body.sessionId,
1236
+ executePayload,
1237
+ withoutRetries(requestOptions)
1238
+ ),
1258
1239
  requestOptions?.signal
1259
1240
  );
1260
1241
 
1261
- const { data, error, logId, instantCharge } = transformExecuteResponse(response);
1242
+ const { data, error, logId, resultType, instantCharge } = transformExecuteResponse(
1243
+ response,
1244
+ toolSlug
1245
+ );
1262
1246
  let result: ToolExecuteResponse = {
1263
1247
  data,
1264
1248
  error,
1265
- successful: !error,
1249
+ successful: isExecutionSuccessful({ resultType }),
1266
1250
  logId,
1267
1251
  ...(instantCharge !== undefined && { instantCharge }),
1268
1252
  };
@@ -1352,6 +1336,7 @@ export class Tools<
1352
1336
  * @param {string} body.endpoint - Path relative to the toolkit's base URL, or an absolute URL
1353
1337
  * @param {'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'} body.method - HTTP method
1354
1338
  * @param {string} [body.connectedAccountId] - The connected account to authenticate as
1339
+ * @param {string} [body.userId] - The user the connected account belongs to. Projects with 2FA enabled check it against the connected account and may require it
1355
1340
  * @param {unknown} [body.body] - JSON request body
1356
1341
  * @param {Array<{ in: 'query' | 'header'; name: string; value: string | number }>} [body.parameters] - Extra query parameters or headers
1357
1342
  * @returns {Promise<ToolProxyResponse>} The upstream status, headers, and parsed body
@@ -1399,6 +1384,7 @@ export class Tools<
1399
1384
  method: toolProxyParams.data.method,
1400
1385
  body: toolProxyParams.data.body,
1401
1386
  connected_account_id: toolProxyParams.data.connectedAccountId,
1387
+ user_id: toolProxyParams.data.userId,
1402
1388
  parameters: parameters,
1403
1389
  /**
1404
1390
  * @deprecated The `customConnectionData` proxy param is deprecated and will be
@@ -1409,9 +1395,7 @@ export class Tools<
1409
1395
  custom_connection_data: toolProxyParams.data.customConnectionData,
1410
1396
  } as ComposioToolProxyParams;
1411
1397
  return withCancellation(
1412
- // Disable retries: a proxied call is a non-idempotent write, and a silent
1413
- // retry after a read timeout can duplicate the side effect.
1414
- () => this.clientWithoutRetries.tools.proxy(proxyBody, requestOptions),
1398
+ () => this.client.tools.proxy(proxyBody, withoutRetries(requestOptions)),
1415
1399
  requestOptions?.signal
1416
1400
  );
1417
1401
  }
@@ -10,6 +10,7 @@ import type {
10
10
  import type { ToolExecuteResponse } from '../types/tool.types';
11
11
  import { ValidationError } from '../errors';
12
12
  import { ComposioRequestCancelledError, isRequestAbortError } from '../errors/SDKErrors';
13
+ import { ComposioToolInputRequiredError } from '../errors/ToolRouterErrors';
13
14
 
14
15
  /**
15
16
  * Find a custom tool entry by slug.
@@ -59,6 +60,9 @@ export function assertUnambiguousCustomToolSlug(
59
60
  * and wraps the result into the standard response format.
60
61
  *
61
62
  * Callers provide a pre-built SessionContext (which may include sibling routing).
63
+ *
64
+ * @throws {ComposioToolInputRequiredError} If a call the tool made through the
65
+ * session context needs user input before it can run
62
66
  */
63
67
  export async function executeCustomTool(
64
68
  entry: CustomToolsMapEntry,
@@ -103,6 +107,12 @@ export async function executeCustomTool(
103
107
  if (err instanceof ComposioRequestCancelledError) {
104
108
  throw err;
105
109
  }
110
+ // `ctx.execute()` / `ctx.proxyExecute()` asked for user input: nothing ran.
111
+ // Flattening it into a failed result would drop the questions and the
112
+ // request state the caller needs to answer them.
113
+ if (err instanceof ComposioToolInputRequiredError) {
114
+ throw err;
115
+ }
106
116
  if (options?.signal?.aborted && isRequestAbortError(err)) {
107
117
  throw new ComposioRequestCancelledError(undefined, {
108
118
  cause: err instanceof Error ? err : undefined,
@@ -108,4 +108,20 @@ export const platform = {
108
108
  fs.writeFileSync(filePath, content);
109
109
  }
110
110
  },
111
+
112
+ writeFileExclusiveSync(filePath: string, content: Uint8Array): void {
113
+ const fd = fs.openSync(filePath, 'wx');
114
+ try {
115
+ try {
116
+ fs.writeFileSync(fd, content);
117
+ } finally {
118
+ fs.closeSync(fd);
119
+ }
120
+ } catch (error) {
121
+ // The path was created here, so a failed write or close must not leave
122
+ // a partial file that a retry would treat as an existing download.
123
+ fs.rmSync(filePath, { force: true });
124
+ throw error;
125
+ }
126
+ },
111
127
  } as Platform;
@@ -85,6 +85,9 @@ export interface Platform {
85
85
  writeFileSync(filePath: string, content: Uint8Array, encoding?: never): void;
86
86
  writeFileSync(filePath: string, content: string, encoding: Uint8ArrayEncoding): void;
87
87
 
88
+ /** Writes a new file, failing if its path already exists. A failed write removes the file. */
89
+ writeFileExclusiveSync(filePath: string, content: Uint8Array): void;
90
+
88
91
  /**
89
92
  * Indicates whether this platform supports file system operations.
90
93
  * Edge runtimes like Cloudflare Workers return false.
@@ -108,4 +108,8 @@ export const platform: Platform = {
108
108
  'Use environment variables or external storage services instead.'
109
109
  );
110
110
  },
111
+
112
+ writeFileExclusiveSync(_filePath: string, _content: Uint8Array): never {
113
+ throw new Error('File system operations are not supported in this runtime environment.');
114
+ },
111
115
  };
@@ -8,6 +8,7 @@ import {
8
8
  ToolCallExecutionTarget,
9
9
  } from '../types/provider.types';
10
10
  import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
11
+ import { isExecutionSuccessful } from '../utils/transformers/toolRouterResponseTransform';
11
12
 
12
13
  /**
13
14
  * @internal
@@ -108,7 +109,7 @@ abstract class BaseProvider<TMcpResponse> {
108
109
  const result = await target.execute(toolSlug, arguments_);
109
110
  return {
110
111
  ...result,
111
- successful: result.error === null,
112
+ successful: isExecutionSuccessful(result),
112
113
  };
113
114
  }
114
115
 
@@ -426,6 +426,11 @@ export const ToolProxyParamsSchema = z.object({
426
426
  )
427
427
  .optional(),
428
428
  connectedAccountId: z.string().optional(),
429
+ /**
430
+ * The user the connected account belongs to. Projects with 2FA enabled check it
431
+ * against the connected account, and require it for orgs created on or after
432
+ */
433
+ userId: z.string().optional(),
429
434
  /**
430
435
  * @deprecated
431
436
  */
@@ -630,6 +630,12 @@ export const ToolRouterSessionExecuteResponseSchema = z.object({
630
630
  data: z.record(z.string(), z.unknown()),
631
631
  error: z.string().nullable(),
632
632
  logId: z.string(),
633
+ /**
634
+ * Whether the tool ran and succeeded (`completed`) or ran and failed
635
+ * (`failed`). A failed execution can carry a `null` or empty `error`, so
636
+ * read this rather than `error` to tell the two apart.
637
+ */
638
+ resultType: z.enum(['completed', 'failed']),
633
639
  /** Actual Instant usage charge when the Session opts into returning it. */
634
640
  instantCharge: z.unknown().optional(),
635
641
  });
@@ -709,28 +715,13 @@ export type ToolRouterSessionWorkbenchConfig = SessionCreateResponse.Config.Work
709
715
 
710
716
  export type ToolRouterSessionWarning = SessionCreateResponse.Warning;
711
717
 
712
- const ToolRouterInstantResponseFilterSchema = z.union([
713
- z.object({ enabled: z.array(z.string()) }),
714
- z.object({ disabled: z.array(z.string()) }),
715
- ]);
716
-
717
- /** Instant policy in the server's Session config (wire field casing). */
718
- export const ToolRouterInstantResponseSchema = z.object({
719
- toolkits: ToolRouterInstantResponseFilterSchema.optional(),
720
- tools: z.record(z.string(), ToolRouterInstantResponseFilterSchema).optional(),
721
- return_instant_charge: z.boolean(),
722
- });
723
- export type ToolRouterInstantResponse = z.infer<typeof ToolRouterInstantResponseSchema>;
724
-
725
718
  /**
726
719
  * Server-side session configuration as returned by the API: toolkit/tool
727
720
  * allowlists, tags, auth configs, connected accounts, manage_connections,
728
- * preload, sandbox (`workbench`), search, execute and Instant settings.
729
- * The generated client still declares the old policy name.
721
+ * preload, sandbox (`workbench`), search, execute, proxy execute and Instant
722
+ * settings.
730
723
  */
731
- export type ToolRouterSessionConfig = Omit<SessionCreateResponse.Config, 'premium_usage'> & {
732
- instant?: false | ToolRouterInstantResponse;
733
- };
724
+ export type ToolRouterSessionConfig = SessionCreateResponse.Config;
734
725
 
735
726
  export interface ToolRouterSessionMetadata {
736
727
  /** Present on every session built from an API response; the constructor synthesises a minimal config when absent. */
@@ -1046,12 +1037,7 @@ export type ToolRouterSessionListConfigHistoryOptions = z.infer<
1046
1037
  * The session configuration at one version, as stored by the API. This is
1047
1038
  * the wire shape (snake_case), with the Instant policy under `instant`.
1048
1039
  */
1049
- export type ToolRouterSessionConfigHistoryConfig = Omit<
1050
- SessionConfigHistoryResponse.Item.Config,
1051
- 'premium_usage'
1052
- > & {
1053
- instant?: false | ToolRouterInstantResponse;
1054
- };
1040
+ export type ToolRouterSessionConfigHistoryConfig = SessionConfigHistoryResponse.Item.Config;
1055
1041
 
1056
1042
  export type ToolRouterSessionConfigHistoryItem = {
1057
1043
  /** The config version this entry represents. */
@@ -6,6 +6,9 @@ import { isPlainObject } from './modifiers/FileToolModifier.utils.neutral';
6
6
 
7
7
  const MAX_REF_CHAIN_DEPTH = 100;
8
8
  const MAX_NODE_DEPTH = 512;
9
+ // Bounds on one null-acceptance check; past either, null is not proven accepted.
10
+ const MAX_NULL_CHECK_DEPTH = 64;
11
+ const MAX_NULL_CHECK_NODES = 2_000;
9
12
  const CYCLE_BREAK_SENTINEL = { type: 'object', additionalProperties: true } as const;
10
13
 
11
14
  /** Keywords whose value is a single subschema. */
@@ -603,27 +606,44 @@ function setOwn(target: Record<string, unknown>, key: string, value: unknown): v
603
606
  }
604
607
 
605
608
  /**
606
- * Widens a property schema so that `null` is an accepted value, without
607
- * placing `type` beside `anyOf` (the API rejects that combination).
609
+ * The only keywords that can reject a `null` instance; every other keyword
610
+ * constrains strings, numbers, arrays or objects and ignores `null`.
608
611
  */
609
- function widenToNullable(node: Record<string, unknown>): Record<string, unknown> {
610
- if (Array.isArray(node.anyOf)) {
611
- const alreadyNullable = node.anyOf.some(
612
- branch => isPlainObject(branch) && branch.type === 'null'
613
- );
614
- return alreadyNullable ? node : { ...node, anyOf: [...node.anyOf, { type: 'null' }] };
615
- }
616
- if (typeof node.type === 'string') {
617
- return node.type === 'null' ? node : { ...node, type: [node.type, 'null'] };
612
+ const NULL_CONSTRAINT_KEYWORDS = [
613
+ 'type',
614
+ 'enum',
615
+ 'const',
616
+ '$ref',
617
+ 'anyOf',
618
+ 'oneOf',
619
+ 'allOf',
620
+ 'not',
621
+ 'if',
622
+ 'then',
623
+ 'else',
624
+ ] as const;
625
+
626
+ /**
627
+ * Widens a property schema so that `null` is an accepted value while keeping
628
+ * every other constraint it declares. A node whose only obstacle is `type` or
629
+ * `anyOf` is widened in place. Anything else is wrapped whole, because JSON
630
+ * Schema keywords apply together: adding `null` to `type` does not lift a
631
+ * sibling `enum`. `acceptsNull` must answer for the strict output.
632
+ */
633
+ function widenToNullable(
634
+ node: Record<string, unknown>,
635
+ acceptsNull: (schema: unknown) => boolean
636
+ ): Record<string, unknown> {
637
+ if (acceptsNull(node)) return node;
638
+ const constraints = NULL_CONSTRAINT_KEYWORDS.filter(key => key in node);
639
+ if (constraints.length === 1 && constraints[0] === 'type') {
640
+ const members = Array.isArray(node.type) ? node.type : [node.type];
641
+ return { ...node, type: [...members, 'null'] };
618
642
  }
619
- if (Array.isArray(node.type)) {
620
- return node.type.includes('null') ? node : { ...node, type: [...node.type, 'null'] };
643
+ if (constraints.length === 1 && constraints[0] === 'anyOf' && Array.isArray(node.anyOf)) {
644
+ return { ...node, anyOf: [...node.anyOf, { type: 'null' }] };
621
645
  }
622
- if ((Array.isArray(node.enum) && node.enum.includes(null)) || node.const === null) return node;
623
- // No `type` at all: an empty schema already accepts null; anything else
624
- // (enum-only, const, composition) is wrapped so the annotation stays outside.
625
646
  const { description, title, ...rest } = node;
626
- if (Object.keys(rest).length === 0) return node;
627
647
  return {
628
648
  ...(description !== undefined ? { description } : {}),
629
649
  ...(title !== undefined ? { title } : {}),
@@ -646,19 +666,136 @@ function resolveLocalRefs(node: unknown, root: Record<string, unknown>): unknown
646
666
  return current;
647
667
  }
648
668
 
649
- /** Whether a schema node accepts `null` as an instance. */
650
- function schemaAcceptsNull(schema: unknown, root: Record<string, unknown>): boolean {
651
- const node = resolveLocalRefs(schema, root);
652
- if (!isPlainObject(node)) return true;
653
- if (typeof node.type === 'string') return node.type === 'null';
654
- if (Array.isArray(node.type)) return node.type.includes('null');
655
- if (Array.isArray(node.enum)) return node.enum.includes(null);
656
- if ('const' in node) return node.const === null;
657
- for (const keyword of ['anyOf', 'oneOf']) {
658
- const branches = node[keyword];
659
- if (Array.isArray(branches)) return branches.some(branch => schemaAcceptsNull(branch, root));
660
- }
661
- return true;
669
+ /**
670
+ * Creates the check for whether schemas of one document accept `null` as an
671
+ * instance: every keyword in `NULL_CONSTRAINT_KEYWORDS` that is present must
672
+ * accept it. This is the single definition of null acceptance; the strict
673
+ * rewrite and `omitNullToolArguments` both decide with it.
674
+ *
675
+ * `strictOutput` answers for the schema `toStrictJsonSchema` emits instead of
676
+ * the one it was given: the rewrite types every node that declares
677
+ * `properties` as an object, so such a node stops accepting null.
678
+ *
679
+ * One check serves a whole document, and an answer is computed once per node.
680
+ * A reference cycle never yields a null by itself, so a node met again while
681
+ * it is being evaluated counts as rejecting. An answer that leans on that is
682
+ * provisional until the node it leans on is done: it is kept if that node
683
+ * does reject null and discarded otherwise.
684
+ *
685
+ * Each check is bounded in depth and in nodes visited. A check that meets a
686
+ * bound proves nothing, so it rejects null whatever its other branches say,
687
+ * which costs at most a redundant null branch or a dropped null. The nodes it
688
+ * went through stay marked as unproven, so a later check that reaches one of
689
+ * them neither repeats the work nor trusts the answer.
690
+ */
691
+ function createNullCheck(
692
+ root: Record<string, unknown>,
693
+ strictOutput = false
694
+ ): (schema: unknown) => boolean {
695
+ // Markers for what an answer leans on, besides the depth of a node on the path.
696
+ const NOTHING = MAX_NULL_CHECK_DEPTH + 1;
697
+ const A_BOUND = -1;
698
+ const answers = new Map<object, { answer: boolean; leansOn: number }>();
699
+ // Nodes whose answer is provisional, oldest first.
700
+ const provisional: object[] = [];
701
+ // Nodes being evaluated, mapped to their depth on the current path.
702
+ const path = new Map<object, number>();
703
+ // Depths of the path nodes that were met again below themselves.
704
+ const metAgain = new Set<number>();
705
+ let budget = 0;
706
+ // Shallowest thing the answers used since the last reset lean on.
707
+ let leansOn = NOTHING;
708
+
709
+ const accepts = (schema: unknown): boolean => {
710
+ if (typeof schema === 'boolean') return schema;
711
+ if (!isPlainObject(schema)) return true;
712
+ const remembered = answers.get(schema);
713
+ if (remembered !== undefined) {
714
+ if (path.size === 0) return remembered.answer && remembered.leansOn !== A_BOUND;
715
+ leansOn = Math.min(leansOn, remembered.leansOn);
716
+ return remembered.answer;
717
+ }
718
+ const onPath = path.get(schema);
719
+ if (onPath !== undefined) {
720
+ metAgain.add(onPath);
721
+ leansOn = Math.min(leansOn, onPath);
722
+ return false;
723
+ }
724
+ const depth = path.size;
725
+ if (depth === 0) budget = MAX_NULL_CHECK_NODES;
726
+ if (depth >= MAX_NULL_CHECK_DEPTH || budget <= 0) {
727
+ leansOn = A_BOUND;
728
+ return false;
729
+ }
730
+ budget -= 1;
731
+
732
+ const outer = leansOn;
733
+ leansOn = NOTHING;
734
+ const mark = provisional.length;
735
+ path.set(schema, depth);
736
+ let answer = keywordsAccept(schema);
737
+ path.delete(schema);
738
+
739
+ const own = leansOn;
740
+ const settled = own >= depth;
741
+ const below = provisional.splice(mark);
742
+ if (answer && metAgain.has(depth)) {
743
+ // The answers below took this node for rejecting null.
744
+ for (const other of below) answers.delete(other);
745
+ } else {
746
+ for (const other of below) {
747
+ const entry = answers.get(other);
748
+ if (entry === undefined) continue;
749
+ if (settled) {
750
+ entry.leansOn = NOTHING;
751
+ } else {
752
+ if (entry.leansOn >= depth) entry.leansOn = own;
753
+ provisional.push(other);
754
+ }
755
+ }
756
+ }
757
+ metAgain.delete(depth);
758
+
759
+ if (depth === 0 && own === A_BOUND) answer = false;
760
+ answers.set(schema, { answer, leansOn: settled ? NOTHING : own });
761
+ if (!settled) provisional.push(schema);
762
+ leansOn = settled ? outer : Math.min(outer, own);
763
+ if (depth === 0) {
764
+ // Whatever is still provisional leans on a bound, and stays so.
765
+ provisional.length = 0;
766
+ leansOn = NOTHING;
767
+ }
768
+ return answer;
769
+ };
770
+
771
+ const keywordsAccept = (node: Record<string, unknown>): boolean => {
772
+ if (typeof node.type === 'string' && node.type !== 'null') return false;
773
+ if (Array.isArray(node.type) && !node.type.includes('null')) return false;
774
+ if (strictOutput && !('type' in node) && isPlainObject(node.properties)) return false;
775
+ if (Array.isArray(node.enum) && !node.enum.includes(null)) return false;
776
+ if ('const' in node && node.const !== null) return false;
777
+ if ('$ref' in node) {
778
+ const resolution =
779
+ typeof node.$ref === 'string' ? tryResolvePointer(root, node.$ref) : undefined;
780
+ if (resolution === undefined || resolution.kind === 'unresolved') return false;
781
+ if (!accepts(resolution.value)) return false;
782
+ }
783
+ if (Array.isArray(node.anyOf) && !node.anyOf.some(accepts)) return false;
784
+ if (Array.isArray(node.oneOf)) {
785
+ const matches = node.oneOf.filter(accepts).length;
786
+ // The strict rewrite turns oneOf into anyOf.
787
+ if (matches === 0 || (matches > 1 && !strictOutput)) return false;
788
+ }
789
+ if (Array.isArray(node.allOf) && !node.allOf.every(accepts)) return false;
790
+ if ('not' in node && accepts(node.not)) return false;
791
+ if ('if' in node) {
792
+ const branch = accepts(node.if) ? 'then' : 'else';
793
+ if (branch in node && !accepts(node[branch])) return false;
794
+ }
795
+ return true;
796
+ };
797
+
798
+ return accepts;
662
799
  }
663
800
 
664
801
  /**
@@ -694,6 +831,8 @@ function schemaAcceptsNull(schema: unknown, root: Record<string, unknown>): bool
694
831
  export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
695
832
  const changes: StrictSchemaChange[] = [];
696
833
  const unsupported: StrictSchemaIncompatibility[] = [];
834
+ // Resolved references, re-checked against the rewritten schema.
835
+ const references: { path: string; ref: string }[] = [];
697
836
  let totalChanges = 0;
698
837
  const recordChange = (change: StrictSchemaChange): void => {
699
838
  totalChanges += 1;
@@ -701,6 +840,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
701
840
  };
702
841
 
703
842
  const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
843
+ const acceptsNullInOutput = createNullCheck(root, true);
704
844
 
705
845
  function walkChildren(
706
846
  node: Record<string, unknown>,
@@ -805,6 +945,8 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
805
945
  keyword: '$ref',
806
946
  detail: `unresolved $ref "${node.$ref}"`,
807
947
  });
948
+ } else {
949
+ references.push({ path, ref: node.$ref });
808
950
  }
809
951
  // The referenced definition is normalized where it is declared.
810
952
  return out;
@@ -834,7 +976,7 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
834
976
  continue;
835
977
  }
836
978
  if (declaredRequired.has(name) || !isPlainObject(propertySchema)) continue;
837
- setOwn(properties, name, widenToNullable(propertySchema));
979
+ setOwn(properties, name, widenToNullable(propertySchema, acceptsNullInOutput));
838
980
  recordChange({
839
981
  path: joinPath(path, `properties.${name}`),
840
982
  reason: 'optional-property-nullable',
@@ -874,6 +1016,18 @@ export function toStrictJsonSchema(schema: unknown): StrictJsonSchemaResult {
874
1016
  }
875
1017
 
876
1018
  const normalized = walk(root, 'schema', 0, '');
1019
+ if (isPlainObject(normalized)) {
1020
+ // Wrapping a property in a null branch moves everything nested in it.
1021
+ for (const { path, ref } of references) {
1022
+ if (tryResolvePointer(normalized, ref).kind === 'unresolved') {
1023
+ unsupported.push({
1024
+ path,
1025
+ keyword: '$ref',
1026
+ detail: `$ref "${ref}" target moved by the rewrite`,
1027
+ });
1028
+ }
1029
+ }
1030
+ }
877
1031
  if (!isPlainObject(normalized) || !isObjectType(normalized.type)) {
878
1032
  unsupported.push({
879
1033
  path: '',
@@ -912,7 +1066,7 @@ export function omitNullToolArguments(
912
1066
  schema: unknown
913
1067
  ): Record<string, unknown> {
914
1068
  const root: Record<string, unknown> = isPlainObject(schema) ? schema : {};
915
- return omitNulls(args, root, root, 0) as Record<string, unknown>;
1069
+ return omitNulls(args, root, root, 0, createNullCheck(root)) as Record<string, unknown>;
916
1070
  }
917
1071
 
918
1072
  /**
@@ -949,7 +1103,8 @@ function omitNulls(
949
1103
  value: unknown,
950
1104
  schema: unknown,
951
1105
  root: Record<string, unknown>,
952
- depth: number
1106
+ depth: number,
1107
+ acceptsNull: (schema: unknown) => boolean
953
1108
  ): unknown {
954
1109
  if (depth > MAX_NODE_DEPTH) {
955
1110
  throw new RangeError(`Tool arguments exceed maximum nesting depth of ${MAX_NODE_DEPTH}`);
@@ -957,7 +1112,7 @@ function omitNulls(
957
1112
  const node = selectBranchFor(schema, value, root);
958
1113
  if (Array.isArray(value)) {
959
1114
  const items = node && isPlainObject(node.items) ? node.items : undefined;
960
- return value.map(item => omitNulls(item, items, root, depth + 1));
1115
+ return value.map(item => omitNulls(item, items, root, depth + 1, acceptsNull));
961
1116
  }
962
1117
  if (!isPlainObject(value)) return value;
963
1118
 
@@ -968,12 +1123,12 @@ function omitNulls(
968
1123
  ? properties[key]
969
1124
  : undefined;
970
1125
  if (child === null) {
971
- if (propertySchema === undefined || schemaAcceptsNull(propertySchema, root)) {
1126
+ if (propertySchema === undefined || acceptsNull(propertySchema)) {
972
1127
  setOwn(clone, key, child);
973
1128
  }
974
1129
  continue;
975
1130
  }
976
- setOwn(clone, key, omitNulls(child, propertySchema, root, depth + 1));
1131
+ setOwn(clone, key, omitNulls(child, propertySchema, root, depth + 1, acceptsNull));
977
1132
  }
978
1133
  return clone;
979
1134
  }
@@ -0,0 +1,20 @@
1
+ import type { ComposioRequestOptions } from '../types/requestOptions.types';
2
+
3
+ /**
4
+ * Request options for a call that executes a tool or proxies an API call: the
5
+ * caller's options with retries disabled.
6
+ *
7
+ * These calls are non-idempotent writes. The client retries timeouts,
8
+ * connection errors, and 408/409/429/5xx responses by default, and a retry
9
+ * after the backend already acted duplicates the side effect (e.g. sends the
10
+ * same email twice). The backend does not deduplicate executions, so every
11
+ * execution path must go through this helper. Reads keep the default retries.
12
+ * See https://github.com/ComposioHQ/composio/issues/3654.
13
+ *
14
+ * @internal
15
+ */
16
+ export function withoutRetries(
17
+ requestOptions?: ComposioRequestOptions
18
+ ): ComposioRequestOptions & { maxRetries: 0 } {
19
+ return { ...requestOptions, maxRetries: 0 };
20
+ }