@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 122 lines 4.92 KB
Raw
1 import { isAPIError } from '@composio/client/effect';
2 import { Effect, Option } from 'effect';
3 import type { ClientApiError } from 'src/services/composio-errors';
4 import type { TerminalUI } from 'src/services/terminal-ui';
5 import { reportFailure, type ReportedFailure } from 'src/effects/report-failure';
6 import { describeDecodeError, isClientDecodeError } from 'src/utils/api-error-extraction';
7 import { isUnauthorized, unauthorizedHint } from 'src/effects/rejected-user-api-key';
8 import { isSafeToRetry, retryHint } from 'src/effects/retry-advice';
9
10 export interface Suggestion {
11 readonly label: string;
12 readonly command: string;
13 }
14
15 const noSuggestions: ReadonlyArray<Suggestion> = [];
16
17 export interface HandleClientApiErrorOptions {
18 readonly fallbackMessage: string;
19 readonly hint: string;
20 readonly searchForSuggestions?: () => Effect.Effect<ReadonlyArray<Suggestion>, unknown, never>;
21 }
22
23 interface ErrorReport {
24 readonly message?: string;
25 readonly suggestedFix?: string;
26 // Set when the failure has its own remedy, which replaces the caller's hint.
27 readonly hint?: string;
28 // Set when running the same command again is safe and may pass.
29 readonly retryable?: boolean;
30 }
31
32 const reportOf = (e: ClientApiError): Effect.Effect<ErrorReport> => {
33 if (isClientDecodeError(e)) return Effect.succeed(describeDecodeError(e));
34 // A temporary failure's remedy is to run the command again, whatever the caller's hint says.
35 if (isSafeToRetry(e)) {
36 const message = isAPIError(e) ? e.details?.message : undefined;
37 return Effect.succeed({ message, hint: retryHint('safe'), retryable: true });
38 }
39 if (isAPIError(e)) {
40 const statusReport = { message: e.details?.message, suggestedFix: e.details?.suggested_fix };
41 return isUnauthorized(e)
42 ? Effect.map(
43 unauthorizedHint(e),
44 Option.match({
45 onNone: () => statusReport,
46 onSome: hint => ({ message: e.details?.message, hint }),
47 })
48 )
49 : Effect.succeed(statusReport);
50 }
51 return Effect.succeed({});
52 };
53
54 /**
55 * Create a handler for a client API error that logs the structured error
56 * details (or a fallback message) and a contextual hint, then fails.
57 *
58 * The final rendering is `reportFailure`'s (`src/effects/report-failure.ts`):
59 * the message and hint reach stderr as plain lines when it is not a TTY, and
60 * the handler fails with a `ReportedFailure`, so the process exits 1 and
61 * callers such as scripts and agents can detect the failure. A failure that is
62 * safe to run again as it is (see `src/effects/retry-advice.ts`) says so in
63 * place of the hint and exits 75. The handler never
64 * succeeds, so the recovered effect keeps the request's own success type and
65 * the caller reads the result straight through.
66 *
67 * Used by info/delete/create commands that share the same error-handling shape.
68 *
69 * When `searchForSuggestions` is provided, the handler will attempt to find
70 * similar items and display "Did you mean?" suggestions instead of the generic hint.
71 * Suggestion search failures are silently swallowed.
72 *
73 * A response that failed client decoding is reported by operation and request
74 * id with an upgrade hint, in place of the fallback message and the hint.
75 *
76 * Recover from every client API error (a non-success status, a connection
77 * failure, a timeout, or a response that failed decoding) with
78 * `Effect.catchTag(CLIENT_API_ERROR_TAGS, ...)`; every other failure passes
79 * through. A single tag narrows the recovery to that status.
80 *
81 * @example
82 * ```ts
83 * .pipe(
84 * Effect.catchTag(CLIENT_API_ERROR_TAGS,
85 * handleClientApiError(ui, {
86 * fallbackMessage: `Failed to fetch auth config "${id}".`,
87 * hint: 'Browse available auth configs:\n> composio dev auth-configs list',
88 * })
89 * )
90 * )
91 * ```
92 */
93 export const handleClientApiError =
94 (ui: TerminalUI, opts: HandleClientApiErrorOptions) =>
95 (e: ClientApiError): Effect.Effect<never, ReportedFailure> =>
96 Effect.gen(function* () {
97 const report = yield* reportOf(e);
98 const message = report.message ?? opts.fallbackMessage;
99 const hint = report.hint ?? opts.hint;
100 // The API's own suggested fix comes first, then the caller's hint — or the
101 // "Did you mean?" suggestions that replace it.
102 const withHint = (suffix: string) =>
103 report.suggestedFix === undefined ? suffix : `${report.suggestedFix}\n\n${suffix}`;
104
105 if (opts.searchForSuggestions && report.hint === undefined) {
106 const suggestions = yield* opts
107 .searchForSuggestions()
108 .pipe(Effect.catch(() => Effect.succeed(noSuggestions)));
109
110 const [first] = suggestions;
111 if (first) {
112 const lines = suggestions.map(s => ` ${s.label}`).join('\n');
113 return yield* reportFailure(
114 ui,
115 message,
116 withHint(`Did you mean?\n${lines}\n\n${first.command}`)
117 );
118 }
119 }
120
121 return yield* reportFailure(ui, message, withHint(hint), { retryable: report.retryable });
122 });