Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 121 lines 4.93 KB
Raw
1 import { isComposioError } from '@composio/client/effect';
2 import { Option, Predicate } from 'effect';
3 import type { ClientApiError } from 'src/services/composio-errors';
4 import { DashboardToolExecutionError } from 'src/services/dashboard-tool-execution';
5
6 /**
7 * The exit code of a failure that is safe to retry as it is: `EX_TEMPFAIL` from `sysexits.h`
8 * ("a temporary failure; the user is invited to retry"). Every other failure exits 1.
9 */
10 export const TEMPORARY_FAILURE_EXIT_CODE = 75;
11
12 /**
13 * What a caller can do after a request failed:
14 *
15 * - `safe`: run the same command again. The request did not take effect (the API refused it with
16 * a 429), or it failed in a way that may pass on a later attempt and repeating it cannot repeat
17 * a side effect (its method is idempotent).
18 * - `check-first`: the request failed in flight and may have taken effect. Running the command
19 * again could repeat its side effect, so check whether it did first.
20 */
21 export type RetryAdvice = 'safe' | 'check-first';
22
23 /** The methods RFC 9110 defines as idempotent: repeating one has the effect of sending it once. */
24 const IDEMPOTENT_METHODS: ReadonlySet<string> = new Set([
25 'GET',
26 'HEAD',
27 'OPTIONS',
28 'TRACE',
29 'PUT',
30 'DELETE',
31 ]);
32
33 /** The transport failures the client refuses to retry: a redirect it will not follow. */
34 const PERMANENT_CONNECTION_REASONS: ReadonlySet<string> = new Set([
35 'OpaqueRedirect',
36 'TooManyRedirects',
37 ]);
38
39 const isClientApiError = (error: unknown): error is ClientApiError =>
40 isComposioError(error) && error._tag !== '@composio/client/ConfigurationError';
41
42 /**
43 * The failed request behind `error`: `error` itself, or the `cause` a command's error keeps (see
44 * `requestError`), a few levels deep.
45 */
46 const clientErrorOf = (error: unknown, depth = 0): Option.Option<ClientApiError> =>
47 isClientApiError(error)
48 ? Option.some(error)
49 : depth < 3 && Predicate.hasProperty(error, 'cause')
50 ? clientErrorOf(error.cause, depth + 1)
51 : Option.none();
52
53 /**
54 * Whether the request ended in a way a later attempt may not: the same conditions the client
55 * retries a call marked `idempotent` on (see `src/services/composio-request.ts`), less a 409.
56 */
57 const isTransient = (error: ClientApiError): boolean => {
58 switch (error._tag) {
59 case '@composio/client/APIConnectionTimeoutError':
60 return true;
61 case '@composio/client/APIConnectionError':
62 return !PERMANENT_CONNECTION_REASONS.has(error.reason);
63 case '@composio/client/RateLimitError':
64 case '@composio/client/InternalServerError':
65 return true;
66 case '@composio/client/APIError':
67 return error.status === 408;
68 default:
69 return false;
70 }
71 };
72
73 /**
74 * The advice for an execution the Dashboard transport sent (always once, as a `POST`): one that
75 * got no answer, or an answer it could not read, may have run the tool; a 429 did not.
76 */
77 const dashboardAdvice = (error: DashboardToolExecutionError): Option.Option<RetryAdvice> => {
78 if (error.status === 429) return Option.some('safe');
79 switch (error.reason) {
80 case 'request':
81 case 'timeout':
82 case 'response':
83 return Option.some('check-first');
84 case 'dashboard':
85 return error.status !== undefined && error.status >= 500
86 ? Option.some('check-first')
87 : Option.none();
88 default:
89 return Option.none();
90 }
91 };
92
93 /**
94 * The retry advice for a failed request, when there is one: none for a failure that would fail
95 * the same way again (a 4xx other than 408 and 429, a read whose response failed decoding,
96 * anything that is not a failed request).
97 */
98 export const retryAdviceFor = (error: unknown): Option.Option<RetryAdvice> => {
99 if (error instanceof DashboardToolExecutionError) return dashboardAdvice(error);
100 return Option.flatMap(clientErrorOf(error), clientError => {
101 const idempotent = IDEMPOTENT_METHODS.has(clientError.method.toUpperCase());
102 // A response that arrived but could not be read: the request ran, so repeating a read fails
103 // the same way, and repeating anything else may act twice.
104 if (clientError._tag === '@composio/client/DecodeError') {
105 return idempotent ? Option.none() : Option.some('check-first');
106 }
107 if (!isTransient(clientError)) return Option.none();
108 if (clientError._tag === '@composio/client/RateLimitError') return Option.some('safe');
109 return Option.some(idempotent ? 'safe' : 'check-first');
110 });
111 };
112
113 /** Whether `error` is a failed request the caller can run again as it is. */
114 export const isSafeToRetry = (error: unknown): boolean =>
115 Option.contains(retryAdviceFor(error), 'safe');
116
117 /** The line that tells the reader what to do about a failure with `advice`. */
118 export const retryHint = (advice: RetryAdvice): string =>
119 advice === 'safe'
120 ? 'This failure is temporary, and repeating the request cannot make a change twice: run the same command again in a moment.'
121 : 'The request may have taken effect before it failed. Check whether it did before you run the command again, or it may happen twice.';