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 BunPath from '@effect/platform-bun/BunPath'; |
| 2 | import { |
| 3 | Data, |
| 4 | Effect, |
| 5 | Match, |
| 6 | Option, |
| 7 | Predicate, |
| 8 | Record as EffectRecord, |
| 9 | Schedule, |
| 10 | Scope, |
| 11 | Stream, |
| 12 | Context, |
| 13 | Layer, |
| 14 | } from 'effect'; |
| 15 | import { HttpClient, HttpClientResponse } from 'effect/http'; |
| 16 | import * as FileSystem from 'effect/FileSystem'; |
| 17 | import * as Path from 'effect/Path'; |
| 18 | import { APP_VERSION } from '../constants'; |
| 19 | import { DEBUG_CONFIG, GITHUB_CONFIG, type GitHubConfig } from 'src/config'; |
| 20 | import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform'; |
| 21 | import { CompareSemverError, semverComparator } from 'src/effects/compare-semver'; |
| 22 | import { ExpectedFailure } from 'src/effects/expected-failure'; |
| 23 | import { fetchLatestCliRelease, GitHubRelease } from 'src/effects/resolve-cli-release'; |
| 24 | import { parseChecksumsText, sha256Hex } from 'src/utils/checksums'; |
| 25 | import { atomicReplaceFile, type AtomicReplaceError } from 'src/utils/atomic-replace'; |
| 26 | |
| 27 | // Note: `node:zlib` does not support Github's zip files |
| 28 | import { extractZipSafely } from 'src/utils/extract-zip-safely'; |
| 29 | import { renderPrettyError } from './utils/pretty-error'; |
| 30 | import { TerminalUI } from './terminal-ui'; |
| 31 | import { NodeOs } from './node-os'; |
| 32 | import { recordLatestStableRelease } from './update-check'; |
| 33 | import { |
| 34 | ArchiveCompanions, |
| 35 | RELEASE_MANIFEST_FILENAME, |
| 36 | RUN_COMPANION_RELEASE_TAG_FILENAME, |
| 37 | resolveArchiveCompanions, |
| 38 | resolveRecordedRunningCliVersion, |
| 39 | resolveRunningCliReleaseTag, |
| 40 | writeInstalledReleaseTag, |
| 41 | type ReleaseManifest, |
| 42 | } from './run-companion-modules'; |
| 43 | |
| 44 | export class UpgradeBinaryError extends Data.TaggedError('services/UpgradeBinaryError')<{ |
| 45 | readonly cause?: unknown; |
| 46 | readonly message?: string; |
| 47 | }> {} |
| 48 | |
| 49 | export class UpgradeBelowMinimumError extends Data.TaggedError( |
| 50 | 'services/UpgradeBelowMinimumError' |
| 51 | )<{ |
| 52 | readonly message: string; |
| 53 | readonly currentVersion: string; |
| 54 | readonly minimumUpgradeFrom: string; |
| 55 | }> { |
| 56 | get [ExpectedFailure]() { |
| 57 | return true; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | const reinstallCommand = (platform: NodeJS.Platform) => |
| 62 | platform === 'win32' |
| 63 | ? 'irm https://raw.githubusercontent.com/ComposioHQ/composio/next/install.ps1 | iex' |
| 64 | : 'curl -fsSL https://composio.dev/install | sh'; |
| 65 | |
| 66 | /** |
| 67 | * CLI binary name constant |
| 68 | */ |
| 69 | export const CLI_BINARY_NAME = 'composio'; |
| 70 | // Older releases shipped macOS local-tool sidecars in this directory next to the |
| 71 | // binary. Current archives omit it, so upgrades remove what an old install left. |
| 72 | const LEGACY_LOCAL_TOOLS_DIRNAME = 'local-tools-binaries'; |
| 73 | |
| 74 | const getBinaryAssetName = (platformArch: PlatformArch) => |
| 75 | `${CLI_BINARY_NAME}-${platformArch.platform}-${platformArch.arch}.zip`; |
| 76 | |
| 77 | const hasPlatformBinaryAsset = (release: GitHubRelease, platformArch: PlatformArch) => |
| 78 | release.assets.some(asset => asset.name === getBinaryAssetName(platformArch)); |
| 79 | |
| 80 | // Dependencies resolved once at service construction time and threaded |
| 81 | // through the module-level helpers below. |
| 82 | interface UpgradeBinaryContext { |
| 83 | readonly httpClient: HttpClient.HttpClient; |
| 84 | readonly fs: FileSystem.FileSystem; |
| 85 | readonly path: Path.Path; |
| 86 | readonly githubConfig: GitHubConfig; |
| 87 | readonly platform: NodeJS.Platform; |
| 88 | } |
| 89 | |
| 90 | /** |
| 91 | * Fetch latest release from GitHub |
| 92 | */ |
| 93 | const fetchGitHubRelease = ( |
| 94 | { githubConfig, httpClient }: UpgradeBinaryContext, |
| 95 | tag: string |
| 96 | ): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> => |
| 97 | Effect.gen(function* () { |
| 98 | const encodedTag = encodeURIComponent(tag); |
| 99 | const url = `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodedTag}`; |
| 100 | const fetchErrorMessage = `Failed to fetch tags/${tag} release from GitHub`; |
| 101 | yield* Effect.logDebug(`GET ${url}`); |
| 102 | |
| 103 | const response = yield* httpClient.get(url).pipe( |
| 104 | Effect.mapError( |
| 105 | cause => |
| 106 | new UpgradeBinaryError({ |
| 107 | cause, |
| 108 | message: fetchErrorMessage, |
| 109 | }) |
| 110 | ) |
| 111 | ); |
| 112 | |
| 113 | if (response.status < 200 || response.status >= 300) { |
| 114 | const pretty = yield* response.json.pipe( |
| 115 | Effect.map(json => |
| 116 | Predicate.isObject(json) ? renderPrettyError(EffectRecord.toEntries(json)) : '' |
| 117 | ), |
| 118 | Effect.catch(() => Effect.succeed('')) |
| 119 | ); |
| 120 | |
| 121 | const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`; |
| 122 | return yield* Effect.fail( |
| 123 | new UpgradeBinaryError({ |
| 124 | cause, |
| 125 | message: fetchErrorMessage, |
| 126 | }) |
| 127 | ); |
| 128 | } |
| 129 | |
| 130 | return yield* HttpClientResponse.schemaBodyJson(GitHubRelease)(response).pipe( |
| 131 | Effect.mapError( |
| 132 | cause => |
| 133 | new UpgradeBinaryError({ |
| 134 | cause, |
| 135 | message: 'Failed to parse GitHub release JSON response', |
| 136 | }) |
| 137 | ) |
| 138 | ); |
| 139 | }); |
| 140 | |
| 141 | const fetchLatestRelease = ( |
| 142 | ctx: UpgradeBinaryContext, |
| 143 | platformArch: PlatformArch, |
| 144 | options: { |
| 145 | prerelease?: boolean; |
| 146 | tag?: string; |
| 147 | } = {} |
| 148 | ): Effect.Effect<GitHubRelease, UpgradeBinaryError, NodeOs> => |
| 149 | Effect.gen(function* () { |
| 150 | const { githubConfig, httpClient } = ctx; |
| 151 | const prerelease = options.prerelease ?? false; |
| 152 | const explicitTag = Option.fromNullishOr(options.tag ?? githubConfig.tag); |
| 153 | const release = yield* explicitTag.pipe( |
| 154 | Option.match({ |
| 155 | onNone: Effect.fn(function* () { |
| 156 | yield* Effect.logDebug( |
| 157 | `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release` |
| 158 | ); |
| 159 | const latest = yield* fetchLatestCliRelease({ |
| 160 | assetDescription: getBinaryAssetName(platformArch), |
| 161 | channel: prerelease ? 'beta' : 'stable', |
| 162 | githubConfig, |
| 163 | hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch), |
| 164 | httpClient, |
| 165 | }).pipe( |
| 166 | Effect.mapError( |
| 167 | error => |
| 168 | new UpgradeBinaryError({ |
| 169 | cause: error, |
| 170 | message: Match.value(error.reason).pipe( |
| 171 | Match.when('request', () => 'Failed to fetch releases from GitHub'), |
| 172 | Match.when('http-status', () => 'Failed to fetch releases from GitHub'), |
| 173 | Match.when('decode', () => 'Failed to parse GitHub releases JSON response'), |
| 174 | Match.when( |
| 175 | 'not-found', |
| 176 | () => |
| 177 | `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub` |
| 178 | ), |
| 179 | Match.when( |
| 180 | 'compare', |
| 181 | () => |
| 182 | `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub` |
| 183 | ), |
| 184 | Match.exhaustive |
| 185 | ), |
| 186 | }) |
| 187 | ) |
| 188 | ); |
| 189 | |
| 190 | yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`); |
| 191 | // Only an unpinned stable lookup answers what the update-check cache stores. |
| 192 | if (!prerelease) { |
| 193 | yield* provideFsAndPath(ctx, recordLatestStableRelease(latest.tag_name)); |
| 194 | } |
| 195 | return latest; |
| 196 | }), |
| 197 | onSome: Effect.fn(function* (tag) { |
| 198 | yield* Effect.logDebug(`Using tag: ${tag}`); |
| 199 | const release = yield* fetchGitHubRelease(ctx, tag); |
| 200 | |
| 201 | return release; |
| 202 | }), |
| 203 | }) |
| 204 | ); |
| 205 | return release; |
| 206 | }); |
| 207 | |
| 208 | const provideFsAndPath = <A, E, R>( |
| 209 | { fs, path }: Pick<UpgradeBinaryContext, 'fs' | 'path'>, |
| 210 | effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path | R> |
| 211 | ) => |
| 212 | effect.pipe( |
| 213 | Effect.provideService(FileSystem.FileSystem, fs), |
| 214 | Effect.provideService(Path.Path, path) |
| 215 | ); |
| 216 | |
| 217 | /** |
| 218 | * Check if update is available |
| 219 | */ |
| 220 | const resolveCurrentReleaseIdentifier = (ctx: UpgradeBinaryContext, currentPath: string) => |
| 221 | provideFsAndPath(ctx, resolveRunningCliReleaseTag(currentPath, APP_VERSION)); |
| 222 | |
| 223 | const isUpdateAvailable = ( |
| 224 | release: GitHubRelease, |
| 225 | currentReleaseIdentifier: string |
| 226 | ): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> => |
| 227 | Effect.gen(function* () { |
| 228 | // Current version is older than latest |
| 229 | const isVersionOutdated = (comparison: number) => comparison < 0; |
| 230 | const comparison = yield* semverComparator(currentReleaseIdentifier, release.tag_name); |
| 231 | return isVersionOutdated(comparison); |
| 232 | }); |
| 233 | |
| 234 | type DownloadProgress = { |
| 235 | readonly receivedBytes: number; |
| 236 | readonly totalBytes: number | undefined; |
| 237 | }; |
| 238 | |
| 239 | type DownloadProgressReporter = (progress: DownloadProgress) => Effect.Effect<void>; |
| 240 | |
| 241 | // Fast enough to look live, slow enough not to thrash the spinner. |
| 242 | const DOWNLOAD_PROGRESS_INTERVAL_MILLIS = 250; |
| 243 | |
| 244 | const MEGABYTE = 1_000_000; |
| 245 | |
| 246 | export const formatMegabytes = (bytes: number): string => `${(bytes / MEGABYTE).toFixed(1)} MB`; |
| 247 | |
| 248 | /** |
| 249 | * Human-readable transfer state. Falls back to a plain byte count when the |
| 250 | * server never told us how large the asset is. |
| 251 | */ |
| 252 | export const formatDownloadProgress = ({ receivedBytes, totalBytes }: DownloadProgress): string => { |
| 253 | if (totalBytes === undefined || totalBytes <= 0) { |
| 254 | return `Downloading... ${formatMegabytes(receivedBytes)}`; |
| 255 | } |
| 256 | |
| 257 | const percent = Math.min(100, Math.floor((receivedBytes / totalBytes) * 100)); |
| 258 | return `Downloading... ${percent}% (${formatMegabytes(receivedBytes)} / ${formatMegabytes(totalBytes)})`; |
| 259 | }; |
| 260 | |
| 261 | const resolveDownloadTotalBytes = ( |
| 262 | asset: { readonly size?: number }, |
| 263 | response: HttpClientResponse.HttpClientResponse |
| 264 | ): number | undefined => { |
| 265 | if (typeof asset.size === 'number' && asset.size > 0) { |
| 266 | return asset.size; |
| 267 | } |
| 268 | |
| 269 | const header = response.headers['content-length']; |
| 270 | const parsed = header === undefined ? Number.NaN : Number.parseInt(header, 10); |
| 271 | return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined; |
| 272 | }; |
| 273 | |
| 274 | /** |
| 275 | * Download binary for current platform |
| 276 | */ |
| 277 | const downloadBinary = ( |
| 278 | { httpClient }: UpgradeBinaryContext, |
| 279 | release: GitHubRelease, |
| 280 | platformArch: PlatformArch, |
| 281 | onProgress: DownloadProgressReporter = () => Effect.void |
| 282 | ): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> => |
| 283 | Effect.gen(function* () { |
| 284 | yield* Effect.logDebug(`Looking up binary for ${platformArch.platform}-${platformArch.arch}`); |
| 285 | |
| 286 | const binaryName = getBinaryAssetName(platformArch); |
| 287 | |
| 288 | const asset = release.assets.find(asset => asset.name === binaryName); |
| 289 | if (!asset) { |
| 290 | return yield* Effect.fail( |
| 291 | new UpgradeBinaryError({ |
| 292 | cause: `Binary not found: ${binaryName}`, |
| 293 | message: `No binary available for ${platformArch.platform}-${platformArch.arch}`, |
| 294 | }) |
| 295 | ); |
| 296 | } |
| 297 | |
| 298 | yield* Effect.logDebug(`Downloading ${asset.name}...`); |
| 299 | |
| 300 | const response = yield* Effect.gen(function* () { |
| 301 | const resp = yield* httpClient.get(asset.browser_download_url).pipe( |
| 302 | Effect.mapError( |
| 303 | cause => |
| 304 | new UpgradeBinaryError({ |
| 305 | cause, |
| 306 | message: `Failed to download binary: ${asset.name}`, |
| 307 | }) |
| 308 | ) |
| 309 | ); |
| 310 | if (resp.status < 200 || resp.status >= 300) { |
| 311 | return yield* Effect.fail( |
| 312 | new UpgradeBinaryError({ |
| 313 | cause: `HTTP ${resp.status}`, |
| 314 | message: `Failed to download binary: ${asset.name}`, |
| 315 | }) |
| 316 | ); |
| 317 | } |
| 318 | return resp; |
| 319 | }); |
| 320 | |
| 321 | // Streamed rather than buffered so the transfer can be reported as it runs: |
| 322 | // these archives are hundreds of megabytes, and a silent multi-minute wait |
| 323 | // is indistinguishable from a hung command. |
| 324 | const totalBytes = resolveDownloadTotalBytes(asset, response); |
| 325 | |
| 326 | const parts: Array<Uint8Array> = []; |
| 327 | let receivedBytes = 0; |
| 328 | let lastReportedAt = 0; |
| 329 | |
| 330 | yield* response.stream.pipe( |
| 331 | Stream.runForEach(chunk => { |
| 332 | parts.push(chunk); |
| 333 | receivedBytes += chunk.length; |
| 334 | |
| 335 | const now = Date.now(); |
| 336 | if (now - lastReportedAt < DOWNLOAD_PROGRESS_INTERVAL_MILLIS) { |
| 337 | return Effect.void; |
| 338 | } |
| 339 | lastReportedAt = now; |
| 340 | return onProgress({ receivedBytes, totalBytes }); |
| 341 | }), |
| 342 | Effect.mapError( |
| 343 | cause => |
| 344 | new UpgradeBinaryError({ |
| 345 | cause, |
| 346 | message: 'Failed to read downloaded binary', |
| 347 | }) |
| 348 | ) |
| 349 | ); |
| 350 | |
| 351 | yield* onProgress({ receivedBytes, totalBytes: totalBytes ?? receivedBytes }); |
| 352 | |
| 353 | const data = new Uint8Array(receivedBytes); |
| 354 | let offset = 0; |
| 355 | for (const part of parts) { |
| 356 | data.set(part, offset); |
| 357 | offset += part.length; |
| 358 | } |
| 359 | |
| 360 | return { |
| 361 | name: binaryName, |
| 362 | data, |
| 363 | }; |
| 364 | }); |
| 365 | |
| 366 | /** |
| 367 | * Fetch checksums.txt from a release, if available. |
| 368 | * Returns the parsed map of filename -> expected SHA-256 hash, or None if not found. |
| 369 | */ |
| 370 | const fetchChecksums = ( |
| 371 | { httpClient }: UpgradeBinaryContext, |
| 372 | release: GitHubRelease |
| 373 | ): Effect.Effect<Option.Option<Map<string, string>>, never, never> => |
| 374 | Effect.gen(function* () { |
| 375 | const checksumsAsset = release.assets.find(a => a.name === 'checksums.txt'); |
| 376 | if (!checksumsAsset) { |
| 377 | yield* Effect.logDebug('No checksums.txt found in release assets'); |
| 378 | return Option.none(); |
| 379 | } |
| 380 | |
| 381 | const response = yield* httpClient |
| 382 | .get(checksumsAsset.browser_download_url) |
| 383 | .pipe(Effect.catch(() => Effect.succeed(null))); |
| 384 | |
| 385 | if (!response || response.status < 200 || response.status >= 300) { |
| 386 | yield* Effect.logDebug('Failed to download checksums.txt'); |
| 387 | return Option.none(); |
| 388 | } |
| 389 | |
| 390 | const text = yield* response.text.pipe(Effect.catch(() => Effect.succeed(''))); |
| 391 | if (!text) { |
| 392 | return Option.none(); |
| 393 | } |
| 394 | |
| 395 | return Option.some(parseChecksumsText(text)); |
| 396 | }); |
| 397 | |
| 398 | /** |
| 399 | * Verify SHA-256 checksum of downloaded data against expected hash. |
| 400 | */ |
| 401 | const verifyChecksum = ( |
| 402 | data: Uint8Array, |
| 403 | expectedHash: string, |
| 404 | fileName: string |
| 405 | ): Effect.Effect<void, UpgradeBinaryError> => |
| 406 | Effect.gen(function* () { |
| 407 | const actual = yield* Effect.tryPromise({ |
| 408 | try: () => sha256Hex(data), |
| 409 | catch: error => |
| 410 | new UpgradeBinaryError({ |
| 411 | cause: error, |
| 412 | message: 'Failed to compute SHA-256 checksum', |
| 413 | }), |
| 414 | }); |
| 415 | |
| 416 | if (actual !== expectedHash) { |
| 417 | return yield* Effect.fail( |
| 418 | new UpgradeBinaryError({ |
| 419 | message: `Checksum mismatch for ${fileName}\n Expected: ${expectedHash}\n Actual: ${actual}`, |
| 420 | }) |
| 421 | ); |
| 422 | } |
| 423 | |
| 424 | yield* Effect.logDebug(`Checksum verified for ${fileName}`); |
| 425 | }); |
| 426 | |
| 427 | /** |
| 428 | * Extract binary from zip archive using FileSystem |
| 429 | */ |
| 430 | const extractBinary = ( |
| 431 | { fs, path, platform }: UpgradeBinaryContext, |
| 432 | { name, data }: { name: string; data: Uint8Array }, |
| 433 | tempDir: string |
| 434 | ): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> => |
| 435 | Effect.gen(function* () { |
| 436 | const zipPath = path.join(tempDir, name); |
| 437 | const extractDir = path.join(tempDir, 'extract'); |
| 438 | const packageDir = path.join(extractDir, path.parse(name).name); |
| 439 | const binaryPath = path.join( |
| 440 | packageDir, |
| 441 | platform === 'win32' ? `${CLI_BINARY_NAME}.exe` : CLI_BINARY_NAME |
| 442 | ); |
| 443 | |
| 444 | yield* Effect.logDebug(`Download zip to ${extractDir}`); |
| 445 | |
| 446 | // Write zip file |
| 447 | yield* fs.writeFile(zipPath, data).pipe( |
| 448 | Effect.mapError( |
| 449 | cause => |
| 450 | new UpgradeBinaryError({ |
| 451 | cause, |
| 452 | message: 'Failed to write zip file', |
| 453 | }) |
| 454 | ) |
| 455 | ); |
| 456 | |
| 457 | // Create extract directory |
| 458 | yield* fs.makeDirectory(extractDir, { recursive: true }).pipe( |
| 459 | Effect.mapError( |
| 460 | cause => |
| 461 | new UpgradeBinaryError({ |
| 462 | cause, |
| 463 | message: 'Failed to create extract directory', |
| 464 | }) |
| 465 | ) |
| 466 | ); |
| 467 | |
| 468 | yield* Effect.tryPromise({ |
| 469 | try: async () => { |
| 470 | await extractZipSafely(zipPath, extractDir); |
| 471 | }, |
| 472 | catch: error => |
| 473 | new UpgradeBinaryError({ |
| 474 | cause: error, |
| 475 | message: 'Failed to extract zip archive', |
| 476 | }), |
| 477 | }); |
| 478 | |
| 479 | // Check if binary exists |
| 480 | const exists = yield* fs.exists(binaryPath).pipe(Effect.catch(() => Effect.succeed(false))); |
| 481 | |
| 482 | if (!exists) { |
| 483 | return yield* Effect.fail( |
| 484 | new UpgradeBinaryError({ |
| 485 | cause: `Binary not found in archive: ${binaryPath}`, |
| 486 | message: 'Extracted archive does not contain expected binary', |
| 487 | }) |
| 488 | ); |
| 489 | } |
| 490 | |
| 491 | // Make executable |
| 492 | yield* fs.chmod(binaryPath, 0o755).pipe( |
| 493 | Effect.mapError( |
| 494 | cause => |
| 495 | new UpgradeBinaryError({ |
| 496 | cause, |
| 497 | message: 'Failed to make binary executable', |
| 498 | }) |
| 499 | ) |
| 500 | ); |
| 501 | |
| 502 | return { |
| 503 | binaryPath, |
| 504 | packageDir, |
| 505 | }; |
| 506 | }); |
| 507 | |
| 508 | /** |
| 509 | * Get current executable path |
| 510 | */ |
| 511 | const getCurrentExecutablePath = Effect.fn(function* () { |
| 512 | // E.g., ~/.composio/composio |
| 513 | const currentPath = process.execPath; |
| 514 | |
| 515 | const runtimesPaths: Array<string | null> = [Bun.which('bun'), Bun.which('node')]; |
| 516 | |
| 517 | if (runtimesPaths.includes(currentPath)) { |
| 518 | return yield* Effect.fail( |
| 519 | new UpgradeBinaryError({ |
| 520 | cause: 'Currently using Composio CLI via Bun or Node.js runtime', |
| 521 | message: |
| 522 | 'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.', |
| 523 | }) |
| 524 | ); |
| 525 | } |
| 526 | |
| 527 | return currentPath; |
| 528 | }); |
| 529 | |
| 530 | /** |
| 531 | * Replace current executable binary with the new target one. |
| 532 | */ |
| 533 | const mapAtomicReplaceError = (message: string) => (error: AtomicReplaceError) => |
| 534 | new UpgradeBinaryError({ |
| 535 | cause: error.cause, |
| 536 | message: `${message}: ${error.message}`, |
| 537 | }); |
| 538 | |
| 539 | const ensureUpgradeAllowedFrom = ( |
| 540 | { minimumUpgradeFrom }: ReleaseManifest, |
| 541 | currentVersion: Option.Option<string>, |
| 542 | platform: NodeJS.Platform |
| 543 | ): Effect.Effect<void, UpgradeBelowMinimumError | UpgradeBinaryError> => |
| 544 | Effect.gen(function* () { |
| 545 | if (Option.isNone(currentVersion)) { |
| 546 | return yield* Effect.logDebug( |
| 547 | `Running version unknown; not checking the archive's minimum of ${minimumUpgradeFrom}` |
| 548 | ); |
| 549 | } |
| 550 | const current = currentVersion.value; |
| 551 | const comparison = yield* semverComparator(current, minimumUpgradeFrom).pipe( |
| 552 | Effect.mapError( |
| 553 | cause => |
| 554 | new UpgradeBinaryError({ |
| 555 | cause, |
| 556 | message: `Cannot compare the running version ${current} with the release's minimum ${minimumUpgradeFrom}`, |
| 557 | }) |
| 558 | ) |
| 559 | ); |
| 560 | if (comparison < 0) { |
| 561 | return yield* new UpgradeBelowMinimumError({ |
| 562 | currentVersion: current, |
| 563 | minimumUpgradeFrom, |
| 564 | message: [ |
| 565 | `This release can only be installed over Composio CLI ${minimumUpgradeFrom} or newer, and this CLI is ${current}.`, |
| 566 | 'Reinstall the CLI to get it:', |
| 567 | ` ${reinstallCommand(platform)}`, |
| 568 | ].join('\n'), |
| 569 | }); |
| 570 | } |
| 571 | }); |
| 572 | |
| 573 | const syncInstalledReleaseManifest = ( |
| 574 | ctx: Pick<UpgradeBinaryContext, 'fs' | 'path'>, |
| 575 | archiveCompanions: ArchiveCompanions, |
| 576 | sourceDirectory: string, |
| 577 | targetDirectory: string |
| 578 | ) => { |
| 579 | const installedManifestPath = ctx.path.join(targetDirectory, RELEASE_MANIFEST_FILENAME); |
| 580 | if (ArchiveCompanions.$is('CompiledNames')(archiveCompanions)) { |
| 581 | return ctx.fs.remove(installedManifestPath, { force: true }).pipe( |
| 582 | Effect.mapError( |
| 583 | cause => |
| 584 | new UpgradeBinaryError({ |
| 585 | cause, |
| 586 | message: `Failed to remove the previous release manifest: ${installedManifestPath}`, |
| 587 | }) |
| 588 | ) |
| 589 | ); |
| 590 | } |
| 591 | return provideFsAndPath( |
| 592 | ctx, |
| 593 | atomicReplaceFile({ |
| 594 | sourcePath: ctx.path.join(sourceDirectory, RELEASE_MANIFEST_FILENAME), |
| 595 | targetPath: installedManifestPath, |
| 596 | }) |
| 597 | ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to update installed release manifest'))); |
| 598 | }; |
| 599 | |
| 600 | const replaceBinary = ( |
| 601 | ctx: Pick<UpgradeBinaryContext, 'fs' | 'path' | 'platform'>, |
| 602 | sourcePath: string, |
| 603 | targetPath: string, |
| 604 | options: { |
| 605 | releaseTag?: string; |
| 606 | currentVersion: Option.Option<string>; |
| 607 | } |
| 608 | ): Effect.Effect<void, UpgradeBinaryError | UpgradeBelowMinimumError, Scope.Scope> => |
| 609 | Effect.gen(function* () { |
| 610 | const { fs, path } = ctx; |
| 611 | yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`); |
| 612 | |
| 613 | const sourceDirectory = path.dirname(sourcePath); |
| 614 | const targetDirectory = path.dirname(targetPath); |
| 615 | const archiveCompanions = yield* provideFsAndPath( |
| 616 | ctx, |
| 617 | resolveArchiveCompanions(sourceDirectory) |
| 618 | ).pipe( |
| 619 | Effect.mapError( |
| 620 | error => |
| 621 | new UpgradeBinaryError({ |
| 622 | cause: error.cause, |
| 623 | message: `Downloaded binary package is invalid: ${error.message}. Reinstall the CLI: ${reinstallCommand(ctx.platform)}`, |
| 624 | }) |
| 625 | ) |
| 626 | ); |
| 627 | if (ArchiveCompanions.$is('Manifest')(archiveCompanions)) { |
| 628 | yield* ensureUpgradeAllowedFrom( |
| 629 | archiveCompanions.manifest, |
| 630 | options.currentVersion, |
| 631 | ctx.platform |
| 632 | ); |
| 633 | } |
| 634 | |
| 635 | const companionReplacements: Array<{ |
| 636 | readonly relativePath: string; |
| 637 | readonly sourcePath: string; |
| 638 | readonly targetPath: string; |
| 639 | }> = []; |
| 640 | |
| 641 | for (const relativePath of archiveCompanions.relativePaths) { |
| 642 | const sourceCompanion = path.join(sourceDirectory, relativePath); |
| 643 | const sourceExists = yield* fs |
| 644 | .exists(sourceCompanion) |
| 645 | .pipe(Effect.catch(() => Effect.succeed(false))); |
| 646 | |
| 647 | if (!sourceExists) { |
| 648 | return yield* Effect.fail( |
| 649 | new UpgradeBinaryError({ |
| 650 | cause: `Missing companion module: ${sourceCompanion}`, |
| 651 | message: 'Downloaded binary package is incomplete', |
| 652 | }) |
| 653 | ); |
| 654 | } |
| 655 | |
| 656 | companionReplacements.push({ |
| 657 | relativePath, |
| 658 | sourcePath: sourceCompanion, |
| 659 | targetPath: path.join(targetDirectory, relativePath), |
| 660 | }); |
| 661 | } |
| 662 | |
| 663 | if (ctx.platform === 'win32') { |
| 664 | // Windows keeps the previous executable locked until its process has fully exited, |
| 665 | // which can be a moment after an upgrade that just ran returns. |
| 666 | yield* fs.remove(`${targetPath}.old`, { force: true }).pipe( |
| 667 | Effect.retry({ times: 10, schedule: Schedule.spaced('200 millis') }), |
| 668 | Effect.mapError( |
| 669 | cause => |
| 670 | new UpgradeBinaryError({ |
| 671 | cause, |
| 672 | message: |
| 673 | 'Could not remove the previous executable backup. Close other Composio processes and retry.', |
| 674 | }) |
| 675 | ) |
| 676 | ); |
| 677 | } |
| 678 | |
| 679 | const releaseTag = options.releaseTag; |
| 680 | const stagedReleaseTagPath = path.join(sourceDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME); |
| 681 | if (releaseTag) { |
| 682 | yield* provideFsAndPath(ctx, writeInstalledReleaseTag(sourceDirectory, releaseTag)).pipe( |
| 683 | Effect.mapError( |
| 684 | error => |
| 685 | new UpgradeBinaryError({ |
| 686 | cause: error, |
| 687 | message: 'Failed to update installed release metadata', |
| 688 | }) |
| 689 | ) |
| 690 | ); |
| 691 | } |
| 692 | |
| 693 | for (const replacement of companionReplacements) { |
| 694 | const { |
| 695 | relativePath, |
| 696 | sourcePath: sourceCompanion, |
| 697 | targetPath: targetCompanion, |
| 698 | } = replacement; |
| 699 | yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe( |
| 700 | Effect.mapError( |
| 701 | cause => |
| 702 | new UpgradeBinaryError({ |
| 703 | cause, |
| 704 | message: `Failed to create companion module directory: ${relativePath}`, |
| 705 | }) |
| 706 | ) |
| 707 | ); |
| 708 | |
| 709 | yield* provideFsAndPath( |
| 710 | ctx, |
| 711 | atomicReplaceFile({ sourcePath: sourceCompanion, targetPath: targetCompanion }) |
| 712 | ).pipe( |
| 713 | Effect.mapError( |
| 714 | mapAtomicReplaceError(`Failed to replace companion module: ${relativePath}`) |
| 715 | ) |
| 716 | ); |
| 717 | } |
| 718 | |
| 719 | yield* syncInstalledReleaseManifest(ctx, archiveCompanions, sourceDirectory, targetDirectory); |
| 720 | |
| 721 | if (releaseTag) { |
| 722 | yield* provideFsAndPath( |
| 723 | ctx, |
| 724 | atomicReplaceFile({ |
| 725 | sourcePath: stagedReleaseTagPath, |
| 726 | targetPath: path.join(targetDirectory, RUN_COMPANION_RELEASE_TAG_FILENAME), |
| 727 | }) |
| 728 | ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to update installed release metadata'))); |
| 729 | } |
| 730 | |
| 731 | yield* provideFsAndPath( |
| 732 | ctx, |
| 733 | atomicReplaceFile({ |
| 734 | sourcePath, |
| 735 | targetPath, |
| 736 | mode: 0o755, |
| 737 | backupPath: ctx.platform === 'win32' ? `${targetPath}.old` : undefined, |
| 738 | }) |
| 739 | ).pipe(Effect.mapError(mapAtomicReplaceError('Failed to replace binary'))); |
| 740 | |
| 741 | const legacyLocalToolsPath = path.join(targetDirectory, LEGACY_LOCAL_TOOLS_DIRNAME); |
| 742 | yield* fs |
| 743 | .remove(legacyLocalToolsPath, { recursive: true, force: true }) |
| 744 | .pipe( |
| 745 | Effect.catch(cause => |
| 746 | Effect.logDebug(`Could not remove obsolete ${legacyLocalToolsPath}: ${String(cause)}`) |
| 747 | ) |
| 748 | ); |
| 749 | }); |
| 750 | |
| 751 | /** |
| 752 | * Main upgrade function |
| 753 | */ |
| 754 | const upgrade = ( |
| 755 | ctx: UpgradeBinaryContext, |
| 756 | options: { |
| 757 | prerelease?: boolean; |
| 758 | tag?: string; |
| 759 | } = {} |
| 760 | ) => |
| 761 | Effect.gen(function* () { |
| 762 | const ui = yield* TerminalUI; |
| 763 | const upgradeTarget = yield* DEBUG_CONFIG.UPGRADE_TARGET; |
| 764 | const currentPath = yield* getCurrentExecutablePath(); |
| 765 | const prerelease = options.prerelease ?? false; |
| 766 | const explicitTag = options.tag; |
| 767 | const currentReleaseIdentifier = yield* resolveCurrentReleaseIdentifier(ctx, currentPath); |
| 768 | const currentVersion = yield* provideFsAndPath( |
| 769 | ctx, |
| 770 | resolveRecordedRunningCliVersion(currentPath, APP_VERSION) |
| 771 | ); |
| 772 | yield* Effect.logDebug(`Current executable path: ${currentPath}`); |
| 773 | yield* Effect.logDebug(`Current release identifier: ${currentReleaseIdentifier}`); |
| 774 | |
| 775 | yield* ui.intro('composio upgrade'); |
| 776 | |
| 777 | // If local binary path is provided (for testing), use it directly |
| 778 | if (upgradeTarget !== undefined) { |
| 779 | yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`); |
| 780 | yield* replaceBinary(ctx, upgradeTarget, currentPath, { |
| 781 | releaseTag: explicitTag, |
| 782 | currentVersion, |
| 783 | }); |
| 784 | yield* ui.outro('Upgrade completed'); |
| 785 | return undefined; |
| 786 | } |
| 787 | |
| 788 | const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner => |
| 789 | Effect.gen(function* () { |
| 790 | const platformArch = yield* detectPlatform; |
| 791 | const release = yield* fetchLatestRelease(ctx, platformArch, { |
| 792 | prerelease, |
| 793 | tag: explicitTag, |
| 794 | }); |
| 795 | if (!explicitTag) { |
| 796 | const updateAvailable = yield* isUpdateAvailable(release, currentReleaseIdentifier); |
| 797 | if (!updateAvailable) { |
| 798 | yield* spinner.stop('You are already running the latest version!'); |
| 799 | return false; |
| 800 | } |
| 801 | } else if (release.tag_name === currentReleaseIdentifier) { |
| 802 | yield* Effect.logDebug(`Already running ${release.tag_name}; re-installing as requested`); |
| 803 | } |
| 804 | |
| 805 | yield* spinner.message( |
| 806 | explicitTag |
| 807 | ? `Installing ${release.tag_name} (current: ${currentReleaseIdentifier})...` |
| 808 | : `New version available: ${release.tag_name} (current: ${currentReleaseIdentifier}). Downloading...` |
| 809 | ); |
| 810 | |
| 811 | const { name, data } = yield* downloadBinary(ctx, release, platformArch, progress => |
| 812 | spinner.message(formatDownloadProgress(progress)) |
| 813 | ); |
| 814 | |
| 815 | yield* spinner.message('Verifying checksum...'); |
| 816 | |
| 817 | const checksums = yield* fetchChecksums(ctx, release); |
| 818 | if (Option.isSome(checksums)) { |
| 819 | const expectedHash = checksums.value.get(name); |
| 820 | if (expectedHash) { |
| 821 | yield* verifyChecksum(data, expectedHash, name); |
| 822 | } else { |
| 823 | yield* Effect.logDebug(`No checksum entry found for ${name} — skipping verification`); |
| 824 | } |
| 825 | } |
| 826 | |
| 827 | yield* spinner.message('Extracting...'); |
| 828 | |
| 829 | // The temporary directory is automatically cleaned up |
| 830 | const tmpDir = yield* ctx.fs |
| 831 | .makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade` }) |
| 832 | .pipe( |
| 833 | Effect.mapError( |
| 834 | cause => |
| 835 | new UpgradeBinaryError({ |
| 836 | cause, |
| 837 | message: 'Failed to create temporary directory', |
| 838 | }) |
| 839 | ) |
| 840 | ); |
| 841 | |
| 842 | const extractedBinary = yield* extractBinary(ctx, { name, data }, tmpDir); |
| 843 | yield* replaceBinary(ctx, extractedBinary.binaryPath, currentPath, { |
| 844 | releaseTag: release.tag_name, |
| 845 | currentVersion, |
| 846 | }); |
| 847 | |
| 848 | yield* spinner.stop('Upgrade completed!'); |
| 849 | return release.tag_name; |
| 850 | }) |
| 851 | ); |
| 852 | |
| 853 | yield* ui.outro( |
| 854 | didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.' |
| 855 | ); |
| 856 | |
| 857 | return didUpgrade || undefined; // release tag string, or undefined if no upgrade |
| 858 | }); |
| 859 | |
| 860 | // Service to manage CLI binary upgrades |
| 861 | const makeUpgradeBinary = Effect.gen(function* () { |
| 862 | const ctx: UpgradeBinaryContext = { |
| 863 | httpClient: yield* HttpClient.HttpClient, |
| 864 | fs: yield* FileSystem.FileSystem, |
| 865 | path: yield* Path.Path, |
| 866 | githubConfig: yield* GITHUB_CONFIG, |
| 867 | platform: (yield* NodeOs).platform, |
| 868 | }; |
| 869 | |
| 870 | return { |
| 871 | upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options), |
| 872 | } as const; |
| 873 | }); |
| 874 | |
| 875 | export type UpgradeBinaryShape = Effect.Success<typeof makeUpgradeBinary>; |
| 876 | |
| 877 | export class UpgradeBinary extends Context.Service<UpgradeBinary, UpgradeBinaryShape>()( |
| 878 | 'services/UpgradeBinary' |
| 879 | ) { |
| 880 | static readonly Default = Layer.effect(UpgradeBinary, makeUpgradeBinary).pipe( |
| 881 | Layer.provide(BunPath.layer) |
| 882 | ); |
| 883 | } |