@devries-cameron20 / composio Mirror · read-only / commits / 8fcb46bd8
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 22, 02:00 UTC

feat: adding cli touchups here (#3035)

## Summary - **Skill installer**: New `installSkill` effect that downloads and installs the `composio-cli` skill for Claude Code during `composio login`. Downloads `composio-skill.zip` from the matching GitHub release, extracts to `~/.agents/skills/composio-cli/`, and creates a symlink at `~/.claude/skills/composio-cli`. Non-fatal — wrapped in `installSkillSafe` so failures don't block login. Adds `--no-skill-install` flag to skip. - **Root help improvements**: Added `composio files` subcommand help, richer examples (multi-query search, parallel execute, multi-step `run` scripts), and inline FILES section in main help output. - **Contextual help on errors**: When a CLI command fails or receives unknown arguments, the relevant subcommand help text is now printed alongside the error message. - **Session artifacts hardening**: `resolveArtifactsRoot()` now respects `COMPOSIO_SESSION_DIR` / `COMPOSIO_CACHE_DIR` env vars and falls back to `os.tmpdir()`. All filesystem operations (mkdirSync, appendFileSync, writeFileSync) are wrapped in try/catch to avoid crashes in sandboxed environments. - **Analytics dir creation**: Wrapped `mkdirSync` for the analytics directory in try/catch (non-fatal in sandboxed environments). - **Consumer cache hardening**: Added error handling for cache read/write in sandboxed environments. - **FetchHttpClient layer**: Added `FetchHttpClient.layer` to production layers so `installSkill` HTTP requests work correctly. - **Symlink fix**: Fixed stale/broken symlink handling in `install-skill.ts` — uses `lstatSync` instead of `existsSync` to correctly detect and remove broken symlinks and directories. - **TS fix**: Changed `detectMaster` parameter type from `NodeJS.ProcessEnv` to `Record<string, string | undefined>` to avoid type conflict from bun env augmentation. - **Cleanup**: Removed accidentally committed `workdir/temp.md`. ## Test plan - [ ] `composio login` installs skill to `~/.agents/skills/composio-cli/` and creates symlink at `~/.claude/skills/composio-cli` - [ ] `composio login --no-skill-install` skips skill installation - [ ] `composio --help` shows updated examples and FILES section - [ ] Passing an unknown flag to a command prints contextual help alongside error - [ ] CLI works in sandboxed environments where `$TMPDIR` or `~/.composio/` may not be writable - [ ] `pnpm typecheck` passes with no errors 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Rahul Tarak committed Mar 26, 2026 at 23:26 UTC 8fcb46bd8be1fb90759230d794e947eb8a3f8f7e
16 files changed +411 -53
.github/workflows/build-cli-binaries.yml
+5
@@ -119,6 +119,11 @@ jobs:
119 - name: Display checksums
120 run: cat ts/packages/cli/dist/binaries/checksums.txt
121
122 + - name: Package skill files
123 + working-directory: ts/packages/cli
124 + run: |
125 + cd skills && zip -r ../dist/binaries/composio-skill.zip composio-cli/
126 +
127 - name: Create GitHub Release
128 uses: softprops/action-gh-release@v2
129 with:
ts/packages/cli/src/analytics/dispatch.ts
+5 -1
@@ -59,7 +59,11 @@ type ConsumerShortTermCacheState = Record<
59 >;
60
61 const ensureAnalyticsDir = () => {
62 - fs.mkdirSync(analyticsDir(), { recursive: true });
62 + try {
63 + fs.mkdirSync(analyticsDir(), { recursive: true });
64 + } catch {
65 + // Non-fatal — analytics directory creation may fail in sandboxed environments.
66 + }
67 };
68
69 const encodeBase64Url = (value: string): string => {
ts/packages/cli/src/cli-main.ts
+22 -4
@@ -6,6 +6,7 @@ import { FetchHttpClient } from '@effect/platform';
6 import { BunContext, BunRuntime, BunFileSystem } from '@effect/platform-bun';
7 import type { Teardown } from '@effect/platform/Runtime';
8 import { rootCommand, runWithConfig } from 'src/commands';
9 +import { matchCommandFromArgv, getCommandHelpText } from 'src/commands/root-help';
10 import * as constants from 'src/constants';
11 import { ComposioCliConfig } from 'src/cli-config';
12 import { BaseConfigProviderLive, ConfigLive, extendConfigProvider } from 'src/services/config';
@@ -104,6 +105,7 @@ const layers = Layer.mergeAll(
105 ProjectContextLive,
106 BunContext.layer,
107 BunFileSystem.layer,
108 + FetchHttpClient.layer,
109 StdinLive,
110 TerminalUILive,
111 Logger.pretty
@@ -193,11 +195,22 @@ runWithArgs.pipe(
195 ),
196 Effect.catchIf(ValidationError.isValidationError, error => {
197 const text = HelpDoc.toAnsiText(error.error).trim();
198 + const errorEffect = text.length > 0 ? Console.error(text) : Effect.void;
199 const flagMatch = text.match(/Received unknown argument: '(-{1,2}[\w-]+)'/);
197 - if (flagMatch && valueOptionNames.has(flagMatch[1])) {
198 - return Console.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`);
199 - }
200 - return Effect.void;
200 + const tipEffect =
201 + flagMatch && valueOptionNames.has(flagMatch[1])
202 + ? Console.error(`Tip: ${flagMatch[1]} requires a value, e.g. ${flagMatch[1]} "value"`)
203 + : Effect.void;
204 + const cmdName = matchCommandFromArgv(process.argv);
205 + const helpText = cmdName ? getCommandHelpText(cmdName) : undefined;
206 + const helpEffect = helpText ? Console.error(helpText) : Effect.void;
207 + return Effect.all([errorEffect, tipEffect, helpEffect], { discard: true }).pipe(
208 + Effect.tap(() =>
209 + Effect.sync(() => {
210 + process.exitCode = 1;
211 + })
212 + )
213 + );
214 }),
215 Effect.withSpan('composio-cli', {
216 attributes: {
@@ -225,6 +238,11 @@ runWithArgs.pipe(
238 ).trim();
239 if (message.length > 0) {
240 yield* Console.error(message);
241 + const cmdName = matchCommandFromArgv(process.argv);
242 + const helpText = cmdName ? getCommandHelpText(cmdName) : undefined;
243 + if (helpText) {
244 + yield* Console.error(helpText);
245 + }
246 process.exitCode = 1;
247 }
248 }
ts/packages/cli/src/commands/connected-accounts/commands/connected-accounts.link.cmd.ts
+46 -3
@@ -6,9 +6,9 @@ import { ComposioUserContext } from 'src/services/user-context';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { requireAuth } from 'src/effects/require-auth';
8 import { resolveToolRouterSession } from 'src/effects/create-tool-router-session';
9 -import { extractMessage } from 'src/utils/api-error-extraction';
9 +import { extractMessage, extractSlug } from 'src/utils/api-error-extraction';
10 import { ProjectContext } from 'src/services/project-context';
11 -import { ComposioClientSingleton } from 'src/services/composio-clients';
11 +import { ComposioClientSingleton, getSessionInfoByUserApiKey } from 'src/services/composio-clients';
12 import {
13 resolveCommandProject,
14 formatResolveCommandProjectError,
@@ -168,6 +168,40 @@ const validateLinkResponse = (
168 });
169 });
170
171 +const handleNoManagedAuth = (ui: TerminalUI, toolkitSlug: string, noBrowser: boolean) =>
172 + Effect.gen(function* () {
173 + const userContext = yield* ComposioUserContext;
174 + const webURL = userContext.data.webURL.replace(/\/+$/, '');
175 + const apiKey = Option.getOrUndefined(userContext.data.apiKey);
176 +
177 + let orgSlug = '~';
178 + if (apiKey) {
179 + const sessionInfo = yield* getSessionInfoByUserApiKey({
180 + baseURL: userContext.data.baseURL,
181 + userApiKey: apiKey,
182 + }).pipe(Effect.catchAll(() => Effect.succeed(null)));
183 +
184 + if (sessionInfo?.project.org.name) {
185 + orgSlug = sessionInfo.project.org.name;
186 + }
187 + }
188 +
189 + const dashboardUrl = `${webURL}/${orgSlug}/~/connect/apps/${toolkitSlug}?open=true`;
190 +
191 + yield* ui.log.warn(
192 + `Composio does not manage auth for "${toolkitSlug}" — opening the dashboard to connect manually.`
193 + );
194 +
195 + if (!noBrowser) {
196 + yield* Effect.tryPromise(() => open(dashboardUrl, { wait: false })).pipe(
197 + Effect.catchAll(() => ui.log.warn('Could not open the browser automatically.'))
198 + );
199 + }
200 +
201 + yield* ui.note(dashboardUrl, 'Dashboard URL');
202 + yield* ui.output(dashboardUrl, noBrowser ? { force: true } : undefined);
203 + });
204 +
205 const runConnectedAccountsLink = (params: {
206 toolkit: Option.Option<string>;
207 authConfig: Option.Option<string>;
@@ -345,6 +379,13 @@ const runConnectedAccountsLink = (params: {
379 Effect.asSome,
380 Effect.catchAll(error =>
381 Effect.gen(function* () {
382 + const slug = extractSlug(error);
383 +
384 + if (slug === 'ToolRouterV2_NoManagedAuth') {
385 + yield* handleNoManagedAuth(ui, toolkitSlug, params.noBrowser);
386 + return Option.none();
387 + }
388 +
389 const message =
390 extractMessage(error) ?? `Failed to create link for toolkit "${toolkitSlug}".`;
391 yield* ui.log.error(message);
@@ -352,6 +393,9 @@ const runConnectedAccountsLink = (params: {
393 yield* ui.log.step('Browse available toolkits:\n> composio dev toolkits list');
394 return Option.none();
395 })
396 + ),
397 + Effect.tap(() =>
398 + invalidateConsumerConnectedToolkitsCache().pipe(Effect.catchAll(() => Effect.void))
399 )
400 );
401
@@ -361,7 +405,6 @@ const runConnectedAccountsLink = (params: {
405 if (Option.isNone(validatedLink)) return;
406
407 const { connectedAccountId: connAccountId, redirectUrl } = validatedLink.value;
364 - yield* invalidateConsumerConnectedToolkitsCache().pipe(Effect.catchAll(() => Effect.void));
408
409 if (params.noWait) {
410 yield* showRedirectUrl(ui, redirectUrl, params.noBrowser);
ts/packages/cli/src/commands/login.cmd.ts
+15 -2
@@ -12,6 +12,7 @@ import { TerminalUI } from 'src/services/terminal-ui';
12 import { commandHintStep } from 'src/services/command-hints';
13 import { runOrgSelection } from 'src/effects/select-org-project';
14 import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
15 +import { installSkillSafe } from 'src/effects/install-skill';
16
17 export const noBrowser = Options.boolean('no-browser').pipe(
18 Options.withDefault(false),
@@ -36,6 +37,11 @@ const yesOpt = Options.boolean('yes').pipe(
37 Options.withDescription('Skip org picker; use session default org')
38 );
39
40 +const noSkillInstall = Options.boolean('no-skill-install').pipe(
41 + Options.withDefault(false),
42 + Options.withDescription('Skip installing the composio-cli skill for Claude Code')
43 +);
44 +
45 /**
46 * Verifies credentials via session/info and stores them.
47 *
@@ -433,8 +439,8 @@ export const browserLogin = (params: {
439 */
440 export const loginCmd = Command.make(
441 'login',
436 - { noBrowser, noWait, key: keyOpt, yes: yesOpt },
437 - ({ noBrowser, noWait, key, yes }) =>
442 + { noBrowser, noWait, key: keyOpt, yes: yesOpt, noSkillInstall },
443 + ({ noBrowser, noWait, key, yes, noSkillInstall }) =>
444 Effect.gen(function* () {
445 const ui = yield* TerminalUI;
446 const ctx = yield* ComposioUserContext;
@@ -447,6 +453,9 @@ export const loginCmd = Command.make(
453 noWait,
454 skipOrgProjectPicker: true,
455 });
456 + if (!noSkillInstall) {
457 + yield* installSkillSafe();
458 + }
459 return;
460 }
461
@@ -467,5 +476,9 @@ export const loginCmd = Command.make(
476 noWait,
477 skipOrgProjectPicker: yes,
478 });
479 +
480 + if (!noSkillInstall && !noWait) {
481 + yield* installSkillSafe();
482 + }
483 })
484 ).pipe(Command.withDescription('Log in to the Composio SDK.'));
ts/packages/cli/src/commands/root-help.ts
+97 -6
@@ -411,8 +411,10 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
411 // ── Account commands ──────────────────────────────────────────────────
412
413 login: {
414 - usage: 'composio login [--no-browser] [--no-wait] [--key text] [-y, --yes]',
415 - description: 'Log in to the Composio CLI session.',
414 + usage:
415 + 'composio login [--no-browser] [--no-wait] [--key text] [-y, --yes] [--no-skill-install]',
416 + description:
417 + 'Log in to the Composio CLI session. By default, also installs the composio-cli skill for Claude Code.',
418 options: [
419 {
420 name: '--key <text>',
@@ -423,6 +425,10 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
425 { name: '--no-browser', description: 'Login without browser interaction' },
426 { name: '--no-wait', description: 'Print login URL and session info, then exit' },
427 { name: '-y, --yes', description: 'Skip org picker; use session default org' },
428 + {
429 + name: '--no-skill-install',
430 + description: 'Skip installing the composio-cli skill for Claude Code',
431 + },
432 ],
433 },
434 logout: {
@@ -441,6 +447,39 @@ const SUBCOMMAND_HELP: Record<string, SubcommandHelp> = {
447 usage: 'composio upgrade',
448 description: 'Upgrade your Composio CLI to the latest available version.',
449 },
450 + files: {
451 + usage: 'composio files',
452 + description: 'Where the Composio CLI stores data on disk.',
453 + examples: [
454 + '~/.composio/',
455 + ' CLI configuration and cache directory.',
456 + ' user_data.json Your auth state (API key, org, base URL)',
457 + ' toolkits.json Cached toolkit list from the API',
458 + ' tools.json Cached tool definitions',
459 + ' trigger-types.json Cached trigger type definitions',
460 + ' consumer-short-term-cache.json Per-org connected toolkits cache (15-min TTL)',
461 + ' analytics.json Anonymous install ID for telemetry',
462 + '',
463 + ' All caches are safe to delete — they will be re-fetched on next use.',
464 + '',
465 + '$TMPDIR/composio/ (or COMPOSIO_SESSION_DIR / COMPOSIO_CACHE_DIR)',
466 + ' Session artifacts directory. Each CLI session gets a unique subdirectory',
467 + ' scoped to your working directory. Stores session history and files',
468 + ' created during `run` and `execute` (e.g. large tool outputs).',
469 + ' Use `composio artifacts cwd` to print the current session path.',
470 + '',
471 + '.composio/ (per-project, optional)',
472 + ' Per-directory project config. Scoped to the nearest parent that has one.',
473 + ' .env Allows COMPOSIO_ORG_ID and COMPOSIO_PROJECT_ID overrides',
474 + ' project.json Project context (org, project binding)',
475 + '',
476 + 'Environment variables that control paths:',
477 + ' COMPOSIO_SESSION_DIR Override session artifacts root',
478 + ' COMPOSIO_CACHE_DIR Override cache directory (also used for artifacts fallback)',
479 + ' COMPOSIO_CACHE_DIR is useful in sandboxed environments where ~/.composio or',
480 + ' $TMPDIR may not be writable.',
481 + ],
482 + },
483
484 // ── Tools commands ────────────────────────────────────────────────────
485
@@ -865,6 +904,29 @@ export function printSubcommandHelp(cmd: string): Effect.Effect<void> {
904 return Console.log(renderSubcommandHelp(help));
905 }
906
907 +/**
908 + * Match the command name from argv without requiring --help at the end.
909 + * Used to print contextual help alongside error messages.
910 + */
911 +export function matchCommandFromArgv(argv: ReadonlyArray<string>): string | undefined {
912 + const args = argv.slice(2).filter(a => a !== '--help' && a !== '-h' && !a.startsWith('--'));
913 + // Try longest match first: "dev toolkits list" → "dev toolkits" → "dev"
914 + for (let len = Math.min(args.length, 3); len > 0; len--) {
915 + const key = args.slice(0, len).join(' ');
916 + if (key in SUBCOMMAND_HELP) return key;
917 + }
918 + return undefined;
919 +}
920 +
921 +/**
922 + * Get rendered help text for a command, or undefined if not found.
923 + */
924 +export function getCommandHelpText(cmd: string): string | undefined {
925 + const help = SUBCOMMAND_HELP[cmd];
926 + if (!help) return undefined;
927 + return renderSubcommandHelp(help);
928 +}
929 +
930 // ── Main help output ───────────────────────────────────────────────────
931
932 /**
@@ -896,14 +958,19 @@ export function printRootHelp(): Effect.Effect<void> {
958 ...renderCompactCommands(OTHER_COMMANDS),
959 '',
960 bold('EXAMPLES'),
899 - ` ${dim('# Find a tool')}`,
900 - ` ${name} search "create github issue"`,
961 + ` ${dim('# Find tools — supports multiple queries at once')}`,
962 + ` ${name} search "send an email" "create github issue"`,
963 + ` ${name} search "list calendar events" --toolkits google_calendar --limit 5`,
964 '',
902 - ` ${dim('# Connect your GitHub account')}`,
965 + ` ${dim('# Connect your account for a toolkit')}`,
966 ` ${name} link github`,
967 '',
968 ` ${dim('# Execute a tool')}`,
906 - ` ${name} execute GITHUB_CREATE_ISSUE -d '{ repo: "owner/repo", title: "Bug" }'`,
969 + ` ${name} execute GITHUB_CREATE_ISSUE -d '{ owner: "acme", repo: "app", title: "Bug" }'`,
970 + '',
971 + ` ${dim('# Execute multiple tools in parallel')}`,
972 + ` ${name} execute -p GMAIL_SEND_EMAIL -d '{ recipient_email: "a@b.com", subject: "Hi" }' \\`,
973 + ` SLACK_SEND_A_MESSAGE_TO_A_SLACK_CHANNEL -d '{ channel: "general", text: "Hello" }'`,
974 '',
975 ` ${dim('# Call an API directly through proxy')}`,
976 ` ${name} proxy https://gmail.googleapis.com/gmail/v1/users/me/profile --toolkit gmail`,
@@ -911,12 +978,36 @@ export function printRootHelp(): Effect.Effect<void> {
978 ` ${dim('# Run a script with injected helpers')}`,
979 ` ${name} run 'const me = await execute("GITHUB_GET_THE_AUTHENTICATED_USER"); console.log(me)'`,
980 '',
981 + ` ${dim('# Run a multi-step script with Promise.all')}`,
982 + ` ${name} run '`,
983 + ` const [emails, issues] = await Promise.all([`,
984 + ` execute("GMAIL_FETCH_EMAILS", { max_results: 5 }),`,
985 + ` execute("GITHUB_LIST_REPOSITORY_ISSUES", { owner: "acme", repo: "app", state: "open" }),`,
986 + ` ]);`,
987 + ` const brief = await subAgent(\`Summarize:\\n\${emails.prompt()}\\n\${issues.prompt()}\`);`,
988 + ` console.log(brief);`,
989 + ` '`,
990 + '',
991 bold('DEVELOPER COMMANDS'),
992 ...renderCompactCommands(DEVELOPER_COMMANDS),
993 '',
994 bold('ACCOUNT'),
995 ...renderCompactCommands(ACCOUNT_COMMANDS),
996 '',
997 + bold('FILES') + dim(' (composio files --help)'),
998 + ` ${bold('~/.composio/')}`,
999 + ` CLI configuration and cache directory. Contains your auth state`,
1000 + ` (user_data.json), cached tool definitions (tools.json, toolkits.json),`,
1001 + ` trigger types, and per-org consumer caches. These caches speed up`,
1002 + ` repeated commands — safe to delete, they will be re-fetched on next use.`,
1003 + '',
1004 + ` ${bold('/tmp/composio/')}`,
1005 + ` Session artifacts directory. Each CLI session gets a unique subdirectory`,
1006 + ` scoped to your working directory. Stores session history and files`,
1007 + ` created during ${bold('run')} and ${bold('execute')} commands (e.g. downloaded attachments,`,
1008 + ` generated outputs). Use \`${name} artifacts cwd\` to print the path for`,
1009 + ` the current directory's session.`,
1010 + '',
1011 bold('FLAGS'),
1012 ' -h, --help Show help for command',
1013 ` --version Show ${name} version`,
ts/packages/cli/src/commands/tools/commands/tools.execute.cmd.ts
+1 -1
@@ -210,7 +210,7 @@ const persistLargeExecuteOutput = (toolSlug: string, json: string, sharedDirecto
210 logId: '',
211 storedInFile: true,
212 tokenCount: getExecuteOutputEncoder().encode(json).length,
213 - outputFilePath,
213 + outputFilePath: outputFilePath ?? '(could not write to disk)',
214 } satisfies StoredExecuteOutputSummary;
215 });
216
ts/packages/cli/src/commands/upgrade.cmd.ts
+5 -1
@@ -1,6 +1,7 @@
1 import { Command } from '@effect/cli';
2 import { Effect } from 'effect';
3 import { UpgradeBinary } from 'src/services/upgrade-binary';
4 +import { installSkillSafe } from 'src/effects/install-skill';
5
6 /**
7 * CLI command to upgrade the CLI to the latest available version.
@@ -13,6 +14,9 @@ import { UpgradeBinary } from 'src/services/upgrade-binary';
14 export const upgradeCmd = Command.make('upgrade', {}, () =>
15 Effect.gen(function* () {
16 const upgradeBinary = yield* UpgradeBinary;
16 - yield* upgradeBinary.upgrade();
17 + const newReleaseTag = yield* upgradeBinary.upgrade();
18 + if (newReleaseTag) {
19 + yield* installSkillSafe({ releaseTag: newReleaseTag });
20 + }
21 })
22 ).pipe(Command.withDescription('Upgrade your Composio CLI to the latest available version.'));
ts/packages/cli/src/effects/install-skill.ts new
+140
@@ -0,0 +1,140 @@
1 +import * as fs from 'node:fs';
2 +import * as path from 'node:path';
3 +import { Effect, Config, Option } from 'effect';
4 +import { HttpClient } from '@effect/platform';
5 +import { NodeOs } from 'src/services/node-os';
6 +import { TerminalUI } from 'src/services/terminal-ui';
7 +import { GITHUB_CONFIG } from 'src/effects/github-config';
8 +import { APP_VERSION } from 'src/constants';
9 +import decompress from 'decompress';
10 +
11 +const SKILL_NAME = 'composio-cli';
12 +const SKILL_ASSET_NAME = 'composio-skill.zip';
13 +
14 +/**
15 + * Install the composio-cli skill into the user's global agent skills directory.
16 + *
17 + * - Downloads composio-skill.zip from the matching CLI GitHub release
18 + * - Extracts to ~/.agents/skills/composio-cli/
19 + * - Creates a symlink at ~/.claude/skills/composio-cli → ../../.agents/skills/composio-cli
20 + *
21 + * Non-fatal: wrapped version catches all errors.
22 + */
23 +export const installSkill = (options?: { readonly releaseTag?: string }) =>
24 + Effect.gen(function* () {
25 + const os = yield* NodeOs;
26 + const ui = yield* TerminalUI;
27 + const httpClient = yield* HttpClient.HttpClient;
28 + const githubConfig = yield* Config.all(GITHUB_CONFIG);
29 + const home = os.homedir;
30 +
31 + const agentSkillDir = path.join(home, '.agents', 'skills', SKILL_NAME);
32 + const claudeSkillLink = path.join(home, '.claude', 'skills', SKILL_NAME);
33 +
34 + // Resolve the release tag — prefer explicit override, then env config, then current version
35 + const tag =
36 + options?.releaseTag ??
37 + Option.getOrElse(githubConfig.TAG, () => `@composio/cli@${APP_VERSION}`);
38 +
39 + // Find the skill asset URL from the release
40 + const releaseUrl = `${githubConfig.API_BASE_URL}/repos/${githubConfig.OWNER}/${githubConfig.REPO}/releases/tags/${encodeURIComponent(tag)}`;
41 + const releaseResponse = yield* httpClient
42 + .get(releaseUrl)
43 + .pipe(
44 + Effect.catchAll(error => Effect.fail(new Error(`Failed to fetch release ${tag}: ${error}`)))
45 + );
46 +
47 + if (releaseResponse.status < 200 || releaseResponse.status >= 300) {
48 + return yield* Effect.fail(
49 + new Error(`Release ${tag} not found (HTTP ${releaseResponse.status})`)
50 + );
51 + }
52 +
53 + const release = (yield* releaseResponse.json.pipe(
54 + Effect.catchAll(() => Effect.fail(new Error('Failed to parse release JSON')))
55 + )) as { assets: Array<{ name: string; browser_download_url: string }> };
56 +
57 + const skillAsset = release.assets.find(a => a.name === SKILL_ASSET_NAME);
58 + if (!skillAsset) {
59 + return yield* Effect.fail(
60 + new Error(`Skill asset ${SKILL_ASSET_NAME} not found in release ${tag}`)
61 + );
62 + }
63 +
64 + // Download the skill zip
65 + const downloadResponse = yield* httpClient
66 + .get(skillAsset.browser_download_url)
67 + .pipe(Effect.catchAll(error => Effect.fail(new Error(`Failed to download skill: ${error}`))));
68 +
69 + if (downloadResponse.status < 200 || downloadResponse.status >= 300) {
70 + return yield* Effect.fail(
71 + new Error(`Failed to download skill (HTTP ${downloadResponse.status})`)
72 + );
73 + }
74 +
75 + const zipData = yield* downloadResponse.arrayBuffer.pipe(
76 + Effect.catchAll(() => Effect.fail(new Error('Failed to read skill zip data')))
77 + );
78 +
79 + // Extract to a temp dir, then move into place
80 + const tmpDir = path.join(os.homedir, '.agents', '.tmp-skill-install');
81 + fs.mkdirSync(tmpDir, { recursive: true });
82 +
83 + try {
84 + const zipPath = path.join(tmpDir, SKILL_ASSET_NAME);
85 + fs.writeFileSync(zipPath, new Uint8Array(zipData));
86 +
87 + yield* Effect.tryPromise({
88 + try: () => decompress(zipPath, tmpDir),
89 + catch: error => new Error(`Failed to extract skill zip: ${error}`),
90 + });
91 +
92 + // The zip contains composio-cli/ directory
93 + const extractedDir = path.join(tmpDir, SKILL_NAME);
94 + if (!fs.existsSync(extractedDir)) {
95 + return yield* Effect.fail(new Error('Extracted skill directory not found'));
96 + }
97 +
98 + // Remove old skill dir and move new one into place
99 + fs.rmSync(agentSkillDir, { recursive: true, force: true });
100 + fs.mkdirSync(path.dirname(agentSkillDir), { recursive: true });
101 + fs.cpSync(extractedDir, agentSkillDir, { recursive: true });
102 + } finally {
103 + fs.rmSync(tmpDir, { recursive: true, force: true });
104 + }
105 +
106 + // Create symlink for Claude Code — always replace any existing entry
107 + fs.mkdirSync(path.join(home, '.claude', 'skills'), { recursive: true });
108 + try {
109 + const stat = fs.lstatSync(claudeSkillLink);
110 + // Entry exists (symlink, broken symlink, or directory) — remove it
111 + if (stat.isSymbolicLink()) {
112 + fs.unlinkSync(claudeSkillLink);
113 + } else if (stat.isDirectory()) {
114 + fs.rmSync(claudeSkillLink, { recursive: true, force: true });
115 + } else {
116 + fs.unlinkSync(claudeSkillLink);
117 + }
118 + } catch {
119 + // lstatSync throws if nothing exists at the path — that's fine
120 + }
121 + const relativeTarget = path.relative(path.dirname(claudeSkillLink), agentSkillDir);
122 + fs.symlinkSync(relativeTarget, claudeSkillLink);
123 +
124 + yield* ui.log.success('Installed composio-cli skill for Claude Code');
125 + });
126 +
127 +/**
128 + * Wrapped version that catches all errors and logs a warning instead of failing.
129 + */
130 +export const installSkillSafe = (options?: { readonly releaseTag?: string }) =>
131 + installSkill(options).pipe(
132 + Effect.sandbox,
133 + Effect.catchAll(cause =>
134 + Effect.gen(function* () {
135 + const ui = yield* TerminalUI;
136 + yield* Effect.logDebug('Skill install failed:', cause);
137 + yield* ui.log.warn('Could not install Claude Code skill (non-fatal)');
138 + })
139 + )
140 + );
ts/packages/cli/src/services/cli-session-artifacts.ts
+33 -14
@@ -1,9 +1,14 @@
1 import fs from 'node:fs';
2 +import os from 'node:os';
3 import path from 'node:path';
4 import { Effect, Option } from 'effect';
5 import { getOrCreateProbablyMyCliSessionIdForCurrentCwd } from 'src/services/consumer-short-term-cache';
6
6 -const CLI_SESSION_ARTIFACTS_ROOT = '/tmp/composio';
7 +const resolveArtifactsRoot = (): string =>
8 + process.env.COMPOSIO_SESSION_DIR?.trim() ||
9 + process.env.COMPOSIO_CACHE_DIR?.trim() ||
10 + path.join(os.tmpdir(), 'composio');
11 +
12 const SESSION_HISTORY_FILE = 'session-history.jsonl';
13
14 export type CliSessionArtifacts = {
@@ -22,13 +27,19 @@ export const resolveCliSessionArtifacts = (params?: {
27 readonly consumerUserId?: string;
28 }) =>
29 Effect.gen(function* () {
25 - const sessionIdOption = yield* getOrCreateProbablyMyCliSessionIdForCurrentCwd(params);
30 + const sessionIdOption = yield* getOrCreateProbablyMyCliSessionIdForCurrentCwd(params).pipe(
31 + Effect.catchAll(() => Effect.succeed(Option.none<string>()))
32 + );
33 if (Option.isNone(sessionIdOption)) {
34 return Option.none<CliSessionArtifacts>();
35 }
36
30 - const directoryPath = path.join(CLI_SESSION_ARTIFACTS_ROOT, sessionIdOption.value);
31 - fs.mkdirSync(directoryPath, { recursive: true });
37 + const directoryPath = path.join(resolveArtifactsRoot(), sessionIdOption.value);
38 + try {
39 + fs.mkdirSync(directoryPath, { recursive: true });
40 + } catch {
41 + return Option.none<CliSessionArtifacts>();
42 + }
43 return Option.some({
44 sessionId: sessionIdOption.value,
45 directoryPath,
@@ -55,7 +66,11 @@ export const appendCliSessionHistory = (params: {
66 sessionId: artifactsOption.value.sessionId,
67 ...params.entry,
68 });
58 - fs.appendFileSync(artifactsOption.value.historyFilePath, `${line}\n`, 'utf8');
69 + try {
70 + fs.appendFileSync(artifactsOption.value.historyFilePath, `${line}\n`, 'utf8');
71 + } catch {
72 + // Best-effort — session history write is non-fatal.
73 + }
74 });
75
76 export const storeCliSessionArtifact = (params: {
@@ -75,14 +90,18 @@ export const storeCliSessionArtifact = (params: {
90 consumerUserId: params.consumerUserId,
91 }).pipe(Effect.map(Option.map(artifacts => artifacts.directoryPath)))
92 ) ||
78 - path.join(CLI_SESSION_ARTIFACTS_ROOT, `adhoc_${randomToken(12)}`);
93 + path.join(resolveArtifactsRoot(), `adhoc_${randomToken(12)}`);
94
80 - fs.mkdirSync(directoryPath, { recursive: true });
81 - const extension = (params.extension ?? 'json').replace(/^\.+/, '') || 'json';
82 - const filePath = path.join(
83 - directoryPath,
84 - `${sanitizeArtifactName(params.name)}_${randomToken()}.${extension}`
85 - );
86 - fs.writeFileSync(filePath, params.contents, 'utf8');
87 - return filePath;
95 + try {
96 + fs.mkdirSync(directoryPath, { recursive: true });
97 + const extension = (params.extension ?? 'json').replace(/^\.+/, '') || 'json';
98 + const filePath = path.join(
99 + directoryPath,
100 + `${sanitizeArtifactName(params.name)}_${randomToken()}.${extension}`
101 + );
102 + fs.writeFileSync(filePath, params.contents, 'utf8');
103 + return filePath;
104 + } catch {
105 + return undefined;
106 + }
107 });
ts/packages/cli/src/services/consumer-short-term-cache.ts
+4 -2
@@ -101,8 +101,10 @@ const writeCache = (state: CacheState) =>
101 Effect.gen(function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const cacheDir = yield* setupCacheDir;
104 - yield* fs.makeDirectory(cacheDir, { recursive: true });
105 - yield* fs.writeFileString(cachePath(cacheDir), JSON.stringify(state, null, 2));
104 + yield* fs.makeDirectory(cacheDir, { recursive: true }).pipe(Effect.catchAll(() => Effect.void));
105 + yield* fs
106 + .writeFileString(cachePath(cacheDir), JSON.stringify(state, null, 2))
107 + .pipe(Effect.catchAll(() => Effect.void));
108 });
109
110 const getAlwaysConnectedNoAuthToolkits = () =>
ts/packages/cli/src/services/master-detector.ts
+2 -2
@@ -1,9 +1,9 @@
1 export type MasterKind = 'claude' | 'codex' | 'user';
2
3 -const hasEnvPrefix = (env: NodeJS.ProcessEnv, prefix: string): boolean =>
3 +const hasEnvPrefix = (env: Record<string, string | undefined>, prefix: string): boolean =>
4 Object.keys(env).some(key => key.startsWith(prefix));
5
6 -export const detectMaster = (env: NodeJS.ProcessEnv = process.env): MasterKind => {
6 +export const detectMaster = (env: Record<string, string | undefined> = process.env): MasterKind => {
7 if (hasEnvPrefix(env, 'CODEX_')) {
8 return 'codex';
9 }
ts/packages/cli/src/services/upgrade-binary.ts
+4 -2
@@ -482,7 +482,7 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
482 yield* ui.log.info(`New local version available (current: ${APP_VERSION})`);
483 yield* replaceBinary(upgradeTargetOpt.value, currentPath);
484 yield* ui.outro('Upgrade completed');
485 - return;
485 + return undefined;
486 }
487
488 const didUpgrade = yield* ui.useMakeSpinner('Checking for updates...', spinner =>
@@ -535,13 +535,15 @@ export class UpgradeBinary extends Effect.Service<UpgradeBinary>()('services/Upg
535 yield* replaceBinary(extractedBinaryPath, currentPath);
536
537 yield* spinner.stop('Upgrade completed!');
538 - return true;
538 + return release.tag_name;
539 })
540 );
541
542 yield* ui.outro(
543 didUpgrade ? 'Restart your terminal to use the new version.' : 'No upgrade needed.'
544 );
545 +
546 + return didUpgrade || undefined; // release tag string, or undefined if no upgrade
547 });
548
549 return {
ts/packages/cli/src/utils/api-error-extraction.ts
+27 -13
@@ -22,26 +22,40 @@ export type ApiErrorDetails = {
22 * Extract a human-readable message from an unknown error value.
23 * Checks `.message`, then `.error` (string or `.error.message`).
24 */
25 -export const extractMessage = (value: unknown): string | undefined => {
25 +export const extractMessage = (value: unknown, seen?: Set<unknown>): string | undefined => {
26 if (typeof value === 'string') return value;
27 - if (value instanceof Error) return value.message;
27 +
28 + // Walk the .cause / .error chain to find the deepest meaningful message.
29 + // Effect's UnknownException stores the real error in .cause; the Composio SDK
30 + // stores the API response body in .error (which itself has .error.message).
31 + // We prefer the deepest message because outer wrappers often have generic
32 + // messages like "An unknown error occurred in Effect.tryPromise".
33 if (value && typeof value === 'object') {
29 - if ('message' in value && typeof (value as { message?: unknown }).message === 'string') {
30 - return (value as { message: string }).message;
34 + const visited = seen ?? new Set<unknown>();
35 + if (visited.has(value)) return undefined;
36 + visited.add(value);
37 +
38 + // Try .cause chain first (Effect's UnknownException → real SDK error)
39 + if ('cause' in value) {
40 + const causeMsg = extractMessage((value as { cause?: unknown }).cause, visited);
41 + if (causeMsg) return causeMsg;
42 }
43 +
44 + // Try .error chain (SDK error → API response body → nested .error.message)
45 if ('error' in value) {
46 const inner = (value as { error?: unknown }).error;
34 - if (typeof inner === 'string') return inner;
35 - if (
36 - inner &&
37 - typeof inner === 'object' &&
38 - 'message' in inner &&
39 - typeof (inner as { message?: unknown }).message === 'string'
40 - ) {
41 - return (inner as { message: string }).message;
42 - }
47 + const innerMsg = extractMessage(inner, visited);
48 + if (innerMsg) return innerMsg;
49 + }
50 +
51 + // Fall back to the wrapper's own message
52 + if ('message' in value && typeof (value as { message?: unknown }).message === 'string') {
53 + return (value as { message: string }).message;
54 }
55 }
56 +
57 + if (value instanceof Error) return value.message;
58 +
59 return undefined;
60 };
61
ts/packages/cli/test/__utils__/services/test-layer.ts
+4 -1
@@ -873,7 +873,9 @@ export const TestLayer = (input?: TestLiveInput) =>
873 primary_tool_slugs: matchedTools.map(tool => tool.slug),
874 related_tool_slugs: [],
875 toolkits: Array.from(
876 - new Set(matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean))
876 + new Set(
877 + matchedTools.map(tool => tool.slug.split('_')[0]?.toLowerCase() ?? '').filter(Boolean)
878 + )
879 ),
880 matchedTools,
881 };
@@ -1109,6 +1111,7 @@ export const TestLayer = (input?: TestLiveInput) =>
1111 BunContext.layer,
1112 MockTerminal.layer,
1113 BunPath.layer,
1114 + FetchHttpClient.layer,
1115 ConsumerProjectResolveFetchMock,
1116 StdinTest,
1117 TerminalUILayer,
ts/packages/cli/test/src/commands/tools/tools.execute.cmd.test.ts
+1 -1
@@ -438,7 +438,7 @@ describe('CLI: composio execute', () => {
438 expect(output.logId).toBe('log_large_output');
439 expect(output.tokenCount).toBeGreaterThan(10_000);
440 expect(output.outputFilePath).toMatch(
441 - /^\/tmp\/composio\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/
441 + /composio\/[^/]+\/GMAIL_SEND_EMAIL_OUTPUT_[^.]+\.json$/
442 );
443 expect(fs.existsSync(output.outputFilePath)).toBe(true);
444 const storedJson = fs.readFileSync(output.outputFilePath, 'utf8');