1
import fsSync from 'node:fs';
2
import fs from 'node:fs/promises';
3
+import os from 'node:os';
4
import path from 'node:path';
5
import { fileURLToPath } from 'node:url';
6
+import decompress from 'decompress';
7
import { detectCliPlatform, supportsCliPlatform } from './platform';
8
import type {
9
LocalBundledBinaryDeclaration,
13
} from './types';
14
15
const DEFAULT_BUNDLE_DIR = 'local-tools-binaries';
16
+const RELEASE_TAG_FILENAME = 'release-tag.txt';
17
+
18
+const DEFAULT_GITHUB_CONFIG = {
19
+ apiBaseUrl: 'https://api.github.com',
20
+ owner: 'ComposioHQ',
21
+ repo: 'composio',
22
+} as const;
23
+
24
+type GitHubReleaseAsset = {
25
+ readonly name: string;
26
+ readonly browser_download_url: string;
27
+};
28
+
29
+type GitHubRelease = {
30
+ readonly tag_name: string;
31
+ readonly assets: ReadonlyArray<GitHubReleaseAsset>;
32
+};
33
+
34
+let localToolsRepairPromise: Promise<boolean> | null = null;
35
36
export interface LocalBundledBinaryResolution {
37
readonly id: string;
77
}
78
};
79
80
+const readTextFileIfPresent = async (filePath: string): Promise<string | undefined> => {
81
+ try {
82
+ const value = (await fs.readFile(filePath, 'utf8')).trim();
83
+ return value.length > 0 ? value : undefined;
84
+ } catch {
85
+ return undefined;
86
+ }
87
+};
88
+
89
+const resolveBinaryAssetName = (): string | undefined => {
90
+ switch (`${process.platform}-${process.arch}`) {
91
+ case 'darwin-arm64':
92
+ return 'composio-darwin-aarch64.zip';
93
+ case 'darwin-x64':
94
+ return 'composio-darwin-x64.zip';
95
+ case 'linux-x64':
96
+ return 'composio-linux-x64.zip';
97
+ case 'linux-arm64':
98
+ return 'composio-linux-aarch64.zip';
99
+ default:
100
+ return undefined;
101
+ }
102
+};
103
+
104
+const fetchGitHubJson = async <T>({
105
+ url,
106
+ accessToken,
107
+}: {
108
+ readonly url: string;
109
+ readonly accessToken?: string;
110
+}): Promise<T> => {
111
+ const response = await fetch(url, {
112
+ headers: {
113
+ Accept: 'application/vnd.github+json',
114
+ 'User-Agent': 'composio-cli-local-tools-repair',
115
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
116
+ },
117
+ });
118
+ if (!response.ok) {
119
+ throw new Error(`GitHub request failed: HTTP ${response.status}`);
120
+ }
121
+ return (await response.json()) as T;
122
+};
123
+
124
+const downloadAsset = async (
125
+ asset: GitHubReleaseAsset,
126
+ accessToken?: string
127
+): Promise<Uint8Array> => {
128
+ const response = await fetch(asset.browser_download_url, {
129
+ headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
130
+ });
131
+ if (!response.ok) {
132
+ throw new Error(`Failed to download ${asset.name}: HTTP ${response.status}`);
133
+ }
134
+ return new Uint8Array(await response.arrayBuffer());
135
+};
136
+
137
+const fetchChecksums = async (
138
+ release: GitHubRelease,
139
+ accessToken?: string
140
+): Promise<Map<string, string> | undefined> => {
141
+ const checksumsAsset = release.assets.find(asset => asset.name === 'checksums.txt');
142
+ if (!checksumsAsset) return undefined;
143
+
144
+ const response = await fetch(checksumsAsset.browser_download_url, {
145
+ headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
146
+ });
147
+ if (!response.ok) return undefined;
148
+
149
+ const checksums = new Map<string, string>();
150
+ const text = await response.text();
151
+ for (const line of text.split('\n')) {
152
+ const trimmed = line.trim();
153
+ if (!trimmed) continue;
154
+ const parts = trimmed.split(/\s+/);
155
+ if (parts.length >= 2) {
156
+ checksums.set(parts[1]!, parts[0]!);
157
+ }
158
+ }
159
+ return checksums;
160
+};
161
+
162
+const verifyChecksum = async ({
163
+ data,
164
+ expectedHash,
165
+ fileName,
166
+}: {
167
+ readonly data: Uint8Array;
168
+ readonly expectedHash: string;
169
+ readonly fileName: string;
170
+}): Promise<void> => {
171
+ const digest = await crypto.subtle.digest('SHA-256', data.slice().buffer);
172
+ const actualHash = Array.from(new Uint8Array(digest))
173
+ .map(byte => byte.toString(16).padStart(2, '0'))
174
+ .join('');
175
+ if (actualHash !== expectedHash) {
176
+ throw new Error(
177
+ `Checksum mismatch while repairing ${fileName}\n Expected: ${expectedHash}\n Actual: ${actualHash}`
178
+ );
179
+ }
180
+};
181
+
182
+const isStandaloneBunExecutable = (): boolean => {
183
+ const currentFilePath = fileURLToPath(import.meta.url);
184
+ return currentFilePath.startsWith('/$bunfs/');
185
+};
186
+
187
+const repairInstalledLocalToolsBundle = async (): Promise<boolean> => {
188
+ if (process.env.COMPOSIO_LOCAL_TOOLS_BIN_DIR?.trim() || !isStandaloneBunExecutable()) {
189
+ return false;
190
+ }
191
+
192
+ const installDirectory = path.dirname(process.execPath);
193
+ const releaseTag =
194
+ process.env.GITHUB_TAG?.trim() ||
195
+ (await readTextFileIfPresent(path.join(installDirectory, RELEASE_TAG_FILENAME)));
196
+ if (!releaseTag) return false;
197
+
198
+ const assetName = resolveBinaryAssetName();
199
+ if (!assetName) return false;
200
+
201
+ const githubConfig = {
202
+ apiBaseUrl:
203
+ process.env.GITHUB_API_BASE_URL ||
204
+ process.env.COMPOSIO_GITHUB_API_BASE_URL ||
205
+ DEFAULT_GITHUB_CONFIG.apiBaseUrl,
206
+ owner:
207
+ process.env.GITHUB_OWNER || process.env.COMPOSIO_GITHUB_OWNER || DEFAULT_GITHUB_CONFIG.owner,
208
+ repo: process.env.GITHUB_REPO || process.env.COMPOSIO_GITHUB_REPO || DEFAULT_GITHUB_CONFIG.repo,
209
+ accessToken: process.env.GITHUB_ACCESS_TOKEN || process.env.COMPOSIO_GITHUB_ACCESS_TOKEN,
210
+ };
211
+
212
+ const release = await fetchGitHubJson<GitHubRelease>({
213
+ url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodeURIComponent(releaseTag)}`,
214
+ accessToken: githubConfig.accessToken,
215
+ });
216
+ const asset = release.assets.find(candidate => candidate.name === assetName);
217
+ if (!asset) return false;
218
+
219
+ const archiveData = await downloadAsset(asset, githubConfig.accessToken);
220
+ const expectedChecksum = (await fetchChecksums(release, githubConfig.accessToken))?.get(
221
+ asset.name
222
+ );
223
+ if (expectedChecksum) {
224
+ await verifyChecksum({
225
+ data: archiveData,
226
+ expectedHash: expectedChecksum,
227
+ fileName: asset.name,
228
+ });
229
+ }
230
+
231
+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'composio-local-tools-repair-'));
232
+ try {
233
+ const zipPath = path.join(tempDir, asset.name);
234
+ const extractDir = path.join(tempDir, 'extract');
235
+ await fs.writeFile(zipPath, archiveData);
236
+ await decompress(zipPath, extractDir);
237
+
238
+ const archiveBundleRoot = path.join(
239
+ extractDir,
240
+ path.parse(asset.name).name,
241
+ DEFAULT_BUNDLE_DIR
242
+ );
243
+ if (!(await binaryExists(archiveBundleRoot))) return false;
244
+
245
+ const installBundleRoot = path.join(installDirectory, DEFAULT_BUNDLE_DIR);
246
+ await fs.rm(installBundleRoot, { force: true, recursive: true });
247
+ await fs.cp(archiveBundleRoot, installBundleRoot, { recursive: true });
248
+ return true;
249
+ } finally {
250
+ await fs.rm(tempDir, { force: true, recursive: true });
251
+ }
252
+};
253
+
254
+const maybeRepairInstalledLocalToolsBundle = async (): Promise<boolean> => {
255
+ localToolsRepairPromise ??= repairInstalledLocalToolsBundle().catch(() => false);
256
+ return localToolsRepairPromise;
257
+};
258
+
259
const findDeclaration = (
260
toolkit: LocalToolkitDeclaration,
261
id: string
293
}
294
}
295
296
+ if (bundledPaths.length > 0 && (await maybeRepairInstalledLocalToolsBundle())) {
297
+ for (const bundledPath of bundledPaths) {
298
+ if (await binaryExists(bundledPath)) {
299
+ return {
300
+ id: ref.bundledBinary,
301
+ path: bundledPath,
302
+ platform: currentPlatform,
303
+ exists: true,
304
+ source: 'bundled',
305
+ };
306
+ }
307
+ }
308
+ }
309
+
310
if (
311
ref.fallbackCommand &&
312
hasPathSeparator(ref.fallbackCommand) &&