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 * as PlatformError from 'effect/PlatformError'; |
| 2 | import { Data, Effect, Option, Predicate, Schema } from 'effect'; |
| 3 | import { ChildProcess as Command } from 'effect/process'; |
| 4 | import semver from 'semver'; |
| 5 | import { trackCliEventEffect } from 'src/analytics/dispatch'; |
| 6 | import { |
| 7 | getPluginLifecycleFailedEvent, |
| 8 | getPluginLifecycleSucceededEvent, |
| 9 | } from 'src/analytics/events'; |
| 10 | import { APP_VERSION } from 'src/constants'; |
| 11 | import { |
| 12 | AGENT_HOSTS, |
| 13 | AGENT_HOST_LABELS, |
| 14 | COMPOSIO_AGENT_PLUGIN_ID, |
| 15 | type AgentHost, |
| 16 | } from './agent-host'; |
| 17 | import { probeHostInstallation } from './agent-host-env'; |
| 18 | import { CommandRunner, type CommandResult } from './command-runner'; |
| 19 | import { NodeOs } from './node-os'; |
| 20 | import { resolveWindowsExecutable } from './windows-executable'; |
| 21 | import { SetupCommandError } from './setup-command-error'; |
| 22 | import { SetupSkillInstaller } from './setup-skill-installer'; |
| 23 | import { cliInvocationContext } from './runtime-cli-context'; |
| 24 | |
| 25 | export const SETUP_TARGETS = ['auto', ...AGENT_HOSTS, 'all'] as const; |
| 26 | export type SetupTarget = (typeof SETUP_TARGETS)[number]; |
| 27 | export type { AgentHost } from './agent-host'; |
| 28 | |
| 29 | const CLAUDE_PLUGIN_MARKETPLACE = { |
| 30 | name: 'composio', |
| 31 | source: 'https://github.com/ComposioHQ/composio-plugin-cc.git', |
| 32 | plugin: COMPOSIO_AGENT_PLUGIN_ID, |
| 33 | } as const; |
| 34 | |
| 35 | const CODEX_PLUGIN_MARKETPLACE = { |
| 36 | name: 'composio', |
| 37 | source: 'https://github.com/ComposioHQ/composio-plugin-openai.git', |
| 38 | plugin: COMPOSIO_AGENT_PLUGIN_ID, |
| 39 | } as const; |
| 40 | |
| 41 | export interface SetupTargetStatus { |
| 42 | readonly target: AgentHost; |
| 43 | readonly available: boolean; |
| 44 | readonly marketplace_configured: boolean; |
| 45 | readonly plugin_installed: boolean; |
| 46 | readonly plugin_enabled: boolean; |
| 47 | /** Whether this host can load the authenticated composio-cli skill. */ |
| 48 | readonly cli_skill_ready: boolean; |
| 49 | } |
| 50 | |
| 51 | export interface SetupTargetResult extends SetupTargetStatus { |
| 52 | readonly changed: boolean; |
| 53 | readonly plugin_changed: boolean; |
| 54 | readonly skill_changed: boolean; |
| 55 | } |
| 56 | |
| 57 | interface SetupTargetAdapter { |
| 58 | readonly target: AgentHost; |
| 59 | readonly executable: string; |
| 60 | readonly marketplace: typeof CLAUDE_PLUGIN_MARKETPLACE | typeof CODEX_PLUGIN_MARKETPLACE; |
| 61 | readonly marketplaceListArgs: ReadonlyArray<string>; |
| 62 | readonly pluginListArgs: ReadonlyArray<string>; |
| 63 | readonly marketplaceAddArgs: ReadonlyArray<string>; |
| 64 | readonly pluginInstallArgs: ReadonlyArray<string>; |
| 65 | readonly pluginEnableArgs: ReadonlyArray<string>; |
| 66 | readonly pluginUninstallArgs: ReadonlyArray<string>; |
| 67 | readonly inspectionHelpArgs: ReadonlyArray<ReadonlyArray<string>>; |
| 68 | readonly marketplaceRecordsKey?: string; |
| 69 | readonly pluginRecordsKey?: string; |
| 70 | readonly pluginScope?: string; |
| 71 | readonly marketplaceRemoveCommand: string; |
| 72 | readonly skillSource: 'bundled' | 'standalone'; |
| 73 | } |
| 74 | |
| 75 | export interface InspectedSetupTarget extends SetupTargetStatus { |
| 76 | readonly marketplace_conflict: boolean; |
| 77 | } |
| 78 | |
| 79 | const ADAPTERS: Readonly<Record<AgentHost, SetupTargetAdapter>> = { |
| 80 | claude: { |
| 81 | target: 'claude', |
| 82 | executable: 'claude', |
| 83 | marketplace: CLAUDE_PLUGIN_MARKETPLACE, |
| 84 | marketplaceListArgs: ['plugin', 'marketplace', 'list', '--json'], |
| 85 | pluginListArgs: ['plugin', 'list', '--json'], |
| 86 | marketplaceAddArgs: [ |
| 87 | 'plugin', |
| 88 | 'marketplace', |
| 89 | 'add', |
| 90 | CLAUDE_PLUGIN_MARKETPLACE.source, |
| 91 | '--scope', |
| 92 | 'user', |
| 93 | ], |
| 94 | pluginInstallArgs: ['plugin', 'install', CLAUDE_PLUGIN_MARKETPLACE.plugin, '--scope', 'user'], |
| 95 | pluginEnableArgs: ['plugin', 'enable', CLAUDE_PLUGIN_MARKETPLACE.plugin, '--scope', 'user'], |
| 96 | pluginUninstallArgs: [ |
| 97 | 'plugin', |
| 98 | 'uninstall', |
| 99 | CLAUDE_PLUGIN_MARKETPLACE.plugin, |
| 100 | '--scope', |
| 101 | 'user', |
| 102 | '--yes', |
| 103 | ], |
| 104 | inspectionHelpArgs: [ |
| 105 | ['plugin', 'marketplace', 'list', '--help'], |
| 106 | ['plugin', 'list', '--help'], |
| 107 | ], |
| 108 | pluginScope: 'user', |
| 109 | marketplaceRemoveCommand: 'claude plugin marketplace remove composio --scope user', |
| 110 | skillSource: 'standalone', |
| 111 | }, |
| 112 | codex: { |
| 113 | target: 'codex', |
| 114 | executable: 'codex', |
| 115 | marketplace: CODEX_PLUGIN_MARKETPLACE, |
| 116 | marketplaceListArgs: ['plugin', 'marketplace', 'list', '--json'], |
| 117 | pluginListArgs: ['plugin', 'list', '--json'], |
| 118 | marketplaceAddArgs: ['plugin', 'marketplace', 'add', CODEX_PLUGIN_MARKETPLACE.source, '--json'], |
| 119 | pluginInstallArgs: ['plugin', 'add', CODEX_PLUGIN_MARKETPLACE.plugin, '--json'], |
| 120 | // Codex has no separate enable command. Re-adding is its native install/repair path. |
| 121 | pluginEnableArgs: ['plugin', 'add', CODEX_PLUGIN_MARKETPLACE.plugin, '--json'], |
| 122 | pluginUninstallArgs: ['plugin', 'remove', CODEX_PLUGIN_MARKETPLACE.plugin, '--json'], |
| 123 | inspectionHelpArgs: [ |
| 124 | ['plugin', 'marketplace', 'list', '--help'], |
| 125 | ['plugin', 'list', '--help'], |
| 126 | ], |
| 127 | marketplaceRecordsKey: 'marketplaces', |
| 128 | pluginRecordsKey: 'installed', |
| 129 | marketplaceRemoveCommand: 'codex plugin marketplace remove composio --json', |
| 130 | skillSource: 'bundled', |
| 131 | }, |
| 132 | }; |
| 133 | |
| 134 | const ADAPTER_LIST = Object.values(ADAPTERS); |
| 135 | const SETUP_COMMAND_TIMEOUT = '2 minutes'; |
| 136 | const MINIMUM_CODEX_SETUP_VERSION = '0.139.0'; |
| 137 | |
| 138 | type SetupFailureStage = 'detect' | 'inspect' | 'validate' | 'mutate' | 'verify' | 'skill'; |
| 139 | |
| 140 | export class SetupProcessError extends Data.TaggedError('services/SetupProcessError')<{ |
| 141 | readonly message: string; |
| 142 | readonly target: AgentHost; |
| 143 | readonly stage: SetupFailureStage; |
| 144 | readonly cause?: unknown; |
| 145 | }> {} |
| 146 | |
| 147 | const setupProcessError = (params: { |
| 148 | readonly adapter: SetupTargetAdapter; |
| 149 | readonly stage: SetupFailureStage; |
| 150 | readonly message: string; |
| 151 | readonly cause?: unknown; |
| 152 | }) => |
| 153 | new SetupProcessError({ |
| 154 | message: params.message, |
| 155 | target: params.adapter.target, |
| 156 | stage: params.stage, |
| 157 | ...(params.cause === undefined ? {} : { cause: params.cause }), |
| 158 | }); |
| 159 | |
| 160 | const asRecord = (value: unknown): Record<string, unknown> | undefined => |
| 161 | Predicate.isObject(value) ? value : undefined; |
| 162 | |
| 163 | const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); |
| 164 | |
| 165 | const parseJson = (value: string): unknown | undefined => |
| 166 | Option.getOrUndefined(decodeJsonOption(value)); |
| 167 | |
| 168 | const isRecord = Predicate.isObject; |
| 169 | |
| 170 | const recordsFrom = ( |
| 171 | value: unknown, |
| 172 | key?: string |
| 173 | ): ReadonlyArray<Record<string, unknown>> | undefined => { |
| 174 | let selected = value; |
| 175 | if (key) { |
| 176 | const record = asRecord(value); |
| 177 | if (!record) return undefined; |
| 178 | selected = record[key]; |
| 179 | } |
| 180 | if (!Array.isArray(selected) || !selected.every(isRecord)) return undefined; |
| 181 | return selected; |
| 182 | }; |
| 183 | |
| 184 | const readString = ( |
| 185 | record: Record<string, unknown> | undefined, |
| 186 | key: string |
| 187 | ): string | undefined => { |
| 188 | const value = record?.[key]; |
| 189 | if (typeof value !== 'string') return undefined; |
| 190 | return value; |
| 191 | }; |
| 192 | |
| 193 | const firstString = (...values: ReadonlyArray<unknown>): string | undefined => { |
| 194 | for (const value of values) { |
| 195 | if (typeof value === 'string') return value; |
| 196 | } |
| 197 | return undefined; |
| 198 | }; |
| 199 | |
| 200 | const normalizeGitHubRepository = (value: string): string | undefined => { |
| 201 | const trimmed = value.trim(); |
| 202 | if (!trimmed) return undefined; |
| 203 | |
| 204 | let repository = trimmed; |
| 205 | if (/^[a-z][a-z0-9+.-]*:\/\//i.test(repository)) { |
| 206 | // new URL() throws on malformed input; an unparseable repository string |
| 207 | // simply normalizes to undefined. |
| 208 | const parsedUrl = Option.liftThrowable((s: string) => new URL(s))(repository); |
| 209 | if (Option.isNone(parsedUrl)) return undefined; |
| 210 | const url = parsedUrl.value; |
| 211 | const isCanonicalGitHubUrl = |
| 212 | url.protocol === 'https:' && |
| 213 | url.hostname.toLowerCase() === 'github.com' && |
| 214 | url.port === '' && |
| 215 | url.username === '' && |
| 216 | url.password === '' && |
| 217 | url.search === '' && |
| 218 | url.hash === ''; |
| 219 | if (!isCanonicalGitHubUrl) return undefined; |
| 220 | repository = url.pathname; |
| 221 | } |
| 222 | |
| 223 | repository = repository.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, ''); |
| 224 | const parts = repository.split('/'); |
| 225 | if (parts.length !== 2 || parts.some(part => !/^[a-z0-9._-]+$/i.test(part))) { |
| 226 | return undefined; |
| 227 | } |
| 228 | return parts.join('/').toLowerCase(); |
| 229 | }; |
| 230 | |
| 231 | const marketplaceState = ( |
| 232 | adapter: SetupTargetAdapter, |
| 233 | output: string |
| 234 | ): { readonly configured: boolean; readonly conflicting: boolean } | undefined => { |
| 235 | const parsed = parseJson(output); |
| 236 | const records = recordsFrom(parsed, adapter.marketplaceRecordsKey); |
| 237 | if (!records) return undefined; |
| 238 | const expected = normalizeGitHubRepository(adapter.marketplace.source); |
| 239 | const sourceMatches = (record: Record<string, unknown>) => { |
| 240 | const nestedSource = asRecord(record.source); |
| 241 | const marketplaceSource = asRecord(record.marketplaceSource); |
| 242 | const source = firstString( |
| 243 | record.source, |
| 244 | readString(nestedSource, 'repo'), |
| 245 | readString(nestedSource, 'source'), |
| 246 | readString(marketplaceSource, 'source') |
| 247 | ); |
| 248 | const candidates = [readString(record, 'repo'), readString(record, 'url'), source]; |
| 249 | return candidates.some(candidate => normalizeGitHubRepository(candidate ?? '') === expected); |
| 250 | }; |
| 251 | const configured = records.some(sourceMatches); |
| 252 | const conflicting = records.some( |
| 253 | record => record.name === adapter.marketplace.name && !sourceMatches(record) |
| 254 | ); |
| 255 | return { configured, conflicting }; |
| 256 | }; |
| 257 | |
| 258 | const pluginState = ( |
| 259 | adapter: SetupTargetAdapter, |
| 260 | output: string |
| 261 | ): { readonly installed: boolean; readonly enabled: boolean } | undefined => { |
| 262 | const parsed = parseJson(output); |
| 263 | const records = recordsFrom(parsed, adapter.pluginRecordsKey); |
| 264 | if (!records) return undefined; |
| 265 | const plugin = records.find(record => { |
| 266 | const id = record.id ?? record.pluginId; |
| 267 | const scopeMatches = !adapter.pluginScope || record.scope === adapter.pluginScope; |
| 268 | return id === adapter.marketplace.plugin && scopeMatches; |
| 269 | }); |
| 270 | if (!plugin || plugin.installed === false) return { installed: false, enabled: false }; |
| 271 | return { installed: true, enabled: plugin.enabled !== false }; |
| 272 | }; |
| 273 | |
| 274 | const commandText = (executable: string, args: ReadonlyArray<string>) => |
| 275 | [executable, ...args].join(' '); |
| 276 | |
| 277 | /** |
| 278 | * The command that runs an agent host's CLI. On Windows the executable is located first: |
| 279 | * an npm-installed host is a `.cmd` shim, which has to run through a shell. Its arguments |
| 280 | * are fixed by `ADAPTERS` and contain nothing a shell would interpret. |
| 281 | */ |
| 282 | const hostCommand = (adapter: SetupTargetAdapter, args: ReadonlyArray<string>) => |
| 283 | Effect.gen(function* () { |
| 284 | const os = yield* NodeOs; |
| 285 | const resolved = |
| 286 | os.platform === 'win32' ? yield* resolveWindowsExecutable(adapter.executable) : Option.none(); |
| 287 | return Option.match(resolved, { |
| 288 | // Not found, or not Windows: spawning by name reports a missing executable as usual. |
| 289 | onNone: () => Command.make(adapter.executable, args), |
| 290 | onSome: executable => |
| 291 | executable.needsShell |
| 292 | ? // A shell takes one command line, not an argument list. |
| 293 | Command.make([`"${executable.path}"`, ...args].join(' '), [], { shell: true }) |
| 294 | : Command.make(executable.path, args), |
| 295 | }); |
| 296 | }); |
| 297 | |
| 298 | const capture = ( |
| 299 | adapter: SetupTargetAdapter, |
| 300 | args: ReadonlyArray<string>, |
| 301 | stage: Extract<SetupFailureStage, 'detect' | 'inspect'> |
| 302 | ) => |
| 303 | Effect.gen(function* () { |
| 304 | const runner = yield* CommandRunner; |
| 305 | return yield* runner.capture(yield* hostCommand(adapter, args)).pipe( |
| 306 | Effect.timeoutOrElse({ |
| 307 | duration: SETUP_COMMAND_TIMEOUT, |
| 308 | orElse: () => |
| 309 | Effect.fail( |
| 310 | setupProcessError({ |
| 311 | adapter, |
| 312 | stage, |
| 313 | message: `The \`${commandText(adapter.executable, args)}\` command timed out after ${SETUP_COMMAND_TIMEOUT}.`, |
| 314 | }) |
| 315 | ), |
| 316 | }) |
| 317 | ); |
| 318 | }); |
| 319 | |
| 320 | const isCommandNotFoundError = ( |
| 321 | error: PlatformError.PlatformError | SetupProcessError |
| 322 | ): error is PlatformError.PlatformError => |
| 323 | Predicate.isTagged(error, 'PlatformError') && Predicate.isTagged(error.reason, 'NotFound'); |
| 324 | |
| 325 | const captureOptional = (adapter: SetupTargetAdapter, args: ReadonlyArray<string>) => |
| 326 | capture(adapter, args, 'detect').pipe( |
| 327 | Effect.catchIf(isCommandNotFoundError, () => |
| 328 | Effect.succeed<CommandResult | undefined>(undefined) |
| 329 | ) |
| 330 | ); |
| 331 | |
| 332 | const targetLabel = (target: AgentHost): string => AGENT_HOST_LABELS[target]; |
| 333 | |
| 334 | const hostUpdateCommand = (adapter: SetupTargetAdapter): string => `${adapter.executable} update`; |
| 335 | |
| 336 | const unsupportedInspectionMessage = (adapter: SetupTargetAdapter) => { |
| 337 | if (adapter.target === 'codex') { |
| 338 | return `This Codex installation does not support safe automatic plugin inspection. Composio setup requires Codex ${MINIMUM_CODEX_SETUP_VERSION} or newer with JSON plugin inspection. Run \`codex update\`, then rerun this command.`; |
| 339 | } |
| 340 | return 'This Claude Code installation does not support safe automatic plugin inspection. Composio setup requires JSON plugin inspection. Run `claude update`, then rerun this command.'; |
| 341 | }; |
| 342 | |
| 343 | const compactCommandDetail = (value: string): string | undefined => { |
| 344 | const firstLine = value |
| 345 | .split(/\r?\n/u) |
| 346 | .map(line => line.trim()) |
| 347 | .find(Boolean); |
| 348 | if (!firstLine) return undefined; |
| 349 | return firstLine.length > 300 ? `${firstLine.slice(0, 297)}...` : firstLine; |
| 350 | }; |
| 351 | |
| 352 | const commandResultDetail = (result: CommandResult): string => { |
| 353 | const detail = compactCommandDetail(result.stderr) ?? compactCommandDetail(result.stdout); |
| 354 | return detail ?? `exit ${result.exitCode}`; |
| 355 | }; |
| 356 | |
| 357 | const capabilityCheckFailureMessage = ( |
| 358 | adapter: SetupTargetAdapter, |
| 359 | command: string, |
| 360 | detail: string |
| 361 | ) => { |
| 362 | const normalizedDetail = detail.trim().replace(/[.]+$/u, ''); |
| 363 | return `Composio could not verify plugin support for ${targetLabel(adapter.target)} because \`${command}\` failed: ${normalizedDetail}. Run \`${hostUpdateCommand(adapter)}\`, then rerun this command.`; |
| 364 | }; |
| 365 | |
| 366 | const supportsInspection = (adapter: SetupTargetAdapter, versionOutput?: string) => |
| 367 | Effect.gen(function* () { |
| 368 | if (adapter.target === 'codex') { |
| 369 | const version = versionOutput?.match(/\b\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?\b/)?.[0]; |
| 370 | if (!version || !semver.valid(version) || semver.lt(version, MINIMUM_CODEX_SETUP_VERSION)) { |
| 371 | return { |
| 372 | supported: false, |
| 373 | reason: unsupportedInspectionMessage(adapter), |
| 374 | reasonCode: 'codex_too_old', |
| 375 | } as const; |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | for (const args of adapter.inspectionHelpArgs) { |
| 380 | const command = commandText(adapter.executable, args); |
| 381 | const result = yield* capture(adapter, args, 'detect').pipe( |
| 382 | Effect.mapError(cause => |
| 383 | setupProcessError({ |
| 384 | adapter, |
| 385 | stage: 'detect', |
| 386 | message: capabilityCheckFailureMessage(adapter, command, errorMessage(cause)), |
| 387 | cause, |
| 388 | }) |
| 389 | ) |
| 390 | ); |
| 391 | if (result.exitCode !== 0) { |
| 392 | return { |
| 393 | supported: false, |
| 394 | reason: capabilityCheckFailureMessage(adapter, command, commandResultDetail(result)), |
| 395 | reasonCode: 'host_command_failed', |
| 396 | } as const; |
| 397 | } |
| 398 | const help = `${result.stdout}\n${result.stderr}`; |
| 399 | if (!/^\s*--json\b/m.test(help)) { |
| 400 | return { |
| 401 | supported: false, |
| 402 | reason: unsupportedInspectionMessage(adapter), |
| 403 | reasonCode: 'no_json_inspection', |
| 404 | } as const; |
| 405 | } |
| 406 | } |
| 407 | return { supported: true } as const; |
| 408 | }); |
| 409 | |
| 410 | const detectAdapter = (adapter: SetupTargetAdapter) => |
| 411 | Effect.gen(function* () { |
| 412 | const versionArgs = ['--version']; |
| 413 | const versionCommand = commandText(adapter.executable, versionArgs); |
| 414 | const detection = yield* captureOptional(adapter, versionArgs).pipe( |
| 415 | Effect.matchEffect({ |
| 416 | onFailure: cause => |
| 417 | Effect.succeed({ |
| 418 | available: true, |
| 419 | supported: false, |
| 420 | unsupportedReason: capabilityCheckFailureMessage( |
| 421 | adapter, |
| 422 | versionCommand, |
| 423 | errorMessage(cause) |
| 424 | ), |
| 425 | unsupportedReasonCode: 'host_command_failed' as const, |
| 426 | }), |
| 427 | onSuccess: result => { |
| 428 | if (!result || result.exitCode === 127) { |
| 429 | return Effect.succeed({ available: false, supported: false }); |
| 430 | } |
| 431 | if (result.exitCode !== 0) { |
| 432 | return Effect.succeed({ |
| 433 | available: true, |
| 434 | supported: false, |
| 435 | unsupportedReason: capabilityCheckFailureMessage( |
| 436 | adapter, |
| 437 | versionCommand, |
| 438 | commandResultDetail(result) |
| 439 | ), |
| 440 | unsupportedReasonCode: 'host_command_failed' as const, |
| 441 | }); |
| 442 | } |
| 443 | |
| 444 | const version = result.stdout.trim() || result.stderr.trim(); |
| 445 | return supportsInspection(adapter, version).pipe( |
| 446 | Effect.match({ |
| 447 | onFailure: cause => ({ |
| 448 | supported: false as const, |
| 449 | reason: errorMessage(cause), |
| 450 | reasonCode: 'host_command_failed' as const, |
| 451 | }), |
| 452 | onSuccess: support => support, |
| 453 | }), |
| 454 | Effect.map(support => |
| 455 | version |
| 456 | ? { |
| 457 | available: true, |
| 458 | supported: support.supported, |
| 459 | version, |
| 460 | ...(support.supported |
| 461 | ? {} |
| 462 | : { |
| 463 | unsupportedReason: support.reason, |
| 464 | unsupportedReasonCode: support.reasonCode, |
| 465 | }), |
| 466 | } |
| 467 | : { |
| 468 | available: true, |
| 469 | supported: support.supported, |
| 470 | ...(support.supported |
| 471 | ? {} |
| 472 | : { |
| 473 | unsupportedReason: support.reason, |
| 474 | unsupportedReasonCode: support.reasonCode, |
| 475 | }), |
| 476 | } |
| 477 | ) |
| 478 | ); |
| 479 | }, |
| 480 | }) |
| 481 | ); |
| 482 | if (detection.available) return detection; |
| 483 | return { ...detection, ...(yield* probeHostInstallation(adapter.target)) }; |
| 484 | }); |
| 485 | |
| 486 | const commandFailureSuffix = (result: CommandResult): string => { |
| 487 | return `: ${commandResultDetail(result)}`; |
| 488 | }; |
| 489 | |
| 490 | const errorMessage = (error: unknown): string => { |
| 491 | if (Predicate.isError(error)) return error.message; |
| 492 | return String(error); |
| 493 | }; |
| 494 | |
| 495 | type SetupOperation = 'setup' | 'uninstall'; |
| 496 | |
| 497 | // Remediation commands must stay usable from the non-interactive shells |
| 498 | // agents run in (the plugin hint's primary audience), so they always carry |
| 499 | // --yes; interactive users can drop it. |
| 500 | const setupCommand = (adapter: SetupTargetAdapter, operation: SetupOperation): string => |
| 501 | `composio setup${operation === 'uninstall' ? ' --uninstall' : ''} --yes --target ${adapter.target}`; |
| 502 | |
| 503 | const recoveryHint = (adapter: SetupTargetAdapter, operation: SetupOperation): string => |
| 504 | `Run \`${setupCommand(adapter, operation)}\` again. If the problem persists, run \`${hostUpdateCommand(adapter)}\` and retry.`; |
| 505 | |
| 506 | const captureInspection = ( |
| 507 | adapter: SetupTargetAdapter, |
| 508 | args: ReadonlyArray<string>, |
| 509 | operation: string, |
| 510 | setupOperation: SetupOperation |
| 511 | ) => |
| 512 | capture(adapter, args, 'inspect').pipe( |
| 513 | Effect.mapError(cause => |
| 514 | setupProcessError({ |
| 515 | adapter, |
| 516 | stage: 'inspect', |
| 517 | message: `Failed to inspect ${targetLabel(adapter.target)} ${operation}: ${errorMessage(cause)}. ${recoveryHint(adapter, setupOperation)}`, |
| 518 | cause, |
| 519 | }) |
| 520 | ) |
| 521 | ); |
| 522 | |
| 523 | const requireInspection = <T>( |
| 524 | adapter: SetupTargetAdapter, |
| 525 | operation: string, |
| 526 | result: CommandResult, |
| 527 | parse: (output: string) => T | undefined, |
| 528 | setupOperation: SetupOperation |
| 529 | ) => { |
| 530 | if (result.exitCode !== 0) { |
| 531 | return setupProcessError({ |
| 532 | adapter, |
| 533 | stage: 'inspect', |
| 534 | message: `Failed to inspect ${targetLabel(adapter.target)} ${operation}${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`, |
| 535 | }); |
| 536 | } |
| 537 | const inspected = parse(result.stdout); |
| 538 | if (!inspected) { |
| 539 | return setupProcessError({ |
| 540 | adapter, |
| 541 | stage: 'inspect', |
| 542 | message: `${targetLabel(adapter.target)} returned invalid JSON while inspecting ${operation}. ${recoveryHint(adapter, setupOperation)}`, |
| 543 | }); |
| 544 | } |
| 545 | return Effect.succeed(inspected); |
| 546 | }; |
| 547 | |
| 548 | const inspectAdapter = ( |
| 549 | adapter: SetupTargetAdapter, |
| 550 | knownDetection?: { |
| 551 | readonly available: boolean; |
| 552 | readonly supported: boolean; |
| 553 | readonly version?: string; |
| 554 | }, |
| 555 | setupOperation: SetupOperation = 'setup' |
| 556 | ) => |
| 557 | Effect.gen(function* () { |
| 558 | const skillInstaller = yield* SetupSkillInstaller; |
| 559 | const detection = knownDetection ?? (yield* detectAdapter(adapter)); |
| 560 | if (!detection.available) { |
| 561 | return { |
| 562 | target: adapter.target, |
| 563 | available: false, |
| 564 | marketplace_configured: false, |
| 565 | plugin_installed: false, |
| 566 | plugin_enabled: false, |
| 567 | cli_skill_ready: false, |
| 568 | marketplace_conflict: false, |
| 569 | } satisfies InspectedSetupTarget; |
| 570 | } |
| 571 | |
| 572 | if (!detection.supported) { |
| 573 | return yield* setupProcessError({ |
| 574 | adapter, |
| 575 | stage: 'inspect', |
| 576 | message: unsupportedInspectionMessage(adapter), |
| 577 | }); |
| 578 | } |
| 579 | |
| 580 | const [marketplaces, plugins] = yield* Effect.all([ |
| 581 | captureInspection(adapter, adapter.marketplaceListArgs, 'marketplaces', setupOperation), |
| 582 | captureInspection(adapter, adapter.pluginListArgs, 'plugins', setupOperation), |
| 583 | ]); |
| 584 | const plugin = yield* requireInspection( |
| 585 | adapter, |
| 586 | 'plugins', |
| 587 | plugins, |
| 588 | output => pluginState(adapter, output), |
| 589 | setupOperation |
| 590 | ); |
| 591 | const pluginReady = plugin.installed && plugin.enabled; |
| 592 | const marketplace = yield* requireInspection( |
| 593 | adapter, |
| 594 | 'marketplaces', |
| 595 | marketplaces, |
| 596 | output => marketplaceState(adapter, output), |
| 597 | setupOperation |
| 598 | ); |
| 599 | let cliSkillReady = pluginReady; |
| 600 | if (adapter.skillSource === 'standalone') { |
| 601 | cliSkillReady = yield* skillInstaller.isClaudeSkillReady; |
| 602 | } |
| 603 | return { |
| 604 | target: adapter.target, |
| 605 | available: true, |
| 606 | marketplace_configured: marketplace.configured, |
| 607 | plugin_installed: plugin.installed, |
| 608 | plugin_enabled: plugin.enabled, |
| 609 | cli_skill_ready: cliSkillReady, |
| 610 | marketplace_conflict: marketplace.conflicting, |
| 611 | } satisfies InspectedSetupTarget; |
| 612 | }); |
| 613 | |
| 614 | interface SetupStep { |
| 615 | readonly args: ReadonlyArray<string>; |
| 616 | readonly operation: string; |
| 617 | } |
| 618 | |
| 619 | const pluginRepairStep = ( |
| 620 | adapter: SetupTargetAdapter, |
| 621 | status: InspectedSetupTarget |
| 622 | ): SetupStep | undefined => { |
| 623 | if (!status.marketplace_configured || !status.plugin_installed) { |
| 624 | return { |
| 625 | args: adapter.pluginInstallArgs, |
| 626 | operation: `Installing the ${adapter.target} plugin`, |
| 627 | }; |
| 628 | } |
| 629 | if (!status.plugin_enabled) { |
| 630 | return { |
| 631 | args: adapter.pluginEnableArgs, |
| 632 | operation: `Enabling the ${adapter.target} plugin`, |
| 633 | }; |
| 634 | } |
| 635 | return undefined; |
| 636 | }; |
| 637 | |
| 638 | export const isSetupPluginReady = (status: SetupTargetStatus): boolean => |
| 639 | status.available && |
| 640 | status.marketplace_configured && |
| 641 | status.plugin_installed && |
| 642 | status.plugin_enabled; |
| 643 | |
| 644 | export const isSetupReady = (status: SetupTargetStatus): boolean => |
| 645 | isSetupPluginReady(status) && status.cli_skill_ready; |
| 646 | |
| 647 | const runRequired = ( |
| 648 | adapter: SetupTargetAdapter, |
| 649 | args: ReadonlyArray<string>, |
| 650 | operation: string, |
| 651 | setupOperation: SetupOperation |
| 652 | ) => |
| 653 | Effect.gen(function* () { |
| 654 | const runner = yield* CommandRunner; |
| 655 | const result = yield* runner.capture(yield* hostCommand(adapter, args)).pipe( |
| 656 | Effect.timeoutOrElse({ |
| 657 | duration: SETUP_COMMAND_TIMEOUT, |
| 658 | orElse: () => |
| 659 | Effect.fail( |
| 660 | setupProcessError({ |
| 661 | adapter, |
| 662 | stage: 'mutate', |
| 663 | message: `${operation} timed out after ${SETUP_COMMAND_TIMEOUT}.`, |
| 664 | }) |
| 665 | ), |
| 666 | }), |
| 667 | Effect.mapError(cause => |
| 668 | setupProcessError({ |
| 669 | adapter, |
| 670 | stage: 'mutate', |
| 671 | message: `${operation} failed: ${errorMessage(cause)}. ${recoveryHint(adapter, setupOperation)}`, |
| 672 | cause, |
| 673 | }) |
| 674 | ) |
| 675 | ); |
| 676 | if (result.exitCode !== 0) { |
| 677 | return yield* setupProcessError({ |
| 678 | adapter, |
| 679 | stage: 'mutate', |
| 680 | message: `${operation} failed${commandFailureSuffix(result)}. ${recoveryHint(adapter, setupOperation)}`, |
| 681 | }); |
| 682 | } |
| 683 | }); |
| 684 | |
| 685 | const validateInitialState = ( |
| 686 | adapter: SetupTargetAdapter, |
| 687 | initial: InspectedSetupTarget, |
| 688 | operation: SetupOperation |
| 689 | ) => { |
| 690 | if (!initial.available) { |
| 691 | return new SetupCommandError({ |
| 692 | operation, |
| 693 | reasonCode: 'target_not_installed', |
| 694 | message: `${adapter.executable} is not installed or not available on PATH. Install it and rerun \`composio setup --yes --target ${adapter.target}\`.`, |
| 695 | }); |
| 696 | } |
| 697 | if (initial.marketplace_conflict) { |
| 698 | return new SetupCommandError({ |
| 699 | operation, |
| 700 | reasonCode: 'marketplace_conflict', |
| 701 | message: `The ${adapter.target} marketplace named "composio" points to a different source. Run \`${adapter.marketplaceRemoveCommand}\`, then rerun \`composio setup --yes --target ${adapter.target}\`.`, |
| 702 | }); |
| 703 | } |
| 704 | return Effect.void; |
| 705 | }; |
| 706 | |
| 707 | const toSetupTargetResult = (params: { |
| 708 | readonly adapter: SetupTargetAdapter; |
| 709 | readonly final: InspectedSetupTarget; |
| 710 | readonly pluginChanged: boolean; |
| 711 | readonly skillChanged: boolean; |
| 712 | }): SetupTargetResult => ({ |
| 713 | target: params.adapter.target, |
| 714 | available: params.final.available, |
| 715 | marketplace_configured: params.final.marketplace_configured, |
| 716 | plugin_installed: params.final.plugin_installed, |
| 717 | plugin_enabled: params.final.plugin_enabled, |
| 718 | cli_skill_ready: params.final.cli_skill_ready, |
| 719 | changed: params.pluginChanged || params.skillChanged, |
| 720 | plugin_changed: params.pluginChanged, |
| 721 | skill_changed: params.skillChanged, |
| 722 | }); |
| 723 | |
| 724 | const installAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) => |
| 725 | Effect.gen(function* () { |
| 726 | const steps: SetupStep[] = []; |
| 727 | if (!initial.marketplace_configured) { |
| 728 | steps.push({ |
| 729 | args: adapter.marketplaceAddArgs, |
| 730 | operation: `Adding the ${adapter.target} marketplace`, |
| 731 | }); |
| 732 | } |
| 733 | const repairStep = pluginRepairStep(adapter, initial); |
| 734 | if (repairStep) steps.push(repairStep); |
| 735 | for (const step of steps) { |
| 736 | yield* runRequired(adapter, step.args, step.operation, 'setup'); |
| 737 | } |
| 738 | const pluginChanged = steps.length > 0; |
| 739 | |
| 740 | const skillInstaller = yield* SetupSkillInstaller; |
| 741 | let skillChanged = false; |
| 742 | if (adapter.skillSource === 'standalone' && !initial.cli_skill_ready) { |
| 743 | skillChanged = yield* skillInstaller.ensureClaudeSkill.pipe( |
| 744 | Effect.mapError(cause => |
| 745 | setupProcessError({ |
| 746 | adapter, |
| 747 | stage: 'skill', |
| 748 | message: `Installing the Claude Code CLI skill failed: ${errorMessage(cause)}. ${recoveryHint(adapter, 'setup')}`, |
| 749 | cause, |
| 750 | }) |
| 751 | ) |
| 752 | ); |
| 753 | } |
| 754 | |
| 755 | const final = yield* inspectAdapter(adapter); |
| 756 | if (!isSetupReady(final)) { |
| 757 | return yield* setupProcessError({ |
| 758 | adapter, |
| 759 | stage: 'verify', |
| 760 | message: `Setup commands completed, but ${adapter.target} did not report the Composio plugin and CLI skill as ready. Rerun \`${setupCommand(adapter, 'setup')}\` or inspect the native ${adapter.target} plugin configuration.`, |
| 761 | }); |
| 762 | } |
| 763 | |
| 764 | return toSetupTargetResult({ adapter, final, pluginChanged, skillChanged }); |
| 765 | }); |
| 766 | |
| 767 | const uninstallAdapter = (adapter: SetupTargetAdapter, initial: InspectedSetupTarget) => |
| 768 | Effect.gen(function* () { |
| 769 | let pluginChanged = false; |
| 770 | if (initial.plugin_installed) { |
| 771 | yield* runRequired( |
| 772 | adapter, |
| 773 | adapter.pluginUninstallArgs, |
| 774 | `Uninstalling the ${adapter.target} plugin`, |
| 775 | 'uninstall' |
| 776 | ); |
| 777 | pluginChanged = true; |
| 778 | } |
| 779 | |
| 780 | const skillInstaller = yield* SetupSkillInstaller; |
| 781 | let skillChanged = false; |
| 782 | if (adapter.skillSource === 'standalone') { |
| 783 | skillChanged = yield* skillInstaller.removeClaudeSkill.pipe( |
| 784 | Effect.mapError(cause => |
| 785 | setupProcessError({ |
| 786 | adapter, |
| 787 | stage: 'skill', |
| 788 | message: `Removing the Claude Code CLI skill failed: ${errorMessage(cause)}. ${recoveryHint(adapter, 'uninstall')}`, |
| 789 | cause, |
| 790 | }) |
| 791 | ) |
| 792 | ); |
| 793 | } |
| 794 | |
| 795 | const final = yield* inspectAdapter(adapter, undefined, 'uninstall'); |
| 796 | if (final.plugin_installed) { |
| 797 | return yield* setupProcessError({ |
| 798 | adapter, |
| 799 | stage: 'verify', |
| 800 | message: `Uninstall commands completed, but ${adapter.target} still reports the Composio plugin as installed. Rerun \`${setupCommand(adapter, 'uninstall')}\` or inspect the native ${adapter.target} plugin configuration.`, |
| 801 | }); |
| 802 | } |
| 803 | |
| 804 | return toSetupTargetResult({ adapter, final, pluginChanged, skillChanged }); |
| 805 | }); |
| 806 | |
| 807 | const FIXED_TARGETS: Readonly<Partial<Record<SetupTarget, ReadonlyArray<AgentHost>>>> = { |
| 808 | claude: ['claude'], |
| 809 | codex: ['codex'], |
| 810 | all: ['claude', 'codex'], |
| 811 | }; |
| 812 | |
| 813 | export type SetupUnsupportedReasonCode = |
| 814 | 'codex_too_old' | 'no_json_inspection' | 'host_command_failed' | 'unknown'; |
| 815 | |
| 816 | export interface SetupTargetDetection { |
| 817 | readonly target: AgentHost; |
| 818 | readonly available: boolean; |
| 819 | readonly supported: boolean; |
| 820 | readonly version?: string; |
| 821 | readonly unsupportedReason?: string; |
| 822 | readonly unsupportedReasonCode?: SetupUnsupportedReasonCode; |
| 823 | readonly configDirPresent?: boolean; |
| 824 | readonly binaryInKnownPaths?: boolean; |
| 825 | } |
| 826 | |
| 827 | export const detectSetupTargets = (target: SetupTarget) => |
| 828 | Effect.gen(function* () { |
| 829 | const targets = FIXED_TARGETS[target] ?? ADAPTER_LIST.map(adapter => adapter.target); |
| 830 | return yield* Effect.all( |
| 831 | targets.map(target => |
| 832 | detectAdapter(ADAPTERS[target]).pipe( |
| 833 | Effect.map((detection): SetupTargetDetection => ({ target, ...detection })) |
| 834 | ) |
| 835 | ) |
| 836 | ); |
| 837 | }); |
| 838 | |
| 839 | export const inspectSetupTargets = ( |
| 840 | detections: ReadonlyArray<SetupTargetDetection>, |
| 841 | options: { |
| 842 | readonly allowMarketplaceConflict?: boolean; |
| 843 | readonly operation?: SetupOperation; |
| 844 | } = {} |
| 845 | ) => |
| 846 | Effect.gen(function* () { |
| 847 | const inspected = yield* Effect.forEach( |
| 848 | detections.filter(detection => detection.available && detection.supported), |
| 849 | detection => |
| 850 | inspectAdapter(ADAPTERS[detection.target], detection, options.operation ?? 'setup') |
| 851 | ); |
| 852 | if (!options.allowMarketplaceConflict) { |
| 853 | yield* Effect.forEach(inspected, status => |
| 854 | validateInitialState(ADAPTERS[status.target], status, options.operation ?? 'setup') |
| 855 | ); |
| 856 | } |
| 857 | return inspected; |
| 858 | }); |
| 859 | |
| 860 | const pluginLifecycleAction = ( |
| 861 | operation: 'setup' | 'uninstall', |
| 862 | status: InspectedSetupTarget |
| 863 | ): 'installed' | 'enabled' | 'configured' | 'uninstalled' => { |
| 864 | if (operation === 'uninstall') return 'uninstalled'; |
| 865 | if (!status.plugin_installed) return 'installed'; |
| 866 | if (!status.plugin_enabled) return 'enabled'; |
| 867 | return 'configured'; |
| 868 | }; |
| 869 | |
| 870 | const runSetupTargets = <E, R>( |
| 871 | inspected: ReadonlyArray<InspectedSetupTarget>, |
| 872 | runAdapter: ( |
| 873 | adapter: SetupTargetAdapter, |
| 874 | status: InspectedSetupTarget |
| 875 | ) => Effect.Effect<SetupTargetResult, E, R>, |
| 876 | verb: 'Setup' | 'Uninstall' |
| 877 | ) => |
| 878 | Effect.gen(function* () { |
| 879 | const operation = verb === 'Uninstall' ? 'uninstall' : 'setup'; |
| 880 | const phase = verb === 'Uninstall' ? 'uninstall' : 'install'; |
| 881 | const { invocationOrigin } = yield* cliInvocationContext; |
| 882 | const completed: SetupTargetResult[] = []; |
| 883 | for (const status of inspected) { |
| 884 | const result = yield* runAdapter(ADAPTERS[status.target], status).pipe( |
| 885 | Effect.tapError(error => |
| 886 | trackCliEventEffect( |
| 887 | getPluginLifecycleFailedEvent({ |
| 888 | operation, |
| 889 | target: status.target, |
| 890 | phase, |
| 891 | error, |
| 892 | invocationOrigin, |
| 893 | cliVersion: APP_VERSION, |
| 894 | }) |
| 895 | ) |
| 896 | ), |
| 897 | Effect.mapError(error => { |
| 898 | if (completed.length === 0) return error; |
| 899 | const targets = completed.map(item => item.target).join(', '); |
| 900 | return setupProcessError({ |
| 901 | adapter: ADAPTERS[status.target], |
| 902 | stage: 'mutate', |
| 903 | message: `${verb} completed for ${targets} before a later target failed: ${errorMessage(error)}`, |
| 904 | cause: error, |
| 905 | }); |
| 906 | }) |
| 907 | ); |
| 908 | if (result.plugin_changed) { |
| 909 | yield* trackCliEventEffect( |
| 910 | getPluginLifecycleSucceededEvent({ |
| 911 | operation, |
| 912 | target: result.target, |
| 913 | action: pluginLifecycleAction(operation, status), |
| 914 | invocationOrigin, |
| 915 | cliVersion: APP_VERSION, |
| 916 | }) |
| 917 | ); |
| 918 | } |
| 919 | completed.push(result); |
| 920 | } |
| 921 | return completed; |
| 922 | }); |
| 923 | |
| 924 | export const installSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) => |
| 925 | runSetupTargets(inspected, installAdapter, 'Setup'); |
| 926 | |
| 927 | export const uninstallSetupTargets = (inspected: ReadonlyArray<InspectedSetupTarget>) => |
| 928 | runSetupTargets(inspected, uninstallAdapter, 'Uninstall'); |