1
-import { Data, Effect, Config, Option } from 'effect';
2
-import { HttpClient, FileSystem } from '@effect/platform';
3
-import * as path from 'node:path';
4
-import { cp as copyPath, rm as removePath } from 'node:fs/promises';
1
+import { Data, Effect, Config, Match, Option, Predicate, Record as EffectRecord } from 'effect';
2
+import { HttpClient, HttpClientResponse, FileSystem, Path } from '@effect/platform';
3
import { APP_VERSION } from '../constants';
4
import { DEBUG_OVERRIDE_CONFIG } from 'src/effects/debug-config';
5
import { GITHUB_CONFIG } from 'src/effects/github-config';
6
import { detectPlatform, type PlatformArch } from 'src/effects/detect-platform';
7
import { CompareSemverError, semverComparator } from 'src/effects/compare-semver';
10
-import { fetchLatestCliRelease, type GitHubRelease } from 'src/effects/resolve-cli-release';
8
+import { fetchLatestCliRelease, GitHubRelease } from 'src/effects/resolve-cli-release';
9
+import { parseChecksumsText, sha256Hex } from 'src/utils/checksums';
10
11
// Note: `node:zlib` does not support Github's zip files
12
import extractZip from 'extract-zip';
14
-import type { Predicate } from 'effect/Predicate';
13
import { renderPrettyError } from './utils/pretty-error';
14
import { TerminalUI } from './terminal-ui';
15
import {
35
const hasPlatformBinaryAsset = (release: GitHubRelease, platformArch: PlatformArch) =>
36
release.assets.some(asset => asset.name === getBinaryAssetName(platformArch));
37
40
-// Service to manage CLI binary upgrades
41
-export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
42
- accessors: true,
43
- // eslint-disable-next-line max-lines-per-function
44
- effect: Effect.gen(function* () {
45
- const httpClient = yield* HttpClient.HttpClient;
46
- const fs = yield* FileSystem.FileSystem;
47
- const githubConfig = yield* Config.all(GITHUB_CONFIG);
48
-
49
- /**
50
- * Fetch latest release from GitHub
51
- */
52
- const fetchGitHubJson = <T>({
53
- url,
54
- fetchErrorMessage,
55
- parseErrorMessage,
56
- }: {
57
- url: string;
58
- fetchErrorMessage: string;
59
- parseErrorMessage: string;
60
- }): Effect.Effect<T, UpgradeBinaryError, never> =>
61
- Effect.gen(function* () {
62
- yield* Effect.logDebug(`GET ${url}`);
38
+const GITHUB_CONFIG_ALL = Config.all(GITHUB_CONFIG);
39
64
- const response = yield* httpClient.get(url).pipe(
65
- Effect.catchAll(error =>
66
- Effect.fail(
67
- new UpgradeBinaryError({
68
- cause: error,
69
- message: fetchErrorMessage,
70
- })
71
- )
72
- )
73
- );
40
+// Dependencies resolved once at service construction time and threaded
41
+// through the module-level helpers below.
42
+interface UpgradeBinaryContext {
43
+ readonly httpClient: HttpClient.HttpClient;
44
+ readonly fs: FileSystem.FileSystem;
45
+ readonly path: Path.Path;
46
+ readonly githubConfig: Config.Config.Success<typeof GITHUB_CONFIG_ALL>;
47
+}
48
75
- if (response.status < 200 || response.status >= 300) {
76
- const pretty = yield* response.json.pipe(
77
- Effect.map(json => renderPrettyError(Object.entries(json as object))),
78
- Effect.catchAll(() => Effect.succeed(''))
49
+/**
50
+ * Fetch latest release from GitHub
51
+ */
52
+const fetchGitHubRelease = (
53
+ { githubConfig, httpClient }: UpgradeBinaryContext,
54
+ tag: string
55
+): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
56
+ Effect.gen(function* () {
57
+ const encodedTag = encodeURIComponent(tag);
58
+ const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodedTag}`;
59
+ const fetchErrorMessage = `Failed to fetch tags/${tag} release from GitHub`;
60
+ yield* Effect.logDebug(`GET ${url}`);
61
+
62
+ const response = yield* httpClient.get(url).pipe(
63
+ Effect.mapError(
64
+ cause =>
65
+ new UpgradeBinaryError({
66
+ cause,
67
+ message: fetchErrorMessage,
68
+ })
69
+ )
70
+ );
71
+
72
+ if (response.status < 200 || response.status >= 300) {
73
+ const pretty = yield* response.json.pipe(
74
+ Effect.map(json =>
75
+ Predicate.isRecord(json) ? renderPrettyError(EffectRecord.toEntries(json)) : ''
76
+ ),
77
+ Effect.catchAll(() => Effect.succeed(''))
78
+ );
79
+
80
+ const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
81
+ return yield* Effect.fail(
82
+ new UpgradeBinaryError({
83
+ cause,
84
+ message: fetchErrorMessage,
85
+ })
86
+ );
87
+ }
88
+
89
+ return yield* HttpClientResponse.schemaBodyJson(GitHubRelease)(response).pipe(
90
+ Effect.mapError(
91
+ cause =>
92
+ new UpgradeBinaryError({
93
+ cause,
94
+ message: 'Failed to parse GitHub release JSON response',
95
+ })
96
+ )
97
+ );
98
+ });
99
+
100
+const fetchLatestRelease = (
101
+ ctx: UpgradeBinaryContext,
102
+ platformArch: PlatformArch,
103
+ options: {
104
+ prerelease?: boolean;
105
+ tag?: string;
106
+ } = {}
107
+): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
108
+ Effect.gen(function* () {
109
+ const { githubConfig, httpClient } = ctx;
110
+ const prerelease = options.prerelease ?? false;
111
+ const explicitTag = options.tag ? Option.some(options.tag) : githubConfig.TAG;
112
+ const release = yield* explicitTag.pipe(
113
+ Option.match({
114
+ onNone: Effect.fn(function* () {
115
+ yield* Effect.logDebug(
116
+ `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`
117
);
80
-
81
- const cause = pretty ? `HTTP ${response.status}\n${pretty}` : `HTTP ${response.status}`;
82
- return yield* Effect.fail(
83
- new UpgradeBinaryError({
84
- cause,
85
- message: fetchErrorMessage,
86
- })
118
+ const latest = yield* fetchLatestCliRelease({
119
+ assetDescription: getBinaryAssetName(platformArch),
120
+ channel: prerelease ? 'beta' : 'stable',
121
+ githubConfig,
122
+ hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),
123
+ httpClient,
124
+ }).pipe(
125
+ Effect.mapError(
126
+ error =>
127
+ new UpgradeBinaryError({
128
+ cause: error,
129
+ message: Match.value(error.reason).pipe(
130
+ Match.when('request', () => 'Failed to fetch releases from GitHub'),
131
+ Match.when('http-status', () => 'Failed to fetch releases from GitHub'),
132
+ Match.when('decode', () => 'Failed to parse GitHub releases JSON response'),
133
+ Match.when(
134
+ 'not-found',
135
+ () =>
136
+ `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`
137
+ ),
138
+ Match.when(
139
+ 'compare',
140
+ () =>
141
+ `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`
142
+ ),
143
+ Match.exhaustive
144
+ ),
145
+ })
146
+ )
147
);
88
- }
148
90
- return (yield* response.json.pipe(
91
- Effect.catchAll(error =>
92
- Effect.fail(
93
- new UpgradeBinaryError({
94
- cause: error,
95
- message: parseErrorMessage,
96
- })
97
- )
98
- )
99
- )) as T;
100
- });
101
-
102
- const fetchLatestRelease = (
103
- platformArch: PlatformArch,
104
- options: {
105
- prerelease?: boolean;
106
- tag?: string;
107
- } = {}
108
- ): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
109
- Effect.gen(function* () {
110
- const prerelease = options.prerelease ?? false;
111
- const explicitTag = options.tag ? Option.some(options.tag) : githubConfig.TAG;
112
- const release = yield* explicitTag.pipe(
113
- Option.match({
114
- onNone: Effect.fn(function* () {
115
- yield* Effect.logDebug(
116
- `No tag specified, resolving latest package-scoped CLI ${prerelease ? 'beta' : 'stable'} release`
117
- );
118
- const latest = yield* fetchLatestCliRelease({
119
- assetDescription: getBinaryAssetName(platformArch),
120
- channel: prerelease ? 'beta' : 'stable',
121
- githubConfig,
122
- hasRequiredAsset: release => hasPlatformBinaryAsset(release, platformArch),
123
- httpClient,
124
- }).pipe(
125
- Effect.mapError(
126
- error =>
127
- new UpgradeBinaryError({
128
- cause: error,
129
- message: error.message.startsWith('Failed to fetch ')
130
- ? 'Failed to fetch releases from GitHub'
131
- : error.message === 'Failed to parse GitHub releases JSON'
132
- ? 'Failed to parse GitHub releases JSON response'
133
- : `Failed to determine latest CLI ${prerelease ? 'beta' : 'stable'} release from @composio/cli tags on GitHub`,
134
- })
135
- )
136
- );
137
-
138
- yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
139
- return latest;
140
- }),
141
- onSome: Effect.fn(function* (tag) {
142
- yield* Effect.logDebug(`Using tag: ${tag}`);
143
- const encodedTag = encodeURIComponent(tag);
144
- const url = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodedTag}`;
145
- const release = yield* fetchGitHubJson<GitHubRelease>({
146
- url,
147
- fetchErrorMessage: `Failed to fetch tags/${tag} release from GitHub`,
148
- parseErrorMessage: 'Failed to parse GitHub release JSON response',
149
- });
150
-
151
- return release as GitHubRelease;
152
- }),
153
- })
154
- );
155
- return release;
156
- });
157
-
158
- /**
159
- * Check if update is available
160
- */
161
- const resolveCurrentReleaseIdentifier = (currentPath: string) =>
162
- readInstalledReleaseTag(currentPath) || `@composio/cli@${APP_VERSION}`;
163
-
164
- const isUpdateAvailable = (
165
- release: GitHubRelease,
166
- currentReleaseIdentifier: string
167
- ): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> =>
168
- Effect.gen(function* () {
169
- // Current version is older than latest
170
- const isVersionOutdated: Predicate<number> = comparison => comparison < 0;
171
- const comparison = yield* semverComparator(currentReleaseIdentifier, release.tag_name);
172
- return isVersionOutdated(comparison);
173
- });
174
-
175
- /**
176
- * Download binary for current platform
177
- */
178
- const downloadBinary = (
179
- release: GitHubRelease,
180
- platformArch: PlatformArch
181
- ): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> =>
182
- Effect.gen(function* () {
183
- yield* Effect.logDebug(
184
- `Looking up binary for ${platformArch.platform}-${platformArch.arch}`
185
- );
149
+ yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
150
+ return latest;
151
+ }),
152
+ onSome: Effect.fn(function* (tag) {
153
+ yield* Effect.logDebug(`Using tag: ${tag}`);
154
+ const release = yield* fetchGitHubRelease(ctx, tag);
155
+
156
+ return release;
157
+ }),
158
+ })
159
+ );
160
+ return release;
161
+ });
162
+
163
+const provideFsAndPath = <A, E>(
164
+ { fs, path }: UpgradeBinaryContext,
165
+ effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>
166
+) =>
167
+ effect.pipe(
168
+ Effect.provideService(FileSystem.FileSystem, fs),
169
+ Effect.provideService(Path.Path, path)
170
+ );
171
187
- const binaryName = getBinaryAssetName(platformArch);
172
+/**
173
+ * Check if update is available
174
+ */
175
+const resolveCurrentReleaseIdentifier = (ctx: UpgradeBinaryContext, currentPath: string) =>
176
+ provideFsAndPath(ctx, readInstalledReleaseTag(currentPath)).pipe(
177
+ Effect.map(releaseTag => releaseTag || `@composio/cli@${APP_VERSION}`)
178
+ );
179
+
180
+const isUpdateAvailable = (
181
+ release: GitHubRelease,
182
+ currentReleaseIdentifier: string
183
+): Effect.Effect<boolean, CompareSemverError | UpgradeBinaryError, never> =>
184
+ Effect.gen(function* () {
185
+ // Current version is older than latest
186
+ const isVersionOutdated = (comparison: number) => comparison < 0;
187
+ const comparison = yield* semverComparator(currentReleaseIdentifier, release.tag_name);
188
+ return isVersionOutdated(comparison);
189
+ });
190
189
- const asset = release.assets.find(asset => asset.name === binaryName);
190
- if (!asset) {
191
- return yield* Effect.fail(
191
+/**
192
+ * Download binary for current platform
193
+ */
194
+const downloadBinary = (
195
+ { httpClient }: UpgradeBinaryContext,
196
+ release: GitHubRelease,
197
+ platformArch: PlatformArch
198
+): Effect.Effect<{ name: string; data: Uint8Array }, UpgradeBinaryError, never> =>
199
+ Effect.gen(function* () {
200
+ yield* Effect.logDebug(`Looking up binary for ${platformArch.platform}-${platformArch.arch}`);
201
+
202
+ const binaryName = getBinaryAssetName(platformArch);
203
+
204
+ const asset = release.assets.find(asset => asset.name === binaryName);
205
+ if (!asset) {
206
+ return yield* Effect.fail(
207
+ new UpgradeBinaryError({
208
+ cause: `Binary not found: ${binaryName}`,
209
+ message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
210
+ })
211
+ );
212
+ }
213
+
214
+ yield* Effect.logDebug(`Downloading ${asset.name}...`);
215
+
216
+ const response = yield* Effect.gen(function* () {
217
+ const resp = yield* httpClient.get(asset.browser_download_url).pipe(
218
+ Effect.mapError(
219
+ cause =>
220
new UpgradeBinaryError({
193
- cause: new Error(`Binary not found: ${binaryName}`),
194
- message: `No binary available for ${platformArch.platform}-${platformArch.arch}`,
221
+ cause,
222
+ message: `Failed to download binary: ${asset.name}`,
223
})
196
- );
197
- }
224
+ )
225
+ );
226
+ if (resp.status < 200 || resp.status >= 300) {
227
+ return yield* Effect.fail(
228
+ new UpgradeBinaryError({
229
+ cause: `HTTP ${resp.status}`,
230
+ message: `Failed to download binary: ${asset.name}`,
231
+ })
232
+ );
233
+ }
234
+ return resp;
235
+ });
236
199
- yield* Effect.logDebug(`Downloading ${asset.name}...`);
237
+ const arrayBuffer = yield* Effect.gen(function* () {
238
+ return yield* response.arrayBuffer;
239
+ }).pipe(
240
+ Effect.mapError(
241
+ cause =>
242
+ new UpgradeBinaryError({
243
+ cause,
244
+ message: 'Failed to read downloaded binary',
245
+ })
246
+ )
247
+ );
248
201
- const response = yield* Effect.gen(function* () {
202
- const resp = yield* httpClient.get(asset.browser_download_url);
203
- if (resp.status < 200 || resp.status >= 300) {
204
- return yield* Effect.fail(
205
- new UpgradeBinaryError({
206
- cause: new Error(`HTTP ${resp.status}`),
207
- message: `Failed to download binary: ${asset.name}`,
208
- })
209
- );
210
- }
211
- return resp;
212
- }).pipe(
213
- Effect.catchAll(error =>
214
- Effect.fail(
215
- new UpgradeBinaryError({
216
- cause: new Error(String(error)),
217
- message: `Failed to download binary: ${asset.name}`,
218
- })
219
- )
220
- )
221
- );
249
+ return {
250
+ name: binaryName,
251
+ data: new Uint8Array(arrayBuffer),
252
+ };
253
+ });
254
223
- const arrayBuffer = yield* Effect.gen(function* () {
224
- return yield* response.arrayBuffer;
225
- }).pipe(
226
- Effect.catchAll(error =>
227
- Effect.fail(
228
- new UpgradeBinaryError({
229
- cause: error as Error,
230
- message: 'Failed to read downloaded binary',
231
- })
232
- )
233
- )
234
- );
255
+/**
256
+ * Fetch checksums.txt from a release, if available.
257
+ * Returns the parsed map of filename -> expected SHA-256 hash, or None if not found.
258
+ */
259
+const fetchChecksums = (
260
+ { httpClient }: UpgradeBinaryContext,
261
+ release: GitHubRelease
262
+): Effect.Effect<Option.Option<Map<string, string>>, never, never> =>
263
+ Effect.gen(function* () {
264
+ const checksumsAsset = release.assets.find(a => a.name === 'checksums.txt');
265
+ if (!checksumsAsset) {
266
+ yield* Effect.logDebug('No checksums.txt found in release assets');
267
+ return Option.none();
268
+ }
269
+
270
+ const response = yield* httpClient
271
+ .get(checksumsAsset.browser_download_url)
272
+ .pipe(Effect.catchAll(() => Effect.succeed(null)));
273
+
274
+ if (!response || response.status < 200 || response.status >= 300) {
275
+ yield* Effect.logDebug('Failed to download checksums.txt');
276
+ return Option.none();
277
+ }
278
+
279
+ const text = yield* response.text.pipe(Effect.catchAll(() => Effect.succeed('')));
280
+ if (!text) {
281
+ return Option.none();
282
+ }
283
+
284
+ return Option.some(parseChecksumsText(text));
285
+ });
286
236
- return {
237
- name: binaryName,
238
- data: new Uint8Array(arrayBuffer),
239
- };
240
- });
241
-
242
- /**
243
- * Fetch checksums.txt from a release, if available.
244
- * Returns the parsed map of filename -> expected SHA-256 hash, or None if not found.
245
- */
246
- const fetchChecksums = (
247
- release: GitHubRelease
248
- ): Effect.Effect<Option.Option<Map<string, string>>, never, never> =>
249
- Effect.gen(function* () {
250
- const checksumsAsset = release.assets.find(a => a.name === 'checksums.txt');
251
- if (!checksumsAsset) {
252
- yield* Effect.logDebug('No checksums.txt found in release assets');
253
- return Option.none();
254
- }
287
+/**
288
+ * Verify SHA-256 checksum of downloaded data against expected hash.
289
+ */
290
+const verifyChecksum = (
291
+ data: Uint8Array,
292
+ expectedHash: string,
293
+ fileName: string
294
+): Effect.Effect<void, UpgradeBinaryError> =>
295
+ Effect.gen(function* () {
296
+ const actual = yield* Effect.tryPromise({
297
+ try: () => sha256Hex(data),
298
+ catch: error =>
299
+ new UpgradeBinaryError({
300
+ cause: error,
301
+ message: 'Failed to compute SHA-256 checksum',
302
+ }),
303
+ });
304
256
- const response = yield* httpClient
257
- .get(checksumsAsset.browser_download_url)
258
- .pipe(Effect.catchAll(() => Effect.succeed(null)));
305
+ if (actual !== expectedHash) {
306
+ return yield* Effect.fail(
307
+ new UpgradeBinaryError({
308
+ message: `Checksum mismatch for ${fileName}\n Expected: ${expectedHash}\n Actual: ${actual}`,
309
+ })
310
+ );
311
+ }
312
260
- if (!response || response.status < 200 || response.status >= 300) {
261
- yield* Effect.logDebug('Failed to download checksums.txt');
262
- return Option.none();
263
- }
313
+ yield* Effect.logDebug(`Checksum verified for ${fileName}`);
314
+ });
315
265
- const text = yield* response.text.pipe(Effect.catchAll(() => Effect.succeed('')));
266
- if (!text) {
267
- return Option.none();
268
- }
316
+/**
317
+ * Extract binary from zip archive using FileSystem
318
+ */
319
+const extractBinary = (
320
+ { fs, path }: UpgradeBinaryContext,
321
+ { name, data }: { name: string; data: Uint8Array },
322
+ tempDir: string
323
+): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
324
+ Effect.gen(function* () {
325
+ const zipPath = path.join(tempDir, name);
326
+ const extractDir = path.join(tempDir, 'extract');
327
+ const packageDir = path.join(extractDir, path.parse(name).name);
328
+ const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
329
+
330
+ yield* Effect.logDebug(`Download zip to ${extractDir}`);
331
+
332
+ // Write zip file
333
+ yield* fs.writeFile(zipPath, data).pipe(
334
+ Effect.mapError(
335
+ cause =>
336
+ new UpgradeBinaryError({
337
+ cause,
338
+ message: 'Failed to write zip file',
339
+ })
340
+ )
341
+ );
342
270
- const checksums = new Map<string, string>();
271
- for (const line of text.split('\n')) {
272
- const trimmed = line.trim();
273
- if (!trimmed) continue;
274
- // Format: "<hash> <filename>" (two spaces, sha256sum compatible)
275
- const parts = trimmed.split(/\s+/);
276
- if (parts.length >= 2) {
277
- checksums.set(parts[1], parts[0]);
278
- }
279
- }
343
+ // Create extract directory
344
+ yield* fs.makeDirectory(extractDir, { recursive: true }).pipe(
345
+ Effect.mapError(
346
+ cause =>
347
+ new UpgradeBinaryError({
348
+ cause,
349
+ message: 'Failed to create extract directory',
350
+ })
351
+ )
352
+ );
353
+
354
+ yield* Effect.tryPromise({
355
+ try: async () => {
356
+ await extractZip(zipPath, { dir: extractDir });
357
+ },
358
+ catch: error =>
359
+ new UpgradeBinaryError({
360
+ cause: error,
361
+ message: 'Failed to extract zip archive',
362
+ }),
363
+ });
364
281
- return Option.some(checksums);
282
- });
283
-
284
- /**
285
- * Verify SHA-256 checksum of downloaded data against expected hash.
286
- */
287
- const verifyChecksum = (
288
- data: Uint8Array,
289
- expectedHash: string,
290
- fileName: string
291
- ): Effect.Effect<void, UpgradeBinaryError> =>
292
- Effect.gen(function* () {
293
- const hashBuffer = yield* Effect.tryPromise({
294
- try: () => {
295
- // Copy into a fresh ArrayBuffer to avoid SharedArrayBuffer type incompatibility
296
- const buf = new ArrayBuffer(data.byteLength);
297
- new Uint8Array(buf).set(data);
298
- return crypto.subtle.digest('SHA-256', buf);
299
- },
300
- catch: error =>
301
- new UpgradeBinaryError({
302
- cause: error as Error,
303
- message: 'Failed to compute SHA-256 checksum',
304
- }),
305
- });
365
+ // Check if binary exists
366
+ const exists = yield* fs.exists(binaryPath).pipe(Effect.catchAll(() => Effect.succeed(false)));
367
+
368
+ if (!exists) {
369
+ return yield* Effect.fail(
370
+ new UpgradeBinaryError({
371
+ cause: `Binary not found in archive: ${binaryPath}`,
372
+ message: 'Extracted archive does not contain expected binary',
373
+ })
374
+ );
375
+ }
376
+
377
+ // Make executable
378
+ yield* fs.chmod(binaryPath, 0o755).pipe(
379
+ Effect.mapError(
380
+ cause =>
381
+ new UpgradeBinaryError({
382
+ cause,
383
+ message: 'Failed to make binary executable',
384
+ })
385
+ )
386
+ );
387
307
- const actual = Array.from(new Uint8Array(hashBuffer))
308
- .map(b => b.toString(16).padStart(2, '0'))
309
- .join('');
388
+ return {
389
+ binaryPath,
390
+ packageDir,
391
+ };
392
+ });
393
311
- if (actual !== expectedHash) {
312
- return yield* Effect.fail(
313
- new UpgradeBinaryError({
314
- message: `Checksum mismatch for ${fileName}\n Expected: ${expectedHash}\n Actual: ${actual}`,
315
- })
316
- );
317
- }
394
+/**
395
+ * Get current executable path
396
+ */
397
+const getCurrentExecutablePath = Effect.fn(function* () {
398
+ // E.g., ~/.composio/composio
399
+ const currentPath = process.execPath;
400
319
- yield* Effect.logDebug(`Checksum verified for ${fileName}`);
320
- });
401
+ const runtimesPaths: Array<string | null> = [Bun.which('bun'), Bun.which('node')];
402
322
- /**
323
- * Extract binary from zip archive using FileSystem
324
- */
325
- const extractBinary = (
326
- { name, data }: { name: string; data: Uint8Array },
327
- tempDir: string
328
- ): Effect.Effect<{ binaryPath: string; packageDir: string }, UpgradeBinaryError, never> =>
329
- Effect.gen(function* () {
330
- const zipPath = path.join(tempDir, name);
331
- const extractDir = path.join(tempDir, 'extract');
332
- const packageDir = path.join(extractDir, path.parse(name).name);
333
- const binaryPath = path.join(packageDir, CLI_BINARY_NAME);
403
+ if (runtimesPaths.includes(currentPath)) {
404
+ return yield* Effect.fail(
405
+ new UpgradeBinaryError({
406
+ cause: 'Currently using Composio CLI via Bun or Node.js runtime',
407
+ message:
408
+ 'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.',
409
+ })
410
+ );
411
+ }
412
335
- yield* Effect.logDebug(`Download zip to ${extractDir}`);
413
+ return currentPath;
414
+});
415
337
- // Write zip file
338
- yield* fs.writeFile(zipPath, data).pipe(
339
- Effect.catchAll(error =>
340
- Effect.fail(
341
- new UpgradeBinaryError({
342
- cause: error as Error,
343
- message: 'Failed to write zip file',
344
- })
345
- )
346
- )
416
+/**
417
+ * Replace current executable binary with the new target one.
418
+ */
419
+const replaceBinary = (
420
+ ctx: UpgradeBinaryContext,
421
+ sourcePath: string,
422
+ targetPath: string,
423
+ options: {
424
+ releaseTag?: string;
425
+ } = {}
426
+): Effect.Effect<void, UpgradeBinaryError> =>
427
+ Effect.gen(function* () {
428
+ const { fs, path } = ctx;
429
+ yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
430
+ yield* fs
431
+ .copy(sourcePath, targetPath, {
432
+ // Note: without `overwrite: true`, the copy operation will silently bail out
433
+ overwrite: true,
434
+ })
435
+ .pipe(
436
+ Effect.mapError(
437
+ cause =>
438
+ new UpgradeBinaryError({
439
+ cause,
440
+ message: 'Failed to replace binary',
441
+ })
442
+ )
443
+ );
444
+
445
+ const sourceDirectory = path.dirname(sourcePath);
446
+ const targetDirectory = path.dirname(targetPath);
447
+ const companionRelativePaths = yield* provideFsAndPath(
448
+ ctx,
449
+ collectExpectedRunCompanionAssetRelativePaths(sourceDirectory)
450
+ );
451
+ for (const relativePath of companionRelativePaths) {
452
+ const sourceCompanion = path.join(sourceDirectory, relativePath);
453
+ const sourceExists = yield* fs
454
+ .exists(sourceCompanion)
455
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
456
+
457
+ if (!sourceExists) {
458
+ return yield* Effect.fail(
459
+ new UpgradeBinaryError({
460
+ cause: `Missing companion module: ${sourceCompanion}`,
461
+ message: 'Downloaded binary package is incomplete',
462
+ })
463
);
464
+ }
465
349
- // Create extract directory
350
- yield* fs.makeDirectory(extractDir, { recursive: true }).pipe(
351
- Effect.catchAll(error =>
352
- Effect.fail(
466
+ const targetCompanion = path.join(targetDirectory, relativePath);
467
+ yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
468
+ Effect.mapError(
469
+ cause =>
470
+ new UpgradeBinaryError({
471
+ cause,
472
+ message: `Failed to create companion module directory: ${relativePath}`,
473
+ })
474
+ )
475
+ );
476
+
477
+ yield* fs
478
+ .copy(sourceCompanion, targetCompanion, {
479
+ overwrite: true,
480
+ })
481
+ .pipe(
482
+ Effect.mapError(
483
+ cause =>
484
new UpgradeBinaryError({
354
- cause: error as Error,
355
- message: 'Failed to create extract directory',
485
+ cause,
486
+ message: `Failed to replace companion module: ${relativePath}`,
487
})
357
- )
488
)
489
);
360
-
361
- yield* Effect.tryPromise({
362
- try: async () => {
363
- await extractZip(zipPath, { dir: extractDir });
364
- },
365
- catch: error =>
490
+ }
491
+
492
+ const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
493
+ const localToolsAssetExists = yield* fs
494
+ .exists(localToolsAssetSource)
495
+ .pipe(Effect.catchAll(() => Effect.succeed(false)));
496
+ if (localToolsAssetExists) {
497
+ const localToolsAssetTarget = path.join(targetDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
498
+ // Replace the whole asset directory: drop the previous tree, then copy
499
+ // the new one (fs.copy is recursive for directories).
500
+ yield* fs.remove(localToolsAssetTarget, { recursive: true, force: true }).pipe(
501
+ Effect.andThen(fs.copy(localToolsAssetSource, localToolsAssetTarget, { overwrite: true })),
502
+ Effect.mapError(
503
+ error =>
504
new UpgradeBinaryError({
367
- cause: error as Error,
368
- message: 'Failed to extract zip archive',
369
- }),
370
- });
371
-
372
- // Check if binary exists
373
- const exists = yield* fs
374
- .exists(binaryPath)
375
- .pipe(Effect.catchAll(() => Effect.succeed(false)));
376
-
377
- if (!exists) {
378
- return yield* Effect.fail(
505
+ cause: error,
506
+ message: 'Failed to replace local-tool binary assets',
507
+ })
508
+ )
509
+ );
510
+ }
511
+
512
+ const releaseTag = options.releaseTag;
513
+ if (releaseTag) {
514
+ yield* provideFsAndPath(ctx, writeInstalledReleaseTag(targetDirectory, releaseTag)).pipe(
515
+ Effect.mapError(
516
+ error =>
517
new UpgradeBinaryError({
380
- cause: new Error(`Binary not found in archive: ${binaryPath}`),
381
- message: 'Extracted archive does not contain expected binary',
518
+ cause: error,
519
+ message: 'Failed to update installed release metadata',
520
})
383
- );
521
+ )
522
+ );
523
+ }
524
+ });
525
+
526
+/**
527
+ * Main upgrade function
528
+ */
529
+const upgrade = (
530
+ ctx: UpgradeBinaryContext,
531
+ options: {
532
+ prerelease?: boolean;
533
+ tag?: string;
534
+ } = {}
535
+) =>
536
+ Effect.gen(function* () {
537
+ const ui = yield* TerminalUI;
538
+ const upgradeTargetOpt = yield* DEBUG_OVERRIDE_CONFIG['UPGRADE_TARGET'];
539
+ const currentPath = yield* getCurrentExecutablePath();
540
+ const prerelease = options.prerelease ?? false;
541
+ const explicitTag = options.tag;
542
+ const currentReleaseIdentifier = yield* resolveCurrentReleaseIdentifier(ctx, currentPath);
543
+ yield* Effect.logDebug(`Current executable path: ${currentPath}`);
544
+ yield* Effect.logDebug(`Current release identifier: ${currentReleaseIdentifier}`);
545
+
546
+ yield* ui.intro('composio upgrade');
547
+
548
+ // If local binary path is provided (for testing), use it directly
549
+ if (Option.isSome(upgradeTargetOpt)) {
550
+ yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`);
551
+ yield* replaceBinary(ctx, upgradeTargetOpt.value, currentPath);
552
+ yield* ui.outro('Upgrade completed');
553
+ return undefined;
554
+ }
555
+
556
+ const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
557
+ Effect.gen(function* () {
558
+ const platformArch = yield* detectPlatform;
559
+ const release = yield* fetchLatestRelease(ctx, platformArch, {
560
+ prerelease,
561
+ tag: explicitTag,
562
+ });
563
+ if (!explicitTag) {
564
+ const updateAvailable = yield* isUpdateAvailable(release, currentReleaseIdentifier);
565
+ if (!updateAvailable) {
566
+ yield* spinner.stop('You are already running the latest version!');
567
+ return false;
568
+ }
569
+ } else if (release.tag_name === currentReleaseIdentifier) {
570
+ yield* Effect.logDebug(`Already running ${release.tag_name}; re-installing as requested`);
571
}
572
386
- // Make executable
387
- yield* fs.chmod(binaryPath, 0o755).pipe(
388
- Effect.catchAll(error =>
389
- Effect.fail(
390
- new UpgradeBinaryError({
391
- cause: error as Error,
392
- message: 'Failed to make binary executable',
393
- })
394
- )
395
- )
573
+ yield* spinner.message(
574
+ explicitTag
575
+ ? `Installing ${release.tag_name} (current: ${currentReleaseIdentifier})...`
576
+ : `New version available: ${release.tag_name} (current: ${currentReleaseIdentifier}). Downloading...`
577
);
578
398
- return {
399
- binaryPath,
400
- packageDir,
401
- };
402
- });
579
+ const { name, data } = yield* downloadBinary(ctx, release, platformArch);
580
404
- /**
405
- * Get current executable path
406
- */
407
- const getCurrentExecutablePath = Effect.fn(function* () {
408
- // E.g., ~/.composio/composio
409
- const currentPath = process.execPath;
581
+ yield* spinner.message('Verifying checksum...');
582
411
- const runtimesPaths = [Bun.which('bun'), Bun.which('node')] as Array<string | null>;
583
+ const checksums = yield* fetchChecksums(ctx, release);
584
+ if (Option.isSome(checksums)) {
585
+ const expectedHash = checksums.value.get(name);
586
+ if (expectedHash) {
587
+ yield* verifyChecksum(data, expectedHash, name);
588
+ } else {
589
+ yield* Effect.logDebug(`No checksum entry found for ${name} — skipping verification`);
590
+ }
591
+ }
592
413
- if (runtimesPaths.includes(currentPath)) {
414
- return yield* Effect.fail(
415
- new UpgradeBinaryError({
416
- cause: new Error(`Currently using Composio CLI via Bun or Node.js runtime`),
417
- message:
418
- 'Cannot upgrade runtime binary. Please run the upgrade command from a self-contained Composio CLI binary.',
419
- })
420
- );
421
- }
593
+ yield* spinner.message('Extracting...');
594
423
- return currentPath;
424
- });
425
-
426
- /**
427
- * Replace current executable binary with the new target one.
428
- */
429
- const replaceBinary = (
430
- sourcePath: string,
431
- targetPath: string,
432
- options: {
433
- releaseTag?: string;
434
- } = {}
435
- ): Effect.Effect<void, UpgradeBinaryError> =>
436
- Effect.gen(function* () {
437
- yield* Effect.logDebug(`Replacing binary: ${sourcePath} -> ${targetPath}`);
438
- yield* fs
439
- .copy(sourcePath, targetPath, {
440
- // Note: without `overwrite: true`, the copy operation will silently bail out
441
- overwrite: true,
442
- })
595
+ // The temporary directory is automatically cleaned up
596
+ const tmpDir = yield* ctx.fs
597
+ .makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade` })
598
.pipe(
444
- Effect.catchAll(error =>
445
- Effect.fail(
599
+ Effect.mapError(
600
+ cause =>
601
new UpgradeBinaryError({
447
- cause: error as Error,
448
- message: 'Failed to replace binary',
602
+ cause,
603
+ message: 'Failed to create temporary directory',
604
})
450
- )
605
)
606
);
607
454
- const sourceDirectory = path.dirname(sourcePath);
455
- const targetDirectory = path.dirname(targetPath);
456
- const companionRelativePaths =
457
- collectExpectedRunCompanionAssetRelativePaths(sourceDirectory);
458
- for (const relativePath of companionRelativePaths) {
459
- const sourceCompanion = path.join(sourceDirectory, relativePath);
460
- const sourceExists = yield* fs
461
- .exists(sourceCompanion)
462
- .pipe(Effect.catchAll(() => Effect.succeed(false)));
463
-
464
- if (!sourceExists) {
465
- return yield* Effect.fail(
466
- new UpgradeBinaryError({
467
- cause: new Error(`Missing companion module: ${sourceCompanion}`),
468
- message: 'Downloaded binary package is incomplete',
469
- })
470
- );
471
- }
472
-
473
- const targetCompanion = path.join(targetDirectory, relativePath);
474
- yield* fs.makeDirectory(path.dirname(targetCompanion), { recursive: true }).pipe(
475
- Effect.catchAll(error =>
476
- Effect.fail(
477
- new UpgradeBinaryError({
478
- cause: error as Error,
479
- message: `Failed to create companion module directory: ${relativePath}`,
480
- })
481
- )
482
- )
483
- );
484
-
485
- yield* fs
486
- .copy(sourceCompanion, targetCompanion, {
487
- overwrite: true,
488
- })
489
- .pipe(
490
- Effect.catchAll(error =>
491
- Effect.fail(
492
- new UpgradeBinaryError({
493
- cause: error as Error,
494
- message: `Failed to replace companion module: ${relativePath}`,
495
- })
496
- )
497
- )
498
- );
499
- }
500
-
501
- const localToolsAssetSource = path.join(sourceDirectory, LOCAL_TOOLS_BINARY_ASSET_DIRNAME);
502
- const localToolsAssetExists = yield* fs
503
- .exists(localToolsAssetSource)
504
- .pipe(Effect.catchAll(() => Effect.succeed(false)));
505
- if (localToolsAssetExists) {
506
- const localToolsAssetTarget = path.join(
507
- targetDirectory,
508
- LOCAL_TOOLS_BINARY_ASSET_DIRNAME
509
- );
510
- yield* Effect.tryPromise({
511
- try: async () => {
512
- await removePath(localToolsAssetTarget, { recursive: true, force: true });
513
- await copyPath(localToolsAssetSource, localToolsAssetTarget, { recursive: true });
514
- },
515
- catch: error =>
516
- new UpgradeBinaryError({
517
- cause: error as Error,
518
- message: 'Failed to replace local-tool binary assets',
519
- }),
520
- });
521
- }
608
+ const extractedBinary = yield* extractBinary(ctx, { name, data }, tmpDir);
609
+ yield* replaceBinary(ctx, extractedBinary.binaryPath, currentPath, {
610
+ releaseTag: release.tag_name,
611
+ });
612
523
- if (options.releaseTag) {
524
- yield* Effect.try({
525
- try: () => writeInstalledReleaseTag(targetDirectory, options.releaseTag!),
526
- catch: error =>
527
- new UpgradeBinaryError({
528
- cause: error as Error,
529
- message: 'Failed to update installed release metadata',
530
- }),
531
- });
532
- }
533
- });
534
-
535
- /**
536
- * Main upgrade function
537
- */
538
- const upgrade = (
539
- options: {
540
- prerelease?: boolean;
541
- tag?: string;
542
- } = {}
543
- ) =>
544
- Effect.gen(function* () {
545
- const ui = yield* TerminalUI;
546
- const upgradeTargetOpt = yield* DEBUG_OVERRIDE_CONFIG['UPGRADE_TARGET'];
547
- const currentPath = yield* getCurrentExecutablePath();
548
- const prerelease = options.prerelease ?? false;
549
- const explicitTag = options.tag;
550
- const currentReleaseIdentifier = resolveCurrentReleaseIdentifier(currentPath);
551
- yield* Effect.logDebug(`Current executable path: ${currentPath}`);
552
- yield* Effect.logDebug(`Current release identifier: ${currentReleaseIdentifier}`);
553
-
554
- yield* ui.intro('composio upgrade');
555
-
556
- // If local binary path is provided (for testing), use it directly
557
- if (Option.isSome(upgradeTargetOpt)) {
558
- yield* ui.log.info(`New local version available (current: ${currentReleaseIdentifier})`);
559
- yield* replaceBinary(upgradeTargetOpt.value, currentPath);
560
- yield* ui.outro('Upgrade completed');
561
- return undefined;
562
- }
613
+ yield* spinner.stop('Upgrade completed!');
614
+ return release.tag_name;
615
+ })
616
+ );
617
564
- const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
565
- Effect.gen(function* () {
566
- const platformArch = yield* detectPlatform;
567
- const release = yield* fetchLatestRelease(platformArch, {
568
- prerelease,
569
- tag: explicitTag,
570
- });
571
- if (!explicitTag) {
572
- const updateAvailable = yield* isUpdateAvailable(release, currentReleaseIdentifier);
573
- if (!updateAvailable) {
574
- yield* spinner.stop('You are already running the latest version!');
575
- return false;
576
- }
577
- } else if (release.tag_name === currentReleaseIdentifier) {
578
- yield* Effect.logDebug(
579
- `Already running ${release.tag_name}; re-installing as requested`
580
- );
581
- }
582
-
583
- yield* spinner.message(
584
- explicitTag
585
- ? `Installing ${release.tag_name} (current: ${currentReleaseIdentifier})...`
586
- : `New version available: ${release.tag_name} (current: ${currentReleaseIdentifier}). Downloading...`
587
- );
588
-
589
- const { name, data } = yield* downloadBinary(release, platformArch);
590
-
591
- yield* spinner.message('Verifying checksum...');
592
-
593
- const checksums = yield* fetchChecksums(release);
594
- if (Option.isSome(checksums)) {
595
- const expectedHash = checksums.value.get(name);
596
- if (expectedHash) {
597
- yield* verifyChecksum(data, expectedHash, name);
598
- } else {
599
- yield* Effect.logDebug(
600
- `No checksum entry found for ${name} — skipping verification`
601
- );
602
- }
603
- }
604
-
605
- yield* spinner.message('Extracting...');
606
-
607
- // The temporary directory is automatically cleaned up
608
- const tmpDir = yield* fs
609
- .makeTempDirectoryScoped({ prefix: `${CLI_BINARY_NAME}-upgrade}` })
610
- .pipe(
611
- Effect.catchAll(error =>
612
- Effect.fail(
613
- new UpgradeBinaryError({
614
- cause: error as Error,
615
- message: 'Failed to create temporary directory',
616
- })
617
- )
618
- )
619
- );
620
-
621
- const extractedBinary = yield* extractBinary({ name, data }, tmpDir);
622
- yield* replaceBinary(extractedBinary.binaryPath, currentPath, {
623
- releaseTag: release.tag_name,
624
- });
625
-
626
- yield* spinner.stop('Upgrade completed!');
627
- return release.tag_name;
628
- })
629
- );
618
+ yield* ui.outro(
619
+ didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
620
+ );
621
631
- yield* ui.outro(
632
- didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
633
- );
622
+ return didUpgrade || undefined; // release tag string, or undefined if no upgrade
623
+ });
624
635
- return didUpgrade || undefined; // release tag string, or undefined if no upgrade
636
- });
625
+// Service to manage CLI binary upgrades
626
+export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/UpgradeBinary', {
627
+ accessors: true,
628
+ effect: Effect.gen(function* () {
629
+ const ctx: UpgradeBinaryContext = {
630
+ httpClient: yield* HttpClient.HttpClient,
631
+ fs: yield* FileSystem.FileSystem,
632
+ path: yield* Path.Path,
633
+ githubConfig: yield* GITHUB_CONFIG_ALL,
634
+ };
635
636
return {
639
- upgrade,
637
+ upgrade: (options: { prerelease?: boolean; tag?: string } = {}) => upgrade(ctx, options),
638
} as const;
639
}),
642
- dependencies: [],
640
+ dependencies: [Path.layer],
641
}) {}