1
import * as fs from 'node:fs';
2
+import * as os from 'node:os';
3
import * as path from 'node:path';
4
import { fileURLToPath } from 'node:url';
5
+import decompress from 'decompress';
6
7
export const RUN_COMPANION_MODULE_BASENAMES = [
8
'run-subagent-shared',
14
name => `${name}.mjs`
15
);
16
17
+export const RUN_COMPANION_RELEASE_TAG_FILENAME = 'release-tag.txt';
18
+
19
+type GitHubReleaseAsset = {
20
+ name: string;
21
+ browser_download_url: string;
22
+};
23
+
24
+type GitHubRelease = {
25
+ tag_name: string;
26
+ assets: GitHubReleaseAsset[];
27
+};
28
+
29
+const DEFAULT_GITHUB_CONFIG = {
30
+ apiBaseUrl: 'https://api.github.com',
31
+ owner: 'ComposioHQ',
32
+ repo: 'composio',
33
+} as const;
34
+
35
+const resolveCompanionInstallDirectory = (execPath: string) => path.dirname(execPath);
36
+
37
+const resolveBinaryAssetName = ({
38
+ platform = process.platform,
39
+ arch = process.arch,
40
+}: {
41
+ platform?: NodeJS.Platform;
42
+ arch?: string;
43
+}) => {
44
+ switch (`${platform}-${arch}`) {
45
+ case 'darwin-arm64':
46
+ return 'composio-darwin-aarch64.zip';
47
+ case 'darwin-x64':
48
+ return 'composio-darwin-x64.zip';
49
+ case 'linux-x64':
50
+ return 'composio-linux-x64.zip';
51
+ case 'linux-arm64':
52
+ return 'composio-linux-aarch64.zip';
53
+ default:
54
+ throw new Error(`Unsupported platform for run companion repair: ${platform}-${arch}`);
55
+ }
56
+};
57
+
58
+const readTextFileIfPresent = (filePath: string) => {
59
+ if (!fs.existsSync(filePath)) {
60
+ return undefined;
61
+ }
62
+
63
+ const value = fs.readFileSync(filePath, 'utf8').trim();
64
+ return value.length > 0 ? value : undefined;
65
+};
66
+
67
+export const readInstalledReleaseTag = (execPath: string) =>
68
+ readTextFileIfPresent(
69
+ path.join(resolveCompanionInstallDirectory(execPath), RUN_COMPANION_RELEASE_TAG_FILENAME)
70
+ );
71
+
72
+export const writeInstalledReleaseTag = (installDir: string, releaseTag: string) => {
73
+ fs.writeFileSync(
74
+ path.join(installDir, RUN_COMPANION_RELEASE_TAG_FILENAME),
75
+ `${releaseTag}\n`,
76
+ 'utf8'
77
+ );
78
+};
79
+
80
+export const listMissingInstalledRunCompanionModules = (execPath: string) => {
81
+ const installDirectory = resolveCompanionInstallDirectory(execPath);
82
+ return RUN_COMPANION_MODULE_FILENAMES.filter(
83
+ fileName => !fs.existsSync(path.join(installDirectory, fileName))
84
+ );
85
+};
86
+
87
+const fetchGitHubJson = async <T>({
88
+ url,
89
+ accessToken,
90
+ fetchErrorMessage,
91
+}: {
92
+ url: string;
93
+ accessToken?: string;
94
+ fetchErrorMessage: string;
95
+}): Promise<T> => {
96
+ const response = await fetch(url, {
97
+ headers: {
98
+ Accept: 'application/vnd.github+json',
99
+ 'User-Agent': 'composio-cli-run-repair',
100
+ ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
101
+ },
102
+ });
103
+
104
+ if (!response.ok) {
105
+ const body = await response.text().catch(() => '');
106
+ throw new Error(`${fetchErrorMessage} (HTTP ${response.status}${body ? `: ${body}` : ''})`);
107
+ }
108
+
109
+ return (await response.json()) as T;
110
+};
111
+
112
+const fetchChecksums = async ({
113
+ release,
114
+ accessToken,
115
+}: {
116
+ release: GitHubRelease;
117
+ accessToken?: string;
118
+}) => {
119
+ const checksumsAsset = release.assets.find(asset => asset.name === 'checksums.txt');
120
+ if (!checksumsAsset) {
121
+ return undefined;
122
+ }
123
+
124
+ const response = await fetch(checksumsAsset.browser_download_url, {
125
+ headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
126
+ });
127
+
128
+ if (!response.ok) {
129
+ return undefined;
130
+ }
131
+
132
+ const text = await response.text();
133
+ const checksums = new Map<string, string>();
134
+ for (const line of text.split('\n')) {
135
+ const trimmed = line.trim();
136
+ if (!trimmed) {
137
+ continue;
138
+ }
139
+
140
+ const parts = trimmed.split(/\s+/);
141
+ if (parts.length >= 2) {
142
+ checksums.set(parts[1]!, parts[0]!);
143
+ }
144
+ }
145
+
146
+ return checksums;
147
+};
148
+
149
+const verifyChecksum = async ({
150
+ data,
151
+ expectedHash,
152
+ fileName,
153
+}: {
154
+ data: Uint8Array;
155
+ expectedHash: string;
156
+ fileName: string;
157
+}) => {
158
+ const digest = await crypto.subtle.digest('SHA-256', data.slice().buffer);
159
+ const actualHash = Array.from(new Uint8Array(digest))
160
+ .map(byte => byte.toString(16).padStart(2, '0'))
161
+ .join('');
162
+
163
+ if (actualHash !== expectedHash) {
164
+ throw new Error(
165
+ `Checksum mismatch while repairing ${fileName}\n Expected: ${expectedHash}\n Actual: ${actualHash}`
166
+ );
167
+ }
168
+};
169
+
170
+const resolveRepairReleaseTag = ({
171
+ execPath,
172
+ appVersion,
173
+}: {
174
+ execPath: string;
175
+ appVersion: string;
176
+}) =>
177
+ process.env.GITHUB_TAG?.trim() ||
178
+ readInstalledReleaseTag(execPath) ||
179
+ `@composio/cli@${appVersion}`;
180
+
181
+export const repairMissingInstalledRunCompanionModules = async ({
182
+ callerImportMetaUrl,
183
+ execPath,
184
+ appVersion,
185
+}: {
186
+ callerImportMetaUrl: string;
187
+ execPath: string;
188
+ appVersion: string;
189
+}) => {
190
+ const currentFilePath = fileURLToPath(callerImportMetaUrl);
191
+ if (!currentFilePath.startsWith('/$bunfs/')) {
192
+ return { repaired: false as const };
193
+ }
194
+
195
+ const missingModules = listMissingInstalledRunCompanionModules(execPath);
196
+ if (missingModules.length === 0) {
197
+ return { repaired: false as const };
198
+ }
199
+
200
+ const releaseTag = resolveRepairReleaseTag({ execPath, appVersion });
201
+ const githubConfig = {
202
+ apiBaseUrl: process.env.GITHUB_API_BASE_URL || DEFAULT_GITHUB_CONFIG.apiBaseUrl,
203
+ owner: process.env.GITHUB_OWNER || DEFAULT_GITHUB_CONFIG.owner,
204
+ repo: process.env.GITHUB_REPO || DEFAULT_GITHUB_CONFIG.repo,
205
+ accessToken: process.env.GITHUB_ACCESS_TOKEN,
206
+ };
207
+
208
+ const encodedTag = encodeURIComponent(releaseTag);
209
+ const release = await fetchGitHubJson<GitHubRelease>({
210
+ url: `${githubConfig.apiBaseUrl}/repos/${githubConfig.owner}/${githubConfig.repo}/releases/tags/${encodedTag}`,
211
+ accessToken: githubConfig.accessToken,
212
+ fetchErrorMessage: `Failed to fetch release metadata for ${releaseTag} while repairing run companion modules`,
213
+ }).catch(error => {
214
+ throw new Error(
215
+ [
216
+ `Unable to restore the files required by 'composio run' for ${releaseTag}.`,
217
+ error instanceof Error ? error.message : String(error),
218
+ `Reinstall the CLI, or set GITHUB_TAG to the exact release tag for this build and try again.`,
219
+ ].join('\n')
220
+ );
221
+ });
222
+
223
+ const assetName = resolveBinaryAssetName({});
224
+ const asset = release.assets.find(candidate => candidate.name === assetName);
225
+ if (!asset) {
226
+ throw new Error(
227
+ `Release ${release.tag_name} does not contain ${assetName}; cannot restore run companion modules.`
228
+ );
229
+ }
230
+
231
+ const archiveResponse = await fetch(asset.browser_download_url, {
232
+ headers: githubConfig.accessToken
233
+ ? { Authorization: `Bearer ${githubConfig.accessToken}` }
234
+ : undefined,
235
+ });
236
+ if (!archiveResponse.ok) {
237
+ throw new Error(
238
+ `Failed to download ${asset.name} from ${release.tag_name} while repairing run companion modules (HTTP ${archiveResponse.status}).`
239
+ );
240
+ }
241
+
242
+ const archiveData = new Uint8Array(await archiveResponse.arrayBuffer());
243
+ const checksums = await fetchChecksums({
244
+ release,
245
+ accessToken: githubConfig.accessToken,
246
+ });
247
+ const expectedChecksum = checksums?.get(asset.name);
248
+ if (expectedChecksum) {
249
+ await verifyChecksum({
250
+ data: archiveData,
251
+ expectedHash: expectedChecksum,
252
+ fileName: asset.name,
253
+ });
254
+ }
255
+
256
+ const tempDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'composio-run-repair-'));
257
+ try {
258
+ const archivePath = path.join(tempDirectory, asset.name);
259
+ const extractDirectory = path.join(tempDirectory, 'extract');
260
+ const packageDirectory = path.join(extractDirectory, path.parse(asset.name).name);
261
+ fs.writeFileSync(archivePath, archiveData);
262
+ fs.mkdirSync(extractDirectory, { recursive: true });
263
+ await decompress(archivePath, extractDirectory);
264
+
265
+ const installDirectory = resolveCompanionInstallDirectory(execPath);
266
+ for (const fileName of RUN_COMPANION_MODULE_FILENAMES) {
267
+ const sourcePath = path.join(packageDirectory, fileName);
268
+ if (!fs.existsSync(sourcePath)) {
269
+ throw new Error(
270
+ `Release ${release.tag_name} is missing ${fileName}; cannot restore the files required by 'composio run'.`
271
+ );
272
+ }
273
+
274
+ fs.copyFileSync(sourcePath, path.join(installDirectory, fileName));
275
+ }
276
+
277
+ writeInstalledReleaseTag(installDirectory, release.tag_name);
278
+ return {
279
+ repaired: true as const,
280
+ releaseTag: release.tag_name,
281
+ };
282
+ } finally {
283
+ fs.rmSync(tempDirectory, { recursive: true, force: true });
284
+ }
285
+};
286
+
287
export const resolveRunCompanionModulePath = ({
288
callerImportMetaUrl,
289
execPath,