@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, 06:00 UTC

next
ts 236 lines 9.64 KB
Raw
1 import { Array as Arr, Effect, Option } from 'effect';
2 import type { CommandTree } from 'src/commands/surface';
3 import { AUTHORIZATION_TIMEOUT_MINUTES } from 'src/effects/authorization-poll';
4 import { BROWSE_TOOLKITS_HINT } from 'src/commands/toolkits/format';
5 import { printFailure, ReportedFailure } from 'src/effects/report-failure';
6 import type { ConnectedAccountItem } from 'src/models/connected-accounts';
7 import type { CliProjectType } from 'src/services/command-project';
8 import type { TerminalUI } from 'src/services/terminal-ui';
9 import { formatConnectedAccountsTable } from '../format';
10
11 /** A connected account as the link flows label it: id first, alias and word id when set. */
12 export interface ExistingAccountLabel {
13 readonly id: string;
14 readonly alias?: string | null;
15 readonly word_id?: string | null;
16 }
17
18 /** A link the API created: the account it belongs to and the page that authorizes it. */
19 export interface LinkTarget {
20 readonly connectedAccountId: string;
21 readonly redirectUrl: string;
22 }
23
24 // --- usage messages the parser cannot produce; printed on stderr --------------------------
25
26 export const ROOT_AUTH_CONFIG_MESSAGE =
27 "`composio link` does not accept `--auth-config`. To link through a developer project's auth config, run `composio dev connected-accounts link --auth-config <id>`.";
28
29 export const TOOLKIT_AND_AUTH_CONFIG_MESSAGE =
30 'Pass a toolkit or `--auth-config`, not both.\n' +
31 ' Tool Router: composio dev connected-accounts link <toolkit>\n' +
32 ' Legacy: composio dev connected-accounts link --auth-config <id>';
33
34 export const missingArgumentMessage = (tree: CommandTree) =>
35 tree === 'root'
36 ? 'Pass the toolkit to link.\n composio link github'
37 : 'Pass the toolkit to link, or `--auth-config`.\n' +
38 ' composio dev connected-accounts link github\n' +
39 ' composio dev connected-accounts link --auth-config <id>';
40
41 export const LIST_REQUIRES_TOOLKIT_MESSAGE =
42 '`--list` needs a toolkit, for example `composio link gmail --list`.';
43
44 export const LIST_WITH_AUTH_CONFIG_MESSAGE = '`--list` cannot be combined with `--auth-config`.';
45
46 export const AUTH_CONFIG_SCOPE_MESSAGE =
47 '`--auth-config` needs a developer project. Pass `--project-name <name>`, or run the command in a directory set up with `composio dev init`.';
48
49 export const INCOMPLETE_LINK_RESPONSE_MESSAGE =
50 'The link response from the API is missing `connected_account_id` or `redirect_url`.';
51
52 // The canonical constant lives with the other toolkit formatters; re-exported here for the
53 // link flow's callers.
54 export { BROWSE_TOOLKITS_HINT };
55
56 export const BROWSE_AUTH_CONFIGS_HINT =
57 'Browse available auth configs:\n> composio dev auth-configs list';
58
59 // --- human renderers (stderr) ---------------------------------------------------------------
60
61 /**
62 * What a command that waits for an authorization writes when stderr is not a terminal: the
63 * step line and the note are decoration and would be dropped, and the URL with them, leaving
64 * an agent nothing to show the person it waits for.
65 */
66 export const formatNonInteractiveAuthorizationInstructions = (
67 redirectUrl: string
68 ) => `Open this URL in your browser to authorize the connection:
69
70 ${redirectUrl}
71
72 hint: For agents: Show the URL above to the user to open. This command waits up to ${AUTHORIZATION_TIMEOUT_MINUTES} minutes for the authorization, then prints the connected account as JSON if stdout is redirected. To return right away with the URL instead, run the same command with --no-wait.`;
73
74 /**
75 * Points the user at the authorization page: a step line and the URL as a note. `manual` is
76 * for a page the CLI does not open itself; `waiting` is for a command that then waits for the
77 * authorization. Off a terminal, a waiting command writes the URL with plain instructions
78 * instead, since nothing else would show it; one that does not wait prints it on stdout.
79 */
80 export const showRedirectUrl = (
81 ui: TerminalUI,
82 redirectUrl: string,
83 options: { readonly manual: boolean; readonly waiting: boolean }
84 ) =>
85 Effect.gen(function* () {
86 const { canDecorate } = yield* ui.capabilities;
87 if (!canDecorate) {
88 if (options.waiting) {
89 yield* ui.error(formatNonInteractiveAuthorizationInstructions(redirectUrl));
90 }
91 return;
92 }
93 yield* ui.log.step(
94 options.manual
95 ? 'Open this URL in your browser to authorize'
96 : 'Redirecting you to the authorization page'
97 );
98 yield* ui.note(redirectUrl, 'Redirect URL');
99 });
100
101 /** `id (alias, word_id)` per account, comma separated. An account without labels is its id. */
102 const formatExistingAccountLabels = (items: ReadonlyArray<ExistingAccountLabel>) =>
103 items
104 .map(item =>
105 Arr.match(
106 [item.alias, item.word_id].filter(
107 (value): value is string => typeof value === 'string' && value.trim().length > 0
108 ),
109 {
110 onEmpty: () => item.id,
111 onNonEmpty: labels => `${item.id} (${labels.join(', ')})`,
112 }
113 )
114 )
115 .join(', ');
116
117 /**
118 * Why a second account needs `--alias` (exit 1), and which accounts already exist for the scope.
119 */
120 export const showExistingAccounts = (
121 ui: TerminalUI,
122 scopeDescription: string,
123 items: ReadonlyArray<ExistingAccountLabel>
124 ) =>
125 Effect.gen(function* () {
126 const message = `A connected account already exists for ${scopeDescription}. Pass --alias to create another one.`;
127 yield* printFailure(ui, message);
128 yield* ui.note(formatExistingAccountLabels(items), 'Existing accounts');
129 return yield* new ReportedFailure({ message });
130 });
131
132 /**
133 * The alias is taken (exit 1): which account holds it, and how to use that account or list them
134 * all. The hint commands differ per tree, so the caller passes them.
135 */
136 export const showAliasConflict = (
137 ui: TerminalUI,
138 params: {
139 readonly alias: string;
140 readonly existingId: string;
141 readonly executeCommand: string;
142 readonly listCommand: string;
143 }
144 ) =>
145 Effect.gen(function* () {
146 const message = `Alias "${params.alias}" is already in use by connected account "${params.existingId}".`;
147 yield* printFailure(ui, message);
148 yield* ui.note(
149 [
150 `Use the existing alias: ${params.executeCommand} <TOOL_SLUG> --account ${params.alias} -d '{ ... }'`,
151 `List connected accounts: ${params.listCommand}`,
152 ].join('\n'),
153 'Tips'
154 );
155 return yield* new ReportedFailure({ message });
156 });
157
158 /** The table of a toolkit's active accounts as a note, or a warning when there are none. */
159 export const showConnectedAccounts = (
160 ui: TerminalUI,
161 toolkitSlug: string,
162 items: ReadonlyArray<ConnectedAccountItem>
163 ) =>
164 Arr.match(items, {
165 onEmpty: () => ui.log.warn(`No active connected accounts found for "${toolkitSlug}".`),
166 onNonEmpty: accounts =>
167 ui.note(formatConnectedAccountsTable(accounts), `${toolkitSlug}: connected accounts`),
168 });
169
170 /**
171 * The dashboard page that connects a toolkit Composio does not manage auth for. Path segments
172 * are encoded so an org name with spaces or `@` does not bake `?open=true` into the path.
173 */
174 export const dashboardConnectUrl = (webURL: string, orgName: string, toolkitSlug: string) =>
175 `${webURL.replace(/\/+$/, '')}/${encodeURIComponent(orgName)}/~/connect/apps/${encodeURIComponent(toolkitSlug)}?open=true`;
176
177 /** The warning that precedes the dashboard URL when Composio does not manage a toolkit's auth. */
178 export const unmanagedAuthMessage = (toolkitSlug: string, noBrowser: boolean) =>
179 `Composio does not manage auth for "${toolkitSlug}". ${noBrowser ? 'Open the dashboard to connect it there.' : 'Opening the dashboard to connect it there.'}`;
180
181 /** The success line once polling sees the account `ACTIVE`. Also the `message` of its payload. */
182 export const activeConnectionMessage = (account: {
183 readonly id: string;
184 readonly toolkit: { readonly slug: string };
185 }) => `Connected account "${account.id}" is now ACTIVE (toolkit: ${account.toolkit.slug}).`;
186
187 // --- machine renderers (stdout) ---------------------------------------------------------------
188
189 /**
190 * A payload as `link` prints it on stdout: indented by two spaces, without a trailing newline,
191 * since `ui.output` adds one. Key order is part of the output.
192 */
193 const toStdoutJson = (payload: object) => JSON.stringify(payload, null, 2);
194
195 /** The `--no-wait` payload: the link to finish by hand. `toolkit` is set by the Tool Router flow. */
196 export const formatPendingLinkJson = (params: {
197 readonly target: LinkTarget;
198 readonly toolkit: Option.Option<string>;
199 readonly projectType: CliProjectType;
200 }) =>
201 toStdoutJson({
202 status: 'pending',
203 message: 'Complete authorization by opening the URL',
204 connected_account_id: params.target.connectedAccountId,
205 redirect_url: params.target.redirectUrl,
206 ...Option.match(params.toolkit, { onNone: () => ({}), onSome: toolkit => ({ toolkit }) }),
207 project_type: params.projectType,
208 });
209
210 /** The payload once the account is `ACTIVE`. */
211 export const formatActiveLinkJson = (params: {
212 readonly account: { readonly id: string; readonly toolkit: { readonly slug: string } };
213 readonly redirectUrl: string;
214 }) =>
215 toStdoutJson({
216 status: 'success',
217 message: activeConnectionMessage(params.account),
218 connected_account_id: params.account.id,
219 toolkit: params.account.toolkit.slug,
220 redirect_url: params.redirectUrl,
221 });
222
223 /**
224 * The `--list` payload: the toolkit's active accounts, schema-filtered upstream. The empty case
225 * lists `items` before `total`, the other case after.
226 */
227 export const formatConnectedAccountsListJson = (
228 toolkitSlug: string,
229 items: ReadonlyArray<ConnectedAccountItem>
230 ) =>
231 toStdoutJson(
232 Arr.match(items, {
233 onEmpty: () => ({ toolkit: toolkitSlug, items: [], total: 0 }),
234 onNonEmpty: accounts => ({ toolkit: toolkitSlug, total: accounts.length, items: accounts }),
235 })
236 );