@devries-cameron20 / composio Mirror · read-only
Fork 0

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

next
ts 290 lines 9.36 KB
Raw
1 // eslint-disable-next-line no-restricted-imports -- FileSystem.symlink cannot create a Windows junction, the only directory link that works without Developer Mode or administrator rights.
2 import { symlink } from 'node:fs/promises';
3 import { Data, Effect, FileSystem, Path } from 'effect';
4 import { HttpClient } from 'effect/http';
5 import { NodeOs } from 'src/services/node-os';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { GITHUB_CONFIG, type GitHubConfig } from 'src/config';
8 import { APP_VERSION, type CliReleaseChannel } from 'src/constants';
9 import { resolveRunningCliReleaseTag } from 'src/services/run-companion-modules';
10 import {
11 fetchLatestCliRelease,
12 fetchCliReleaseByTag,
13 type GitHubRelease,
14 } from 'src/effects/resolve-cli-release';
15 import { extractZipSafely } from 'src/utils/extract-zip-safely';
16
17 const SKILL_NAME = 'composio-cli';
18 const SKILL_ASSET_NAME = 'composio-skill.zip';
19 export const SKILL_RELEASE_TAG_FILENAME = '.composio-release-tag';
20 export type SkillReleaseChannel = CliReleaseChannel;
21 export type SkillInstallTarget = 'claude' | 'codex' | 'openclaw';
22
23 const SKILL_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
24
25 const SKILL_TARGET_LABELS: Record<SkillInstallTarget, string> = {
26 claude: 'Claude Code',
27 codex: 'Codex',
28 openclaw: 'OpenClaw',
29 };
30
31 const SKILL_TARGET_DIRECTORIES: Record<SkillInstallTarget, ReadonlyArray<string>> = {
32 claude: ['.claude', 'skills'],
33 codex: ['.codex', 'skills'],
34 openclaw: ['.openclaw', 'skills'],
35 };
36
37 export class SkillInstallError extends Data.TaggedError('effects/SkillInstallError')<{
38 readonly cause?: unknown;
39 readonly message: string;
40 readonly phase: 'release' | 'download' | 'extract';
41 readonly status?: number;
42 }> {}
43
44 const hasSkillAsset = (release: GitHubRelease) =>
45 release.assets.some(asset => asset.name === SKILL_ASSET_NAME);
46
47 export const resolveInstalledSkillName = (skillName?: string): string => {
48 const normalized = skillName?.trim();
49 if (!normalized) {
50 return SKILL_NAME;
51 }
52 if (normalized === '.' || normalized === '..' || !SKILL_NAME_PATTERN.test(normalized)) {
53 throw new Error(
54 'Invalid skill name. Use letters, numbers, dots, underscores, or hyphens only.'
55 );
56 }
57 return normalized;
58 };
59
60 export const resolveTargetSkillPath = ({
61 home,
62 path,
63 skillName,
64 target,
65 }: {
66 home: string;
67 path: Path.Path;
68 skillName: string;
69 target: SkillInstallTarget;
70 }): string => path.join(home, ...SKILL_TARGET_DIRECTORIES[target], skillName);
71
72 const resolveTargetLabel = (target: SkillInstallTarget): string => SKILL_TARGET_LABELS[target];
73
74 export const inferSkillReleaseChannel = (tagOrVersion: string): SkillReleaseChannel =>
75 tagOrVersion.includes('-beta.') ? 'beta' : 'stable';
76
77 export const resolveSkillReleaseTag = ({
78 channel,
79 githubConfig,
80 httpClient,
81 installedReleaseTag,
82 releaseTag,
83 }: {
84 channel?: SkillReleaseChannel;
85 githubConfig: GitHubConfig;
86 httpClient: HttpClient.HttpClient;
87 installedReleaseTag?: string;
88 releaseTag?: string;
89 }) =>
90 Effect.gen(function* () {
91 if (releaseTag) {
92 return releaseTag;
93 }
94
95 const configTag = githubConfig.tag;
96 if (configTag) {
97 return configTag;
98 }
99
100 if (installedReleaseTag) {
101 return installedReleaseTag;
102 }
103
104 const latest = yield* fetchLatestCliRelease({
105 assetDescription: SKILL_ASSET_NAME,
106 channel: channel ?? inferSkillReleaseChannel(APP_VERSION),
107 githubConfig,
108 hasRequiredAsset: hasSkillAsset,
109 httpClient,
110 });
111
112 return latest.tag_name;
113 });
114
115 /**
116 * Install the composio-cli skill into the user's global agent skills directory.
117 *
118 * - Downloads composio-skill.zip from the matching CLI GitHub release
119 * - Extracts to ~/.agents/skills/<skill-name>/
120 * - Creates a symlink in the selected agent's skills directory
121 *
122 * Non-fatal: wrapped version catches all errors.
123 */
124 export const installSkill = (options?: {
125 readonly releaseTag?: string;
126 readonly channel?: SkillReleaseChannel;
127 readonly target?: SkillInstallTarget;
128 readonly skillName?: string;
129 readonly silent?: boolean;
130 }) =>
131 Effect.gen(function* () {
132 const os = yield* NodeOs;
133 const ui = yield* TerminalUI;
134 const fs = yield* FileSystem.FileSystem;
135 const path = yield* Path.Path;
136 const httpClient = yield* HttpClient.HttpClient;
137 const githubConfig = yield* GITHUB_CONFIG;
138 const home = os.homedir;
139 const target = options?.target ?? 'claude';
140 const skillName = resolveInstalledSkillName(options?.skillName);
141
142 const agentSkillDir = path.join(home, '.agents', 'skills', skillName);
143 const targetSkillPath = resolveTargetSkillPath({ home, path, skillName, target });
144
145 const tag = yield* resolveSkillReleaseTag({
146 channel: options?.channel,
147 githubConfig,
148 httpClient,
149 installedReleaseTag: yield* resolveRunningCliReleaseTag(process.execPath, APP_VERSION),
150 releaseTag: options?.releaseTag,
151 });
152
153 const release = yield* fetchCliReleaseByTag({ githubConfig, httpClient, tag }).pipe(
154 Effect.mapError(
155 error =>
156 new SkillInstallError({
157 cause: error,
158 message: error.message,
159 phase: 'release',
160 status: error.status,
161 })
162 )
163 );
164
165 const skillAsset = release.assets.find(a => a.name === SKILL_ASSET_NAME);
166 if (!skillAsset) {
167 return yield* Effect.fail(
168 new SkillInstallError({
169 message: `Skill asset ${SKILL_ASSET_NAME} not found in release ${tag}`,
170 phase: 'release',
171 })
172 );
173 }
174
175 // Download the skill zip
176 const downloadResponse = yield* httpClient.get(skillAsset.browser_download_url).pipe(
177 Effect.mapError(
178 cause =>
179 new SkillInstallError({
180 cause,
181 message: 'Failed to download skill',
182 phase: 'download',
183 })
184 )
185 );
186
187 if (downloadResponse.status < 200 || downloadResponse.status >= 300) {
188 return yield* Effect.fail(
189 new SkillInstallError({
190 message: `Failed to download skill (HTTP ${downloadResponse.status})`,
191 phase: 'download',
192 status: downloadResponse.status,
193 })
194 );
195 }
196
197 const zipData = yield* downloadResponse.arrayBuffer.pipe(
198 Effect.mapError(
199 cause =>
200 new SkillInstallError({
201 cause,
202 message: 'Failed to read skill zip data',
203 phase: 'download',
204 })
205 )
206 );
207
208 // Extract to a temp dir, then move into place
209 const tmpDir = path.join(os.homedir, '.agents', '.tmp-skill-install');
210
211 yield* Effect.gen(function* () {
212 yield* fs.makeDirectory(tmpDir, { recursive: true });
213 const zipPath = path.join(tmpDir, SKILL_ASSET_NAME);
214 yield* fs.writeFile(zipPath, new Uint8Array(zipData));
215
216 yield* Effect.tryPromise({
217 try: () => extractZipSafely(zipPath, tmpDir),
218 catch: cause =>
219 new SkillInstallError({
220 cause,
221 message: 'Failed to extract skill zip',
222 phase: 'extract',
223 }),
224 });
225
226 // The zip contains composio-cli/ directory
227 const extractedDir = path.join(tmpDir, SKILL_NAME);
228 if (!(yield* fs.exists(extractedDir))) {
229 return yield* Effect.fail(
230 new SkillInstallError({
231 message: 'Extracted skill directory not found',
232 phase: 'extract',
233 })
234 );
235 }
236
237 yield* Effect.gen(function* () {
238 // Replace the canonical skill and agent target without interruption leaving either absent.
239 yield* fs.remove(agentSkillDir, { recursive: true, force: true });
240 yield* fs.makeDirectory(path.dirname(agentSkillDir), { recursive: true });
241 yield* fs.copy(extractedDir, agentSkillDir, { overwrite: true });
242 yield* fs.writeFileString(path.join(agentSkillDir, SKILL_RELEASE_TAG_FILENAME), `${tag}\n`);
243
244 yield* fs.makeDirectory(path.dirname(targetSkillPath), { recursive: true });
245 yield* fs.remove(targetSkillPath, { recursive: true, force: true });
246 yield* os.platform === 'win32'
247 ? Effect.tryPromise({
248 try: () => symlink(agentSkillDir, targetSkillPath, 'junction'),
249 catch: cause =>
250 new SkillInstallError({
251 cause,
252 message: `Failed to link the skill into ${targetSkillPath}`,
253 phase: 'extract',
254 }),
255 })
256 : fs.symlink(
257 path.relative(path.dirname(targetSkillPath), agentSkillDir),
258 targetSkillPath
259 );
260 }).pipe(Effect.uninterruptible);
261 }).pipe(
262 Effect.ensuring(fs.remove(tmpDir, { recursive: true, force: true }).pipe(Effect.orDie))
263 );
264
265 if (!options?.silent) {
266 yield* ui.log.success(`Installed ${skillName} skill for ${resolveTargetLabel(target)}`);
267 }
268 });
269
270 /**
271 * Wrapped version that catches all errors and logs a warning instead of failing.
272 */
273 export const installSkillSafe = (options?: {
274 readonly releaseTag?: string;
275 readonly channel?: SkillReleaseChannel;
276 readonly target?: SkillInstallTarget;
277 readonly skillName?: string;
278 readonly silent?: boolean;
279 }) =>
280 installSkill(options).pipe(
281 Effect.sandbox,
282 Effect.catch(cause =>
283 Effect.gen(function* () {
284 const ui = yield* TerminalUI;
285 yield* Effect.logDebug('Skill install failed:', cause);
286 const targetLabel = resolveTargetLabel(options?.target ?? 'claude');
287 yield* ui.log.warn(`Could not install ${targetLabel} skill (non-fatal)`);
288 })
289 )
290 );