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 { Data, Effect, Option, Predicate, Result } from 'effect'; |
| 3 | import { ExpectedFailure } from 'src/effects/expected-failure'; |
| 4 | import { extractMessage } from 'src/utils/api-error-extraction'; |
| 5 | import { ProjectContext } from './project-context'; |
| 6 | import { ComposioUserContext } from './user-context'; |
| 7 | import { |
| 8 | resolveConsumerProject, |
| 9 | findDeveloperProjectByName, |
| 10 | DeveloperProjectNotFoundError, |
| 11 | AmbiguousDeveloperProjectNameError, |
| 12 | getSessionInfoByUserApiKey, |
| 13 | userKeyBelongsToOrg, |
| 14 | } from './composio-account'; |
| 15 | |
| 16 | export type ProjectMode = 'consumer' | 'developer'; |
| 17 | |
| 18 | export type CliProjectType = 'CONSUMER' | 'DEVELOPER'; |
| 19 | |
| 20 | export type CliProjectResolutionSource = |
| 21 | | 'consumer-default' |
| 22 | | 'developer-project-name' |
| 23 | | 'developer-local-config' |
| 24 | | 'developer-explicit' |
| 25 | | 'developer-default'; |
| 26 | |
| 27 | export interface ResolvedCommandProject { |
| 28 | readonly orgId: string; |
| 29 | readonly projectId: string; |
| 30 | readonly projectName?: string; |
| 31 | readonly projectType: CliProjectType; |
| 32 | readonly consumerUserId?: string; |
| 33 | readonly source: CliProjectResolutionSource; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * The command's project could not be determined from the CLI's state and flags. The message |
| 38 | * names the command that fixes it; the invocation prints it as one line and exits 1. |
| 39 | */ |
| 40 | export class ProjectResolutionError extends Data.TaggedError('services/ProjectResolutionError')<{ |
| 41 | readonly reason: |
| 42 | | 'missing_org' |
| 43 | | 'missing_developer_project' |
| 44 | | 'project_not_found' |
| 45 | | 'ambiguous_project_name' |
| 46 | | 'org_mismatch' |
| 47 | | 'request_failed'; |
| 48 | readonly message: string; |
| 49 | readonly cause?: unknown; |
| 50 | }> { |
| 51 | get [ExpectedFailure]() { |
| 52 | return true; |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | const missingOrg = () => |
| 57 | new ProjectResolutionError({ |
| 58 | reason: 'missing_org', |
| 59 | message: 'No current org configured. Run `composio login` or `composio orgs switch`.', |
| 60 | }); |
| 61 | |
| 62 | /** |
| 63 | * Lookup failures a user can act on become `ProjectResolutionError`; other client errors |
| 64 | * (connection, configuration) keep their type. |
| 65 | */ |
| 66 | const normalizeLookupError = <E>(error: E): ProjectResolutionError | E => { |
| 67 | if (error instanceof DeveloperProjectNotFoundError) { |
| 68 | return new ProjectResolutionError({ |
| 69 | reason: 'project_not_found', |
| 70 | message: `Developer project "${error.projectName}" was not found in org "${error.orgId}". Run \`composio dev init\` or \`composio dev projects list\`.`, |
| 71 | }); |
| 72 | } |
| 73 | if (error instanceof AmbiguousDeveloperProjectNameError) { |
| 74 | return new ProjectResolutionError({ |
| 75 | reason: 'ambiguous_project_name', |
| 76 | message: `Developer project name "${error.projectName}" is ambiguous in org "${error.orgId}". Use an exact unique project name.`, |
| 77 | }); |
| 78 | } |
| 79 | const apiMessage = isAPIError(error) ? extractMessage(error) : undefined; |
| 80 | return apiMessage === undefined |
| 81 | ? error |
| 82 | : new ProjectResolutionError({ reason: 'request_failed', message: apiMessage, cause: error }); |
| 83 | }; |
| 84 | |
| 85 | /** Why the working directory's developer project cannot serve a command. */ |
| 86 | type DirectoryProjectRefusal = |
| 87 | | { readonly reason: 'missing_developer_project' } |
| 88 | | { |
| 89 | readonly reason: 'org_mismatch'; |
| 90 | readonly directoryOrgId: string; |
| 91 | readonly storedOrgId: Option.Option<string>; |
| 92 | }; |
| 93 | |
| 94 | const refusalError = (refusal: DirectoryProjectRefusal): ProjectResolutionError => |
| 95 | refusal.reason === 'missing_developer_project' |
| 96 | ? new ProjectResolutionError({ |
| 97 | reason: 'missing_developer_project', |
| 98 | message: 'No developer project configured for this directory. Run `composio dev init`.', |
| 99 | }) |
| 100 | : new ProjectResolutionError({ |
| 101 | reason: 'org_mismatch', |
| 102 | message: Option.match(refusal.storedOrgId, { |
| 103 | onSome: storedOrgId => |
| 104 | `This directory is set up for a developer project in org "${refusal.directoryOrgId}", not in the org you are logged in to ("${storedOrgId}"). Run \`composio orgs switch\` to use that org, \`composio dev init\` to set this directory up in yours, or pass --project-name.`, |
| 105 | onNone: () => |
| 106 | `This directory is set up for a developer project in org "${refusal.directoryOrgId}", which your API key cannot access. Run \`composio dev init\` to set it up in one of your orgs, or pass --project-name.`, |
| 107 | }), |
| 108 | }); |
| 109 | |
| 110 | /** |
| 111 | * The developer project the working directory is set up for, or why it cannot be used. A cloned |
| 112 | * repository's `.composio/` must not send the user's requests, and the credentials some of them |
| 113 | * carry, to a project its author chose, so the project must be in the org the user is logged in |
| 114 | * to. Without a stored org, as with a key from `COMPOSIO_USER_API_KEY`, it must be in an org the |
| 115 | * key belongs to. |
| 116 | */ |
| 117 | const localDeveloperProject = (params: { |
| 118 | projectContext: ProjectContext['Service']; |
| 119 | apiKey: string; |
| 120 | storedOrgId: Option.Option<string>; |
| 121 | }) => |
| 122 | Effect.gen(function* () { |
| 123 | const localProject = yield* params.projectContext.resolve; |
| 124 | if (Option.isNone(localProject)) { |
| 125 | return Result.fail<DirectoryProjectRefusal>({ reason: 'missing_developer_project' }); |
| 126 | } |
| 127 | const { orgId, projectId, projectName } = localProject.value; |
| 128 | const allowed = yield* Option.match(params.storedOrgId, { |
| 129 | onSome: storedOrgId => Effect.succeed(storedOrgId === orgId), |
| 130 | onNone: () => userKeyBelongsToOrg({ apiKey: params.apiKey, orgId }), |
| 131 | }); |
| 132 | if (!allowed) { |
| 133 | return Result.fail<DirectoryProjectRefusal>({ |
| 134 | reason: 'org_mismatch', |
| 135 | directoryOrgId: orgId, |
| 136 | storedOrgId: params.storedOrgId, |
| 137 | }); |
| 138 | } |
| 139 | return Result.succeed({ |
| 140 | orgId, |
| 141 | projectId, |
| 142 | projectName: Option.getOrUndefined(projectName), |
| 143 | projectType: 'DEVELOPER', |
| 144 | source: 'developer-local-config', |
| 145 | } satisfies ResolvedCommandProject); |
| 146 | }); |
| 147 | |
| 148 | /** The directory's developer project; fails with `ProjectResolutionError` when it cannot be used. */ |
| 149 | const resolveLocalDeveloperProject = (params: Parameters<typeof localDeveloperProject>[0]) => |
| 150 | localDeveloperProject(params).pipe( |
| 151 | Effect.flatMap(result => Effect.fromResult(Result.mapError(result, refusalError))) |
| 152 | ); |
| 153 | |
| 154 | /** What is wrong with the directory's developer project, as the start of a sentence. */ |
| 155 | const refusalSummary = (refusal: DirectoryProjectRefusal): string => |
| 156 | refusal.reason === 'missing_developer_project' |
| 157 | ? 'No developer project is set up for this directory' |
| 158 | : Option.match(refusal.storedOrgId, { |
| 159 | onSome: storedOrgId => |
| 160 | `This directory's developer project is in org "${refusal.directoryOrgId}", not the org you are logged in to ("${storedOrgId}")`, |
| 161 | onNone: () => |
| 162 | `This directory's developer project is in org "${refusal.directoryOrgId}", which your API key cannot access`, |
| 163 | }); |
| 164 | |
| 165 | /** The command that lets the directory's own developer project serve the next run. */ |
| 166 | const refusalRemedy = (refusal: DirectoryProjectRefusal): string => |
| 167 | refusal.reason === 'missing_developer_project' |
| 168 | ? 'Run `composio dev init` to choose one, or pass --project-name.' |
| 169 | : Option.match(refusal.storedOrgId, { |
| 170 | onSome: () => |
| 171 | "Run `composio orgs switch` to use the directory's org, or `composio dev init` to set this directory up in yours.", |
| 172 | onNone: () => 'Run `composio dev init` to set this directory up in one of your orgs.', |
| 173 | }); |
| 174 | |
| 175 | /** The stderr notice naming the default developer project a command uses instead. */ |
| 176 | const defaultProjectNotice = ( |
| 177 | refusal: DirectoryProjectRefusal, |
| 178 | project: ResolvedCommandProject, |
| 179 | storedOrgId: Option.Option<string> |
| 180 | ): string => { |
| 181 | const which = Option.isSome(storedOrgId) |
| 182 | ? 'the newest developer project in the org you are logged in to' |
| 183 | : 'the newest developer project in the org you joined most recently'; |
| 184 | return `${refusalSummary(refusal)}; using "${project.projectName}" (${project.projectId}), ${which}, instead. ${refusalRemedy(refusal)}`; |
| 185 | }; |
| 186 | |
| 187 | /** |
| 188 | * The developer project the backend acts on for a user-key request that names none: the newest |
| 189 | * developer project of the stored org (sent as `x-org-id`, so `composio orgs switch` holds), or |
| 190 | * without one, of the org the user joined most recently. Read once from session info, so every |
| 191 | * request of the command names this one project even if another becomes the newest meanwhile. |
| 192 | * Session info without a project, or a 404, means there is no such project. Other request |
| 193 | * failures keep their cause and message instead of recommending project setup. |
| 194 | */ |
| 195 | const defaultDeveloperProject = (params: { |
| 196 | apiKey: string; |
| 197 | storedOrgId: Option.Option<string>; |
| 198 | refusal: DirectoryProjectRefusal; |
| 199 | }) => |
| 200 | getSessionInfoByUserApiKey({ |
| 201 | userApiKey: params.apiKey, |
| 202 | orgId: Option.getOrUndefined(params.storedOrgId), |
| 203 | }).pipe( |
| 204 | Effect.map( |
| 205 | info => |
| 206 | ({ |
| 207 | orgId: info.project.org.id, |
| 208 | projectId: info.project.nano_id, |
| 209 | projectName: info.project.name, |
| 210 | projectType: 'DEVELOPER', |
| 211 | source: 'developer-default', |
| 212 | }) satisfies ResolvedCommandProject |
| 213 | ), |
| 214 | Effect.mapError(error => |
| 215 | (isAPIError(error) && error.status === 404) || |
| 216 | Predicate.isTagged(error, 'services/HttpDecodingError') |
| 217 | ? new ProjectResolutionError({ |
| 218 | reason: 'missing_developer_project', |
| 219 | message: `${refusalSummary(params.refusal)}, and no developer project was found in your org to use instead. Run \`composio dev init\` to set one up.`, |
| 220 | cause: error, |
| 221 | }) |
| 222 | : error |
| 223 | ) |
| 224 | ); |
| 225 | |
| 226 | export const resolveCommandProject = (params: { mode: ProjectMode; projectName?: string }) => |
| 227 | Effect.gen(function* () { |
| 228 | const ctx = yield* ComposioUserContext; |
| 229 | const projectContext = yield* ProjectContext; |
| 230 | const apiKey = Option.getOrUndefined(ctx.data.apiKey); |
| 231 | if (!apiKey) { |
| 232 | return yield* Effect.fail(missingOrg()); |
| 233 | } |
| 234 | |
| 235 | // The directory's own project needs no stored org: a key from `COMPOSIO_USER_API_KEY` |
| 236 | // carries none, and the project file names its org. |
| 237 | if (params.mode === 'developer' && !params.projectName) { |
| 238 | return yield* resolveLocalDeveloperProject({ |
| 239 | projectContext, |
| 240 | apiKey, |
| 241 | storedOrgId: ctx.data.orgId, |
| 242 | }); |
| 243 | } |
| 244 | |
| 245 | const currentOrgId = yield* Option.match(ctx.data.orgId, { |
| 246 | onNone: () => Effect.fail(missingOrg()), |
| 247 | onSome: value => Effect.succeed(value), |
| 248 | }); |
| 249 | |
| 250 | if (params.projectName) { |
| 251 | const developerProject = yield* findDeveloperProjectByName({ |
| 252 | apiKey, |
| 253 | orgId: currentOrgId, |
| 254 | name: params.projectName, |
| 255 | }); |
| 256 | |
| 257 | return { |
| 258 | orgId: currentOrgId, |
| 259 | projectId: developerProject.id, |
| 260 | projectName: developerProject.name, |
| 261 | projectType: 'DEVELOPER', |
| 262 | source: params.mode === 'consumer' ? 'developer-project-name' : 'developer-explicit', |
| 263 | } satisfies ResolvedCommandProject; |
| 264 | } |
| 265 | |
| 266 | const consumerProject = yield* resolveConsumerProject({ |
| 267 | apiKey, |
| 268 | orgId: currentOrgId, |
| 269 | }); |
| 270 | |
| 271 | return { |
| 272 | orgId: consumerProject.org_id, |
| 273 | projectId: consumerProject.project_nano_id, |
| 274 | projectName: consumerProject.project_name, |
| 275 | projectType: 'CONSUMER', |
| 276 | consumerUserId: consumerProject.consumer_user_id, |
| 277 | source: 'consumer-default', |
| 278 | } satisfies ResolvedCommandProject; |
| 279 | }).pipe(Effect.mapError(normalizeLookupError)); |
| 280 | |
| 281 | /** |
| 282 | * The developer project for a dev command that acted on the backend's default project before |
| 283 | * it named one, so a directory without a usable project of its own keeps working: `--project-name`'s |
| 284 | * (whose failures stay failures), else the directory's, else the backend's default developer |
| 285 | * project (`defaultDeveloperProject`). `notice` says, for stderr, why the default stands in and |
| 286 | * which project it is; it is none when the command uses the project it was given. The default |
| 287 | * never stands in for a `--project-name` that cannot be resolved, and no request ever names a |
| 288 | * directory project that fails the org check. |
| 289 | */ |
| 290 | export const resolveDeveloperProjectOrDefault = (params: { projectName?: string }) => |
| 291 | Effect.gen(function* () { |
| 292 | if (params.projectName) { |
| 293 | const project = yield* resolveCommandProject({ |
| 294 | mode: 'developer', |
| 295 | projectName: params.projectName, |
| 296 | }); |
| 297 | return { project, notice: Option.none<string>() }; |
| 298 | } |
| 299 | const ctx = yield* ComposioUserContext; |
| 300 | const projectContext = yield* ProjectContext; |
| 301 | const apiKey = Option.getOrUndefined(ctx.data.apiKey); |
| 302 | if (!apiKey) { |
| 303 | return yield* Effect.fail(missingOrg()); |
| 304 | } |
| 305 | const storedOrgId = ctx.data.orgId; |
| 306 | const local = yield* localDeveloperProject({ projectContext, apiKey, storedOrgId }); |
| 307 | return yield* Result.match(local, { |
| 308 | onSuccess: project => Effect.succeed({ project, notice: Option.none<string>() }), |
| 309 | onFailure: refusal => |
| 310 | Effect.map(defaultDeveloperProject({ apiKey, storedOrgId, refusal }), project => ({ |
| 311 | project, |
| 312 | notice: Option.some(defaultProjectNotice(refusal, project, storedOrgId)), |
| 313 | })), |
| 314 | }); |
| 315 | }).pipe(Effect.mapError(normalizeLookupError)); |