diff --git a/.github/workflows/blank.yml b/.github/workflows/blank.yml new file mode 100644 index 00000000..01502b13 --- /dev/null +++ b/.github/workflows/blank.yml @@ -0,0 +1,36 @@ +# This is a basic workflow to help you get started with Actions + +name: CI + +# Controls when the workflow will run +on: + # Triggers the workflow on push or pull request events but only for the "main" branch + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# A workflow run is made up of one or more jobs that can run sequentially or in parallel +jobs: + # This workflow contains a single job called "build" + build: + # The type of runner that the job will run on + runs-on: ubuntu-latest + + # Steps represent a sequence of tasks that will be executed as part of the job + steps: + # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it + - uses: actions/checkout@v4 + + # Runs a single command using the runners shell + - name: Run a one-line script + run: echo Hello, world! + + # Runs a set of commands using the runners shell + - name: Run a multi-line script + run: | + echo Add other actions to build, + echo test, and deploy your project. diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..2752eb92 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.DS_Store diff --git a/README.md b/README.md index 347cf2dc..6f61d364 100644 --- a/README.md +++ b/README.md @@ -1,194 +1,35 @@ -# GitHub Copilot CLI +# Xx2Dee7xX-joke-cli -The power of GitHub Copilot, now in your terminal. +Small CLI that fetches random jokes from JokeAPI. -GitHub Copilot CLI brings AI-powered coding assistance directly to your command line, enabling you to build, debug, and understand code through natural language conversations. Powered by the same agentic harness as GitHub's Copilot coding agent, it provides intelligent assistance while staying deeply integrated with your GitHub workflow. +## Requirements -See [our official documentation](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) for more information. +- Node.js 18+ (uses global fetch and AbortController) -![Image of the splash screen for the Copilot CLI](https://github.com/user-attachments/assets/f40aa23d-09dd-499e-9457-1d57d3368887) +## Install / Run - -## 🚀 Introduction and Overview - -We're bringing the power of GitHub Copilot coding agent directly to your terminal. With GitHub Copilot CLI, you can work locally and synchronously with an AI agent that understands your code and GitHub context. - -- **Terminal-native development:** Work with Copilot coding agent directly in your command line — no context switching required. -- **GitHub integration out of the box:** Access your repositories, issues, and pull requests using natural language, all authenticated with your existing GitHub account. -- **Agentic capabilities:** Build, edit, debug, and refactor code with an AI collaborator that can plan and execute complex tasks. -- **MCP-powered extensibility:** Take advantage of the fact that the coding agent ships with GitHub's MCP server by default and supports custom MCP servers to extend capabilities. -- **Full control:** Preview every action before execution — nothing happens without your explicit approval. - -We're still early in our journey, but with your feedback, we're rapidly iterating to make the GitHub Copilot CLI the best possible companion in your terminal. - -## 📦 Getting Started - -### Supported Platforms - -- **Linux** -- **macOS** -- **Windows** - -### Prerequisites - -- (On Windows) **PowerShell** v6 or higher -- An **active Copilot subscription**. See [Copilot plans](https://github.com/features/copilot/plans?ref_cta=Copilot+plans+signup&ref_loc=install-copilot-cli&ref_page=docs). - -If you have access to GitHub Copilot via your organization or enterprise, you cannot use GitHub Copilot CLI if your organization owner or enterprise administrator has disabled it in the organization or enterprise settings. See [Managing policies and features for GitHub Copilot in your organization](http://docs.github.com/copilot/managing-copilot/managing-github-copilot-in-your-organization/managing-github-copilot-features-in-your-organization/managing-policies-for-copilot-in-your-organization) for more information. - -### Installation - -Install with the install script (macOS and Linux): - -```bash -curl -fsSL https://gh.io/copilot-install | bash -``` - -Or +Make the script executable and run locally: ```bash -wget -qO- https://gh.io/copilot-install | bash +chmod +x index.js +./index.js ``` -Use `| sudo bash` to run as root and install to `/usr/local/bin`. - -Set `PREFIX` to install to `$PREFIX/bin/` directory. Defaults to `/usr/local` -when run as root or `$HOME/.local` when run as a non-root user. - -Set `VERSION` to install a specific version. Defaults to the latest version. - -For example, to install version `v0.0.369` to a custom directory: +Or run with node directly: ```bash -curl -fsSL https://gh.io/copilot-install | VERSION="v0.0.369" PREFIX="$HOME/custom" bash +node index.js --category Programming --repeat 3 ``` -Install with [Homebrew](https://formulae.brew.sh/cask/copilot-cli) (macOS and Linux): - -```bash -brew install copilot-cli -``` - -```bash -brew install copilot-cli@prerelease -``` - - -Install with [WinGet](https://github.com/microsoft/winget-cli) (Windows): - -```bash -winget install GitHub.Copilot -``` - -```bash -winget install GitHub.Copilot.Prerelease -``` - - -Install with [npm](https://www.npmjs.com/package/@github/copilot) (macOS, Linux, and Windows): - -```bash -npm install -g @github/copilot -``` - -```bash -npm install -g @github/copilot@prerelease -``` - - -### Launching the CLI - -```bash -copilot -``` - -On first launch, you'll be greeted with our adorable animated banner! If you'd like to see this banner again, launch `copilot` with the `--banner` flag. - -If you're not currently logged in to GitHub, you'll be prompted to use the `/login` slash command. Enter this command and follow the on-screen instructions to authenticate. - -#### Authenticate with a Personal Access Token (PAT) - -You can also authenticate using a fine-grained PAT with the "Copilot Requests" permission enabled. - -1. Visit https://github.com/settings/personal-access-tokens/new -2. Under "Permissions," click "add permissions" and select "Copilot Requests" -3. Generate your token -4. Add the token to your environment via the environment variable `GH_TOKEN` or `GITHUB_TOKEN` (in order of precedence) - -### Using the CLI - -Launch `copilot` in a folder that contains code you want to work with. - -By default, `copilot` utilizes Claude Sonnet 4.5. Run the `/model` slash command to choose from other available models, including Claude Sonnet 4 and GPT-5. - -### Experimental Mode - -Experimental mode enables access to new features that are still in development. You can activate experimental mode by: - -- Launching with the `--experimental` flag: `copilot --experimental` -- Using the `/experimental` slash command from within the CLI - -Once activated, the setting is persisted in your config, so the `--experimental` flag is no longer needed on subsequent launches. - -#### Experimental Features - -- **Autopilot mode:** Autopilot is a new mode (press `Shift+Tab` to cycle through modes), which encourages the agent to continue working until a task is completed. - -Each time you submit a prompt to GitHub Copilot CLI, your monthly quota of premium requests is reduced by one. For information about premium requests, see [About premium requests](https://docs.github.com/copilot/managing-copilot/monitoring-usage-and-entitlements/about-premium-requests). - -For more information about how to use the GitHub Copilot CLI, see [our official documentation](https://docs.github.com/copilot/concepts/agents/about-copilot-cli). - -## 🔧 Configuring LSP Servers - -GitHub Copilot CLI supports Language Server Protocol (LSP) for enhanced code intelligence. This feature provides intelligent code features like go-to-definition, hover information, and diagnostics. - -### Installing Language Servers - -Copilot CLI does not bundle LSP servers. You need to install them separately. For example, to set up TypeScript support: - -```bash -npm install -g typescript-language-server -``` - -For other languages, install the corresponding LSP server and configure it following the same pattern shown below. - -### Configuring LSP Servers - -LSP servers are configured through a dedicated LSP configuration file. You can configure LSP servers at the user level or repository level: - -**User-level configuration** (applies to all projects): -Edit `~/.copilot/lsp-config.json` - -**Repository-level configuration** (applies to specific project): -Create `.github/lsp.json` in your repository root - -Example configuration: - -```json -{ - "lspServers": { - "typescript": { - "command": "typescript-language-server", - "args": ["--stdio"], - "fileExtensions": { - ".ts": "typescript", - ".tsx": "typescript" - } - } - } -} -``` - -### Viewing LSP Server Status - -Check configured LSP servers using the `/lsp` command in an interactive session, or view your configuration files directly. - -For more information, see the [changelog](./changelog.md). - -## 📢 Feedback and Participation +## Options -We're excited to have you join us early in the Copilot CLI journey. +- `--category, -c` Joke category (Any, Programming, Misc, Dark, Pun, Spooky, Christmas, etc.) +- `--unsafe` Allow all flags (disables blacklist). By default explicit/racist/etc. are filtered. +- `--timeout` Fetch timeout in milliseconds (default 5000) +- `--retries` Number of retries on network errors (default 2) +- `--repeat` How many jokes to fetch (default 1) -We're building quickly. Expect frequent updates--please keep your client up to date for the latest features and fixes! +## Notes -Your insights are invaluable! Open an issue in this repo, join Discussions, and run `/feedback` from the CLI to submit a confidential feedback survey! +- The CLI uses [JokeAPI](https://v2.jokeapi.dev). No API key is required. +- For Node <18 support, add a polyfill such as `node-fetch` and update the script accordingly. diff --git a/index.js b/index.js new file mode 100644 index 00000000..511f9468 --- /dev/null +++ b/index.js @@ -0,0 +1,136 @@ +#!/usr/bin/env node +/** + * Random Joke CLI (no dependencies) + * + * Usage: + * node index.js [--category Any] [--unsafe] [--timeout 5000] [--retries 2] [--repeat 1] + * + * Examples: + * ./index.js + * ./index.js --category Programming + * ./index.js --unsafe --repeat 3 + */ + +const DEFAULT_TIMEOUT = 5000; // ms +const DEFAULT_RETRIES = 2; +const DEFAULT_REPEAT = 1; + +function parseArgs(argv) { + const args = { + category: 'Any', + safe: true, + timeout: DEFAULT_TIMEOUT, + retries: DEFAULT_RETRIES, + repeat: DEFAULT_REPEAT, + }; + + for (let i = 2; i < argv.length; i++) { + const a = argv[i]; + if (a === '--category' || a === '-c') { + args.category = argv[++i] || 'Any'; + } else if (a === '--unsafe') { + args.safe = false; + } else if (a === '--timeout') { + args.timeout = Number(argv[++i]) || DEFAULT_TIMEOUT; + } else if (a === '--retries') { + args.retries = Math.max(0, Number(argv[++i]) || DEFAULT_RETRIES); + } else if (a === '--repeat') { + args.repeat = Math.max(1, Number(argv[++i]) || DEFAULT_REPEAT); + } else if (a === '--help' || a === '-h') { + printHelpAndExit(); + } else { + console.warn(`Unknown arg: ${a}`); + printHelpAndExit(1); + } + } + return args; +} + +function printHelpAndExit(code = 0) { + console.log(` +Random Joke CLI + +Usage: + index.js [--category ] [--unsafe] [--timeout ] [--retries ] [--repeat ] + +Options: + --category, -c Joke category (Any, Programming, Misc, Dark, Pun, Spooky, Christmas, etc.) + --unsafe Allow all flags (disables blacklist). By default explicit/racist/etc. are filtered. + --timeout Fetch timeout in milliseconds (default ${DEFAULT_TIMEOUT}) + --retries Number of retries on network errors (default ${DEFAULT_RETRIES}) + --repeat How many jokes to fetch (default ${DEFAULT_REPEAT}) + --help, -h Show this help +`); + process.exit(code); +} + +async function fetchWithTimeout(url, timeoutMs, retries) { + let lastErr = null; + for (let attempt = 0; attempt <= retries; attempt++) { + const controller = new AbortController(); + const id = setTimeout(() => controller.abort(), timeoutMs); + + try { + const res = await fetch(url, { signal: controller.signal }); + clearTimeout(id); + if (!res.ok) { + lastErr = new Error(`HTTP ${res.status}`); + // For 4xx/5xx, don't retry further in many cases, but we'll retry anyway a limited number of times. + throw lastErr; + } + const data = await res.json(); + return data; + } catch (err) { + clearTimeout(id); + lastErr = err; + const isAbort = err.name === 'AbortError'; + const isLast = attempt === retries; + if (isLast) break; + const backoff = 200 * Math.pow(2, attempt); // simple exponential backoff + await new Promise(r => setTimeout(r, backoff)); + } + } + throw lastErr; +} + +function buildUrl(category, safe) { + const base = 'https://v2.jokeapi.dev/joke'; + const cat = encodeURIComponent(category || 'Any'); + const params = new URLSearchParams(); + if (safe) params.set('blacklistFlags', 'nsfw,religious,political,racist,sexist,explicit'); + // You can add other params like lang= or format= + return `${base}/${cat}?${params.toString()}`; +} + +function printJoke(data) { + if (!data) return; + if (data.error) { + console.error('API error:', data.message || JSON.stringify(data)); + return; + } + if (data.type === 'single') { + console.log(data.joke); + } else { + console.log(data.setup); + console.log(data.delivery); + } +} + +async function main() { + const opts = parseArgs(process.argv); + const url = buildUrl(opts.category, opts.safe); + + for (let i = 0; i < opts.repeat; i++) { + try { + const data = await fetchWithTimeout(url, opts.timeout, opts.retries); + printJoke(data); + if (i < opts.repeat - 1) console.log('---'); // separator between jokes + } catch (err) { + console.error('Failed to fetch joke:', err.message || err); + process.exitCode = 1; + return; + } + } +} + +main(); diff --git a/package.json b/package.json new file mode 100644 index 00000000..47d85f77 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "Xx2Dee7xX-joke-cli", + "version": "0.1.0", + "description": "Small CLI that fetches random jokes from JokeAPI", + "bin": { + "random-joke": "index.js" + }, + "engines": { + "node": ">=18" + }, + "license": "MIT" +}