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
| 1 | import { isAPIError } from '@composio/client/effect'; |
| 2 | import { Command as CliCommand, Flag } from 'effect/cli'; |
| 3 | import { Effect, Option } from 'effect'; |
| 4 | import * as FileSystem from 'effect/FileSystem'; |
| 5 | import * as Path from 'effect/Path'; |
| 6 | import { ComposioUserContext } from 'src/services/user-context'; |
| 7 | import { NodeProcess } from 'src/services/node-process'; |
| 8 | import { projectKeysToJSON, type ProjectKeys } from 'src/models/project-keys'; |
| 9 | import { userDataFromJSON } from 'src/models/user-data'; |
| 10 | import { |
| 11 | createProjectApiKey, |
| 12 | getSessionInfo, |
| 13 | listOrgProjects, |
| 14 | sessionProjectApiKeyOf, |
| 15 | sessionUserIdOf, |
| 16 | type OrgProject, |
| 17 | } from 'src/services/composio-account'; |
| 18 | import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch'; |
| 19 | import * as constants from 'src/constants'; |
| 20 | import { TerminalUI } from 'src/services/terminal-ui'; |
| 21 | import { browserLogin } from 'src/effects/browser-login'; |
| 22 | import { setupCacheDir } from 'src/effects/setup-cache-dir'; |
| 23 | import { CLIENT_API_ERROR_TAGS } from 'src/services/composio-errors'; |
| 24 | import { commandInputError } from 'src/commands/errors'; |
| 25 | import { printFailure, ReportedFailure } from 'src/effects/report-failure'; |
| 26 | import { |
| 27 | describeDecodeError, |
| 28 | isClientConnectionError, |
| 29 | isClientDecodeError, |
| 30 | type ClientApiError, |
| 31 | } from 'src/utils/api-error-extraction'; |
| 32 | |
| 33 | /** |
| 34 | * `composio init` — Initialize a developer project in the current directory. |
| 35 | * |
| 36 | * ## Behavior |
| 37 | * |
| 38 | * 1. **Project selection** — fetches projects from the API and prompts for selection. |
| 39 | * 2. **Writes config** — saves `<cwd>/.composio/project.json`. |
| 40 | * |
| 41 | * ## Flags |
| 42 | * |
| 43 | * - `--yes` / `-y` — auto-select the first project from the list |
| 44 | */ |
| 45 | |
| 46 | const noBrowserOpt = Flag.Boolean('no-browser').pipe( |
| 47 | Flag.withDefault(false), |
| 48 | Flag.withDescription('Login without browser interaction') |
| 49 | ); |
| 50 | |
| 51 | const yesOpt = Flag.Boolean('yes').pipe( |
| 52 | Flag.withAlias('y'), |
| 53 | Flag.withDefault(false), |
| 54 | Flag.withDescription('Auto-select the current org project, else first developer project') |
| 55 | ); |
| 56 | |
| 57 | // --------------------------------------------------------------------------- |
| 58 | // File I/O helpers |
| 59 | // --------------------------------------------------------------------------- |
| 60 | /** Writes project keys to `<cwd>/.composio/` and creates a `.gitignore`. */ |
| 61 | const writeProjectConfig = (composioDir: string, selected: ProjectKeys) => |
| 62 | Effect.gen(function* () { |
| 63 | const fs = yield* FileSystem.FileSystem; |
| 64 | const path = yield* Path.Path; |
| 65 | |
| 66 | yield* fs.makeDirectory(composioDir, { recursive: true }).pipe(Effect.catch(() => Effect.void)); |
| 67 | |
| 68 | const projectJson = yield* projectKeysToJSON(selected); |
| 69 | yield* fs.writeFileString( |
| 70 | path.join(composioDir, constants.PROJECT_CONFIG_FILE_NAME), |
| 71 | projectJson |
| 72 | ); |
| 73 | |
| 74 | // Create .composio/.gitignore to prevent accidental commits |
| 75 | const gitignorePath = path.join(composioDir, '.gitignore'); |
| 76 | const gitignoreExists = yield* fs.exists(gitignorePath); |
| 77 | if (!gitignoreExists) { |
| 78 | yield* fs.writeFileString(gitignorePath, '*\n'); |
| 79 | } |
| 80 | }); |
| 81 | |
| 82 | // --------------------------------------------------------------------------- |
| 83 | // Structured output helper |
| 84 | // --------------------------------------------------------------------------- |
| 85 | |
| 86 | const makeOutputJson = (selected: ProjectKeys, composioDir: string) => |
| 87 | JSON.stringify({ |
| 88 | org_id: selected.orgId, |
| 89 | project_id: selected.projectId, |
| 90 | path: composioDir, |
| 91 | }); |
| 92 | |
| 93 | const getGlobalUserApiKey = () => |
| 94 | Effect.gen(function* () { |
| 95 | const fs = yield* FileSystem.FileSystem; |
| 96 | const path = yield* Path.Path; |
| 97 | const cacheDir = yield* setupCacheDir; |
| 98 | const userConfigPath = path.join(cacheDir, constants.USER_CONFIG_FILE_NAME); |
| 99 | const exists = yield* fs.exists(userConfigPath); |
| 100 | if (!exists) return undefined; |
| 101 | |
| 102 | const userDataRaw = yield* fs.readFileString(userConfigPath, 'utf8'); |
| 103 | const parsed = yield* userDataFromJSON(userDataRaw).pipe(Effect.option); |
| 104 | if (Option.isNone(parsed)) return undefined; |
| 105 | |
| 106 | return Option.getOrUndefined(parsed.value.apiKey); |
| 107 | }); |
| 108 | |
| 109 | const upsertEnvVar = (content: string, key: string, value: string): string => { |
| 110 | const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| 111 | const line = `${key}=${value}`; |
| 112 | const pattern = new RegExp(`^${escapedKey}=.*$`, 'm'); |
| 113 | if (pattern.test(content)) { |
| 114 | return content.replace(pattern, line); |
| 115 | } |
| 116 | return content.trim().length ? `${content.trimEnd()}\n${line}\n` : `${line}\n`; |
| 117 | }; |
| 118 | |
| 119 | const ensureProjectApiKeyInEnv = (params: { cwd: string; selected: ProjectKeys }) => |
| 120 | Effect.gen(function* () { |
| 121 | const { cwd, selected } = params; |
| 122 | const ui = yield* TerminalUI; |
| 123 | const fs = yield* FileSystem.FileSystem; |
| 124 | const path = yield* Path.Path; |
| 125 | |
| 126 | const envPath = path.join(cwd, '.env.local'); |
| 127 | const envExists = yield* fs.exists(envPath); |
| 128 | const existingEnvContent = envExists ? yield* fs.readFileString(envPath, 'utf8') : ''; |
| 129 | const hasProjectApiKey = /^COMPOSIO_API_KEY=.*/m.test(existingEnvContent); |
| 130 | const hasTestUserId = /^COMPOSIO_TEST_USER_ID=.*/m.test(existingEnvContent); |
| 131 | |
| 132 | const uakApiKey = yield* getGlobalUserApiKey(); |
| 133 | if (!uakApiKey) { |
| 134 | yield* ui.log.warn('No global API key found; skipping .env.local creation.'); |
| 135 | return; |
| 136 | } |
| 137 | |
| 138 | const sessionInfo = yield* getSessionInfo({ |
| 139 | apiKey: uakApiKey, |
| 140 | orgId: selected.orgId, |
| 141 | projectId: selected.projectId, |
| 142 | }); |
| 143 | yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id, uakApiKey); |
| 144 | |
| 145 | let projectApiKey = sessionProjectApiKeyOf(sessionInfo); |
| 146 | if (!projectApiKey && !hasProjectApiKey) { |
| 147 | const dateSuffix = new Date().toISOString().slice(0, 10); |
| 148 | projectApiKey = yield* createProjectApiKey({ |
| 149 | apiKey: uakApiKey, |
| 150 | orgId: selected.orgId, |
| 151 | projectId: selected.projectId, |
| 152 | name: `composio-cli-${dateSuffix}`, |
| 153 | }); |
| 154 | } |
| 155 | |
| 156 | const sessionUserId = sessionUserIdOf(sessionInfo); |
| 157 | const composioTestUserId = `pg-test-${sessionUserId}`; |
| 158 | const composioDir = path.join(cwd, constants.PROJECT_COMPOSIO_DIR); |
| 159 | |
| 160 | let nextEnvContent = existingEnvContent; |
| 161 | if (!hasProjectApiKey && projectApiKey) { |
| 162 | nextEnvContent = upsertEnvVar(nextEnvContent, 'COMPOSIO_API_KEY', projectApiKey); |
| 163 | } |
| 164 | if (!hasTestUserId) { |
| 165 | nextEnvContent = upsertEnvVar(nextEnvContent, 'COMPOSIO_TEST_USER_ID', composioTestUserId); |
| 166 | } |
| 167 | |
| 168 | if (nextEnvContent !== existingEnvContent) { |
| 169 | yield* fs.writeFileString(envPath, nextEnvContent); |
| 170 | } |
| 171 | yield* writeProjectConfig(composioDir, { |
| 172 | ...selected, |
| 173 | testUserId: Option.some(composioTestUserId), |
| 174 | }); |
| 175 | if (nextEnvContent !== existingEnvContent) { |
| 176 | yield* ui.log.step( |
| 177 | envExists |
| 178 | ? 'Updated .env.local with Composio credentials' |
| 179 | : 'Created .env.local with Composio credentials' |
| 180 | ); |
| 181 | } |
| 182 | }); |
| 183 | |
| 184 | const logEnvCreationHttpError = (ui: TerminalUI) => (e: ClientApiError) => |
| 185 | Effect.gen(function* () { |
| 186 | yield* ui.log.warn('Could not create .env.local from session info.'); |
| 187 | if (isClientDecodeError(e)) { |
| 188 | const { message, hint } = describeDecodeError(e); |
| 189 | yield* ui.log.error(message); |
| 190 | yield* ui.log.step(hint); |
| 191 | return; |
| 192 | } |
| 193 | if (isAPIError(e)) { |
| 194 | yield* ui.log.error(`HTTP ${e.status}`); |
| 195 | if (e.details) { |
| 196 | yield* ui.log.error(e.details.message); |
| 197 | if (e.details.suggested_fix !== undefined) { |
| 198 | yield* ui.log.step(e.details.suggested_fix); |
| 199 | } |
| 200 | return; |
| 201 | } |
| 202 | } |
| 203 | // A connection failure names what the transport reported; every other |
| 204 | // failure keeps the line it had as a stringified error. |
| 205 | yield* ui.log.error( |
| 206 | isClientConnectionError(e) && e.description !== undefined |
| 207 | ? e.description |
| 208 | : `Error: ${e.message}` |
| 209 | ); |
| 210 | }); |
| 211 | |
| 212 | const logEnvCreationDecodingError = (ui: TerminalUI) => (e: { cause?: unknown }) => |
| 213 | Effect.gen(function* () { |
| 214 | yield* ui.log.warn('Could not decode API key response; skipping .env.local creation.'); |
| 215 | if (e.cause) { |
| 216 | yield* ui.log.error(String(e.cause)); |
| 217 | } |
| 218 | }); |
| 219 | |
| 220 | const selectDefaultProject = (params: { |
| 221 | projects: ReadonlyArray<OrgProject>; |
| 222 | defaultOrgId: string; |
| 223 | defaultProjectId?: string; |
| 224 | }): OrgProject | undefined => { |
| 225 | const { projects, defaultOrgId, defaultProjectId } = params; |
| 226 | const exactMatch = projects.find(p => p.org_id === defaultOrgId && p.id === defaultProjectId); |
| 227 | if (exactMatch) return exactMatch; |
| 228 | |
| 229 | const sameOrgFirst = projects.find(p => p.org_id === defaultOrgId); |
| 230 | if (sameOrgFirst) return sameOrgFirst; |
| 231 | |
| 232 | return projects[0]; |
| 233 | }; |
| 234 | |
| 235 | // --------------------------------------------------------------------------- |
| 236 | // Command |
| 237 | // --------------------------------------------------------------------------- |
| 238 | |
| 239 | /** |
| 240 | * CLI command to initialize a Composio project in the current directory. |
| 241 | * |
| 242 | * Creates `<cwd>/.composio/project.json` with org_id and project_id. |
| 243 | * Fetches projects from the API and prompts for selection. |
| 244 | * |
| 245 | * @example |
| 246 | * ```bash |
| 247 | * composio init |
| 248 | * composio init --yes |
| 249 | * ``` |
| 250 | */ |
| 251 | export const initCmd = CliCommand.make( |
| 252 | 'init', |
| 253 | { |
| 254 | noBrowser: noBrowserOpt, |
| 255 | yes: yesOpt, |
| 256 | }, |
| 257 | ({ noBrowser, yes }) => |
| 258 | Effect.gen(function* () { |
| 259 | const ui = yield* TerminalUI; |
| 260 | const proc = yield* NodeProcess; |
| 261 | const path = yield* Path.Path; |
| 262 | |
| 263 | yield* ui.intro('composio dev init'); |
| 264 | |
| 265 | const composioDir = path.join(proc.cwd, constants.PROJECT_COMPOSIO_DIR); |
| 266 | |
| 267 | yield* initInteractiveFlow({ composioDir, noBrowser, yes }); |
| 268 | }) |
| 269 | ).pipe(CliCommand.withDescription('Initialize this directory with a developer project.')); |
| 270 | |
| 271 | /** |
| 272 | * Interactive init flow — handles login, project selection, wizard, install. |
| 273 | * Extracted to keep the main command handler under the line limit. |
| 274 | */ |
| 275 | const initInteractiveFlow = (params: { composioDir: string; noBrowser: boolean; yes: boolean }) => |
| 276 | Effect.gen(function* () { |
| 277 | const { composioDir, noBrowser, yes } = params; |
| 278 | const ui = yield* TerminalUI; |
| 279 | const ctx = yield* ComposioUserContext; |
| 280 | const proc = yield* NodeProcess; |
| 281 | |
| 282 | // 1. Ensure global user API key exists (ignore local/project keys). |
| 283 | let globalApiKey = yield* getGlobalUserApiKey(); |
| 284 | if (!globalApiKey) { |
| 285 | yield* ui.log.step('No credentials found. Logging in...'); |
| 286 | yield* browserLogin({ scope: 'project', noBrowser }); |
| 287 | globalApiKey = yield* getGlobalUserApiKey(); |
| 288 | } |
| 289 | |
| 290 | // 2. Fetch projects |
| 291 | const orgIdValue = Option.getOrUndefined(ctx.data.orgId); |
| 292 | const projectIdValue = Option.getOrUndefined(ctx.data.projectId); |
| 293 | if (!globalApiKey || !orgIdValue) { |
| 294 | return yield* commandInputError('dev init')( |
| 295 | 'No global API key or org ID found. Please try `composio login` first.' |
| 296 | ); |
| 297 | } |
| 298 | |
| 299 | const orgProjects = yield* listOrgProjects({ |
| 300 | apiKey: globalApiKey, |
| 301 | orgId: orgIdValue, |
| 302 | }).pipe( |
| 303 | Effect.catchTag(CLIENT_API_ERROR_TAGS, e => |
| 304 | Effect.gen(function* () { |
| 305 | yield* Effect.logDebug('Failed to list org projects:', e); |
| 306 | yield* ui.log.warn('Could not fetch projects from the server.'); |
| 307 | yield* ui.log.info( |
| 308 | 'Create a project at https://platform.composio.dev, then run `composio dev init` again.' |
| 309 | ); |
| 310 | yield* ui.outro(''); |
| 311 | return yield* Effect.fail(e); |
| 312 | }) |
| 313 | ), |
| 314 | // Every other failure to reach the API gets the same guidance; only the |
| 315 | // wording differs by how far the request got. |
| 316 | Effect.catch(e => |
| 317 | Effect.gen(function* () { |
| 318 | yield* Effect.logDebug('Failed to fetch org projects:', e); |
| 319 | yield* ui.log.warn('Unexpected response from the server.'); |
| 320 | yield* ui.log.info( |
| 321 | 'Create a project at https://platform.composio.dev, then run `composio dev init` again.' |
| 322 | ); |
| 323 | yield* ui.outro(''); |
| 324 | return yield* Effect.fail(e); |
| 325 | }) |
| 326 | ) |
| 327 | ); |
| 328 | |
| 329 | if (orgProjects.data.length === 0) { |
| 330 | const message = 'No projects found for your organization.'; |
| 331 | yield* printFailure( |
| 332 | ui, |
| 333 | message, |
| 334 | 'Create a project at https://platform.composio.dev, then run `composio dev init` again.' |
| 335 | ); |
| 336 | yield* ui.outro(''); |
| 337 | return yield* new ReportedFailure({ message }); |
| 338 | } |
| 339 | |
| 340 | // 3. Select a developer project |
| 341 | const orgProjectToKeys = (p: OrgProject): ProjectKeys => ({ |
| 342 | orgId: p.org_id, |
| 343 | projectId: p.id, |
| 344 | projectName: Option.some(p.name), |
| 345 | orgName: Option.none(), |
| 346 | email: Option.some(p.email), |
| 347 | testUserId: Option.none(), |
| 348 | }); |
| 349 | |
| 350 | const skipProjectPicker = yes || orgProjects.data.length === 1; |
| 351 | const defaultProject = |
| 352 | selectDefaultProject({ |
| 353 | projects: orgProjects.data, |
| 354 | defaultOrgId: orgIdValue, |
| 355 | defaultProjectId: projectIdValue, |
| 356 | }) ?? orgProjects.data[0]; |
| 357 | const selectedProject: OrgProject = skipProjectPicker |
| 358 | ? defaultProject |
| 359 | : yield* ui.select<OrgProject>( |
| 360 | 'Select a developer project:', |
| 361 | orgProjects.data.map(p => ({ value: p, label: p.name, hint: p.id })) |
| 362 | ); |
| 363 | |
| 364 | const selected = orgProjectToKeys(selectedProject); |
| 365 | yield* ui.log.step(`Using developer project "${selectedProject.name}"`); |
| 366 | |
| 367 | // 4. Write project config |
| 368 | yield* writeProjectConfig(composioDir, selected); |
| 369 | yield* ensureProjectApiKeyInEnv({ cwd: proc.cwd, selected }).pipe( |
| 370 | Effect.catchTag(CLIENT_API_ERROR_TAGS, e => |
| 371 | Effect.gen(function* () { |
| 372 | yield* Effect.logDebug('Failed to resolve project API key from session/info:', e); |
| 373 | yield* logEnvCreationHttpError(ui)(e); |
| 374 | }) |
| 375 | ), |
| 376 | // The project is already written; a key the CLI could not resolve is a |
| 377 | // warning with manual instructions, never a failed init. |
| 378 | Effect.catch(e => |
| 379 | Effect.gen(function* () { |
| 380 | yield* Effect.logDebug('Failed to resolve the project API key:', e); |
| 381 | yield* logEnvCreationDecodingError(ui)(e); |
| 382 | }) |
| 383 | ) |
| 384 | ); |
| 385 | |
| 386 | yield* ui.log.success(`Project initialized in ${composioDir}/`); |
| 387 | yield* ui.log.info( |
| 388 | 'This directory will use the selected developer project for manage/listen flows.' |
| 389 | ); |
| 390 | yield* ui.output(makeOutputJson(selected, composioDir)); |
| 391 | yield* ui.outro(''); |
| 392 | }); |