Skip to content
Back to search

ccg

MarketplaceWorks with Claude CodeGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/fengshao1227/ccg-workflow with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/fengshao1227/ccg-workflow'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/fengshao1227--ccg-workflow/badge.svg)](/listings/fengshao1227--ccg-workflow)

HTML

<a href="/listings/fengshao1227--ccg-workflow"><img src="/api/listings/fengshao1227--ccg-workflow/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**Option A — full install (multi-model orchestration + commands + hooks + binary, recommended)**

# Install (interactive 4-step wizard)
npx ccg-workflow

# Or non-interactive with defaults
npx ccg-workflow init --skip-prompt

Requires **Node.js 20+** and **Claude Code CLI**. Codex CLI, Grok CLI, Kimi Code CLI, and Antigravity are optional (enable multi-model features).

**Option B — native plugin (skills only, zero dependencies, v3.5.1+)**

Want just the skills (web-ops toolkit, quality gates, frontend-design, domain knowledge) without the multi-model orchestration?

claude plugin marketplace add fengshao1227/ccg-workflow
claude plugin install ccg@ccg

Skills are invoked as `/ccg:<skill>`. No npx, no binary. The multi-model commands ship only through Option A (their templates carry install-time placeholders that a native plugin can't resolve).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 27 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "ccg",
  3. "owner": {
  4. "name": "fengshao1227",
  5. "url": "https://github.com/fengshao1227"
  6. },
  7. "metadata": {
  8. "description": "CCG multi-model collaboration system — install the skills natively via Claude Code plugins, or the full workflow (commands + hooks + binary) via `npx ccg-workflow`.",
  9. "version": "3.7.4"
  10. },
  11. "plugins": [
  12. {
  13. "name": "ccg",
  14. "source": ".",
  15. "description": "All CCG skills in one install: bt-panel / seo-page-builder / adsense-site-auditor / scrapling, the verify-* quality gates + gen-docs, the Impeccable-fused frontend-design skill, and 60+ domain-knowledge references. Invoked as /ccg:<skill>.",
  16. "version": "3.7.4",
  17. "category": "workflow",
  18. "keywords": [
  19. "skills",
  20. "deployment",
  21. "seo",
  22. "frontend-design",
  23. "code-review"
  24. ]
  25. }
  26. ]
  27. }
README.md · README · 384 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # CCG - Claude + Codex + Gemini Multi-Model Collaboration
  2. <div align="center">
  3. <img src="assets/logo/ccg-logo-cropped.png" alt="CCG Workflow" width="400">
  4. [![GitHub stars](https://img.shields.io/github/stars/fengshao1227/ccg-workflow?style=social)](https://github.com/fengshao1227/ccg-workflow)
  5. [![NPM Downloads](https://img.shields.io/npm/dt/ccg-workflow?style=flat-square&color=blue)](https://www.npmjs.com/package/ccg-workflow)
  6. [![npm version](https://img.shields.io/npm/v/ccg-workflow.svg)](https://www.npmjs.com/package/ccg-workflow)
  7. [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
  8. [![CI](https://github.com/fengshao1227/ccg-workflow/actions/workflows/ci.yml/badge.svg)](https://github.com/fengshao1227/ccg-workflow/actions/workflows/ci.yml)
  9. [![codecov](https://codecov.io/gh/fengshao1227/ccg-workflow/graph/badge.svg)](https://codecov.io/gh/fengshao1227/ccg-workflow)
  10. [![Claude Code](https://img.shields.io/badge/Claude%20Code-Compatible-green.svg)](https://claude.ai/code)
  11. [![Node](https://img.shields.io/badge/Node.js-%3E%3D20-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
  12. [![Follow on X](https://img.shields.io/badge/X-@CCG__Workflow-black?logo=x&logoColor=white)](https://x.com/CCG_Workflow)
  13. ![star](https://atomgit.com/fengshao1227/ccg-workflow/star/badge.svg)
  14. [![Docs](https://img.shields.io/badge/Docs-ccg.fengshao1227.com-blue?style=for-the-badge&logo=readthedocs&logoColor=white)](https://ccg.fengshao1227.com/)
  15. [![Ask DeepWiki](https://img.shields.io/badge/Ask-DeepWiki-blue?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTEyIDJDNi40OCAyIDIgNi40OCAyIDEyczQuNDggMTAgMTAgMTAgMTAtNC40OCAxMC0xMFMxNy41MiAyIDEyIDJ6bTEgMTdoLTJ2LTJoMnYyem0yLjA3LTcuNzVsLS45Ljkydi4wMUM0LjE3IDEyLjE3IDE0IDEzIDE0IDEzaC0yYzAtMS4xLjktMiAyLTJzMi0uOSAyLTItLjktMi0yLTJINmMwLTIuMjEgMS43OS00IDQtNGgyYzIuMjEgMCA0IDEuNzkgNCA0IDAgLjg4LS4zNiAxLjY4LS45MyAyLjI1eiIgZmlsbD0id2hpdGUiLz48L3N2Zz4=)](https://deepwiki.com/fengshao1227/ccg-workflow)
  16. [简体中文](./README.zh-CN.md) | English | [**Documentation**](https://ccg.fengshao1227.com/)
  17. </div>
  18. ## ♥️ Sponsor
  19. [![PackyCode](assets/sponsors/packycode.png)](https://www.packyapi.ai/register?aff=m21P)
  20. Thanks to [PackyCode](https://www.packyapi.ai/register?aff=m21P) for sponsoring this project! PackyCode is a stable, high-throughput API gateway for leading models — one domain, one key, automatic failover, 97% availability. Dedicated high-speed routes for Codex and Claude Code. Pay in RMB 1:1 with no FX markup or top-up fees; new users get a first-charge discount plus $1 in free credits, and eligible groups start from 20% of list price. [Sign up here](https://www.packyapi.ai/register?aff=m21P) to get started.
  21. > 💡 PackyCode also exposes an Anthropic-compatible endpoint, so it can serve as your API provider for Claude Code itself — run `npx ccg-workflow`, pick PackyCode at Step 1, and paste your key.
  22. ---
  23. [![APIMart](assets/sponsors/apimart.jpg)](https://go.apimart.ai/gh-ccg-workflow)
  24. Thanks to [APIMart](https://go.apimart.ai/gh-ccg-workflow) for sponsoring this project! APIMart is a low-cost API platform for AI image & video generation — GPT-Image-2 from $0.006/image, 160+ images per dollar. One async API covers both image and video: submit a task, get an ID, fetch results via polling or callback. Batch tens of thousands of images without timeouts, switch models without changing code. Pay-as-you-go with no monthly fee — [sign up here](https://go.apimart.ai/gh-ccg-workflow) to get started.
  25. > 💡 APIMart also exposes an Anthropic-compatible endpoint, so it can serve as your API provider for Claude Code itself — run `npx ccg-workflow`, pick APIMart at Step 1, and paste your key.
  26. ---
  27. [![x6.ai](assets/sponsors/x6ai.png)](https://x6.ai)
  28. [x6.ai](https://x6.ai): One API key for every major model. Official-key and proxy channels, up to 90% off, free credits on sign-up. Pay with Alipay, Google Pay, Apple Pay, Visa or Mastercard.
  29. > 💡 x6.ai also exposes an Anthropic-compatible endpoint, so it can serve as your API provider for Claude Code itself — run `npx ccg-workflow`, pick x6.ai at Step 1, and paste your key.
  30. ---
  31. ## Choose the skills you use (v3.7.0)
  32. Install native skills independently, or select them during the CCG setup wizard. Each selected skill gets a `ccg-` entry; its scripts and references live in a versioned source cache.
  33. ```bash
  34. npx ccg-workflow skills catalog
  35. npx ccg-workflow skills install verify-quality seo-page-builder
  36. npx ccg-workflow skills list --installed --json
  37. npx ccg-workflow skills update
  38. npx ccg-workflow skills remove seo-page-builder
  39. # Codex native skills
  40. npx ccg-workflow skills install verify-quality --target codex
  41. # Configure the framework with a saved selection
  42. npx ccg-workflow init --skills verify-quality,verify-security
  43. npx ccg-workflow doctor --json
  44. ```
  45. Claude Code uses `/ccg-verify-quality`; Codex uses `$ccg-verify-quality`. The manager exposes only selected entries, keeps supporting resources together, refuses ownership conflicts and preserves edited caches. The menu has **S. Manage Skills** and **V. Doctor**. Reinstalling retains the latest selection; `--skills all` selects the catalog and `--skills none` selects none. Existing full installations remain available as compatibility mode.
  46. `doctor --json` returns a versioned report with check IDs, status, remediation, and failure/warning counts. It detects the actual Claude/Codex/Skills-only mode, validates the selected backends (including review routes), Hook registrations and managed skills. Failures exit with code 1. Version and filesystem checks establish configuration health; they do not call a model or prove vendor API access.
  47. Standalone Codex mode checks its own CLI, configuration and installed files. Missing shared Claude routing is optional; missing external delegation tools are reported as warnings with setup instructions.
  48. Model-action Hooks now follow the configured routes and concrete model IDs, avoid duplicate calls to one backend, and use native Agents for pure Claude setups. Native mode uses on-demand skill discovery; legacy knowledge excerpts have a fixed size limit.
  49. ### Use an OpenCode worker, including DeepSeek
  50. Configure your provider in OpenCode with `/connect`, then query `opencode models` (or `opencode models deepseek`) for its actual model IDs. In CCG's model menu choose **OpenCode** and enter that `provider/model`. Keep Claude Code as the coordinator; the worker runs through the existing wrapper. CCG preserves the chosen model when changing routing, reinstalling or updating, and does not manage the provider credentials.
  51. ## 🐳 CCG on DeepSeek Harness — `dsh-ccg`
  52. The same role matrix, running natively inside [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness). It ships **inside this package** — no second install, no second version to track.
  53. ```bash
  54. npx ccg-workflow dsh install # every profile found; --profile <name> for one
  55. npx ccg-workflow dsh list # which profiles have it
  56. ```
  57. Or pick **`D. DeepSeek Harness`** from `npx ccg-workflow`.
  58. Requires dsh `0.2.0-rc.2` or `0.2.1-alpha.2`. After updating CCG, run `npx ccg-workflow@latest dsh install` again and restart dsh. Configuration now belongs to each profile's `cordis.patch.yml`; the CCG card is in Settings › Built-in plugins.
  59. Seven role-pinned delegation tools, each on its own model with its own expert persona — and two things the Claude Code side cannot do as cleanly:
  60. - **Model panels.** Give one role several models and they all answer the same brief independently, rendered **side by side in the conversation**. Nothing votes, nothing is averaged — disagreement is the finding.
  61. - **Live teammates.** `ccg_team` hires a role as a colleague that stays alive across turns, owns its own files (a colliding hire is *refused*, not warned about), and reports back on its own. Every hire asks you to approve it first.
  62. No external CLI, no binary bridge, no cold-start tax — every hop is a provider API request. Source lives in [`dsh-ccg/`](./dsh-ccg); [full README →](./dsh-ccg/README.md)
  63. ## 🧩 Also by the author
  64. **[DSH Marketplace](https://dshmarketplace.dev/)** — a directory of [DeepSeek Harness plugins](https://dshmarketplace.dev/plugins). 2,500+ indexed across 14 categories, bilingual EN / 中文.
  65. Not a sponsor — same author as CCG, built out of a plain annoyance: DSH plugins are multiplying fast, but figuring out what one does, whether it still installs, and what the command actually is meant opening one GitHub README after another. So the install commands here are put through a throwaway container first. **A plugin only gets a check mark if it really installs — and if it can't, the listing says why** (buried in a monorepo subdirectory, never published to npm, and so on). A verified index, not another awesome list.
  66. ```bash
  67. dsh plugin --profile web add dshmarketplace-plugin # browse the store from inside DSH
  68. npx dshmarketplace-cli add owner/repo # install any plugin from your shell
  69. ```
  70. There is also a [Python SDK](https://github.com/DshMarketPlace/dshmarketplace-py) and a [public API](https://dshmarketplace.dev/api-docs). Early days — bug reports and plugin submissions are very welcome on [GitHub](https://github.com/DshMarketPlace).
  71. ---
  72. ## What is CCG?
  73. **CCG is a workflow engine for Claude Code.** It turns Claude into a multi-model orchestrator — Claude stays in control while dispatching specialized work to Codex (OpenAI), Grok (xAI), Kimi Code (Moonshot), and Antigravity through a Go binary bridge.
  74. One command. Describe what you want. The engine handles the rest.
  75. ```bash
  76. npx ccg-workflow # Install in 60 seconds
  77. ```
  78. ## Architecture
  79. <div align="center">
  80. <img src="assets/readme/architecture.png" alt="CCG Architecture" width="800">
  81. </div>
  82. **Claude Code** is the lead orchestrator. It analyzes your intent, selects a strategy, and manages the entire workflow. The **Hook Engine** injects state every turn so Claude never loses context — even after compaction. The **codeagent-wrapper** (a compiled Go binary) bridges Claude to external models for parallel analysis and review.
  83. ## How It Works
  84. ```
  85. You: /ccg:go add JWT authentication to this API
  86. CCG Engine:
  87. 1. Reads project context (git status, tech stack, file structure)
  88. 2. Classifies: feature / L complexity / backend / high risk
  89. 3. Selects strategy: full-collaborate
  90. 4. Creates .ccg/tasks/add-jwt-auth/task.json
  91. 5. Launches dual-model analysis (Codex + Gemini in parallel)
  92. 6. Produces plan → HARD STOP for your approval
  93. 7. Spawns Agent Teams Builders for parallel implementation
  94. 8. Runs quality gates + dual-model cross-review
  95. 9. Reports results
  96. Every turn, a hook injects:
  97. <ccg-state>
  98. Task: add-jwt-auth (in_progress)
  99. Strategy: full-collaborate
  100. Phase: 4-implementation
  101. </ccg-state>
  102. ```
  103. ## 10 Built-in Strategies
  104. The engine auto-selects the right strategy based on task type and complexity:
  105. | Strategy | When | External Models | Agent Teams |
  106. |----------|------|:---:|:---:|
  107. | `direct-fix` | Simple bug, single file | — | — |
  108. | `quick-implement` | Small feature, clear scope | — | — |
  109. | `guided-develop` | Medium feature, needs planning | Single | — |
  110. | `full-collaborate` | Complex feature, multi-module | Dual parallel | ✓ |
  111. | `debug-investigate` | Complex bug, unknown cause | Dual diagnosis | — |
  112. | `refactor-safely` | Code restructuring | Dual review | — |
  113. | `deep-research` | Technical research | Dual exploration | — |
  114. | `optimize-measure` | Performance optimization | Optional | — |
  115. | `review-audit` | Code review | Dual cross-review | — |
  116. | `git-action` | commit, rollback, branches | — | — |
  117. Simple tasks run fast with zero overhead. Complex tasks get the full engine.
  118. ## Core Features
  119. ### Hook Engine — Never Lose Context
  120. 4 JavaScript hooks inject state into every Claude Code session:
  121. | Hook | Event | What it does |
  122. |------|-------|-------------|
  123. | `workflow-state.js` | Every turn | Injects current task state as breadcrumb |
  124. | `session-start.js` | Session start/compact | Re-injects full project context |
  125. | `subagent-context.js` | Agent/Bash spawn | Injects spec directly into subagent prompts |
  126. | `skill-router.js` | Every turn | Auto-injects domain knowledge by keyword |
  127. Context survives compaction. Sub-agents born with spec in their prompt. Zero state loss.
  128. ### Task System — Persistent Lifecycle
  129. Medium+ complexity tasks get a persistent directory:
  130. ```
  131. .ccg/tasks/add-jwt-auth/
  132. ├── task.json # Status, strategy, phase, gate
  133. ├── requirements.md # Enhanced requirements
  134. ├── plan.md # Approved implementation plan
  135. ├── context.jsonl # Spec files for sub-agent injection
  136. ├── review.md # Review results
  137. └── research/ # Persisted research findings
  138. ```
  139. ### Quality Gates — Built-in Security & Quality
  140. | Gate | Trigger |
  141. |------|---------|
  142. | `/ccg:verify-security` | New modules, security changes |
  143. | `/ccg:verify-quality` | Changes > 30 lines |
  144. | `/ccg:verify-change` | Doc sync check |
  145. | `/ccg:verify-module` | Module structure check |
  146. | `/ccg:gen-docs` | Auto-generate README + DESIGN |
  147. ### 100+ Domain Knowledge Files
  148. When your message mentions security, caching, RAG, Kubernetes, etc., the relevant knowledge file is auto-injected. 10 domains, 61 files:
  149. `Security` · `Architecture` · `DevOps` · `AI/MLOps` · `Development` · `Frontend Design` · `Infrastructure` · `Mobile` · `Data Engineering` · `Orchestration`
  150. ### Standalone Skills — battle-tested website workflows (v3.5.1)
  151. Self-contained skills, each usable on its own or auto-triggered by intent. Drawn from real site-building work and shipped with their scripts:
  152. | Skill | What it does |
  153. |-------|-------------|
  154. | `/ccg:bt-panel` | Drive a **BaoTa / aaPanel** server over its HTTP API — deploy a build, update a live site, read/write files, run shell, run MySQL. No SSH or rsync; just a panel URL + API key. Ships `bt_client.py` + one-shot `bt_deploy.py`. |
  155. | `/ccg:seo-page-builder` | Build, audit, or optimize **SEO tool pages** (AI generator / remover / enhancer / converter / editor). SERP-intent driven, with a runnable `onpage-audit.py` keyword-density meter. |
  156. | `/ccg:adsense-site-auditor` | Audit a site for **Google AdSense** readiness against the full official checklist — eligibility, ownership, content quality, ads.txt, privacy, Publisher Policies — before you apply or after a rejection. |
  157. > `bt-panel` reads credentials only from env vars / a git-ignored `sites.json`; nothing is hardcoded. `seo-page-builder` is adapted from yuzeiki's skill of the same name (see its SKILL.md).
  158. ## Commands
  159. ### Core (v3.0 default: 13 commands)
  160. | Command | Description |
  161. |---------|-------------|
  162. | `/ccg:go` | **Smart entry** — describe what you want, engine handles the rest |
  163. | `/ccg:commit` | Smart conventional commit |
  164. | `/ccg:rollback` | Interactive rollback |
  165. | `/ccg:clean-branches` | Clean merged branches |
  166. | `/ccg:worktree` | Worktree management |
  167. | `/ccg:init` | Initialize project CLAUDE.md |
  168. | `/ccg:context` | Project context management |
  169. ### OpenSpec Integration
  170. | Command | Description |
  171. |---------|-------------|
  172. | `/ccg:spec-init` | Initialize OPSX environment |
  173. | `/ccg:spec-research` | Requirements → constraints |
  174. | `/ccg:spec-plan` | Constraints → zero-decision plan |
  175. | `/ccg:spec-impl` | Execute plan + archive |
  176. | `/ccg:spec-review` | Dual-model cross-review |
  177. ### Legacy Mode (18 additional commands)
  178. Includes `/ccg:workflow`, `/ccg:plan`, `/ccg:execute`, `/ccg:frontend`, `/ccg:backend`, `/ccg:analyze`, `/ccg:debug`, `/ccg:optimize`, `/ccg:test`, `/ccg:review`, `/ccg:team`, and more.
  179. ## Quick Start
  180. **Option A — full install (multi-model orchestration + commands + hooks + binary, recommended)**
  181. ```bash
  182. # Install (interactive 4-step wizard)
  183. npx ccg-workflow
  184. # Or non-interactive with defaults
  185. npx ccg-workflow init --skip-prompt
  186. ```
  187. Requires **Node.js 20+** and **Claude Code CLI**. Codex CLI, Grok CLI, Kimi Code CLI, and Antigravity are optional (enable multi-model features).
  188. **Option B — native plugin (skills only, zero dependencies, v3.5.1+)**
  189. Want just the skills (web-ops toolkit, quality gates, frontend-design, domain knowledge) without the multi-model orchestration?
  190. ```bash
  191. claude plugin marketplace add fengshao1227/ccg-workflow
  192. claude plugin install ccg@ccg
  193. ```
  194. Skills are invoked as `/ccg:<skill>`. No npx, no binary. The multi-model commands ship only through Option A (their templates carry install-time placeholders that a native plugin can't resolve).
  195. ## CLI Commands
  196. ```bash
  197. npx ccg-workflow # Interactive menu
  198. npx ccg-workflow init # 4-step install wizard
  199. npx ccg-workflow doctor # Environment health check
  200. npx ccg-workflow doctor --json # Machine-readable health report
  201. npx ccg-workflow skills list # Catalog and native selection
  202. npx ccg-workflow status # Installation overview
  203. npx ccg-workflow codex-mode install # Install Codex-Led mode
  204. npx ccg-workflow codex-mode uninstall # Uninstall Codex-Led mode
  205. npx ccg-workflow dsh install # Install CCG into DeepSeek Harness
  206. npx ccg-workflow dsh list # Which dsh profiles have it
  207. npx ccg-workflow dsh uninstall # Remove it from every profile
  208. npx ccg-workflow uninstall # Uninstall CCG
  209. npx ccg-workflow config mcp # Configure MCP tokens
  210. npx ccg-workflow diagnose-mcp # Diagnose MCP issues
  211. ```
  212. ## Configuration
  213. ```
  214. ~/.claude/
  215. ├── commands/ccg/ # Slash commands
  216. ├── hooks/ccg/ # Hook scripts (5 files)
  217. ├── skills/ccg/ # Legacy bundled skills
  218. ├── skills/ccg-<slug> # Selected native skill entries
  219. ├── .ccg-skills/ # Native selection manifest and resource cache
  220. ├── rules/ # Auto-trigger rules
  221. ├── .ccg/
  222. │ ├── config.toml # Model routing, MCP, performance
  223. │ ├── engine/ # 10 strategy files + model router
  224. │ └── prompts/ # Expert prompts (codex/gemini/claude)
  225. └── bin/codeagent-wrapper # Multi-model bridge (Go binary)
  226. ```
  227. ### Environment Variables
  228. Set in `~/.claude/settings.json` under `"env"`:
  229. | Variable | Default | Description |
  230. |----------|---------|-------------|
  231. | `CODEX_TIMEOUT` | `7200` | Wrapper timeout (seconds) |
  232. | `CODEAGENT_POST_MESSAGE_DELAY` | `5` | Post-completion delay |
  233. | `CODEAGENT_BROWSER` | `default` | Set to `builtin` to stop opening the system browser for the Web UI |
  234. | `CODEAGENT_AGY_SETTINGS` | - | Settings file passed to agy as `--settings` (needs an agy that has the flag) |
  235. | `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | unset | Set `1` for parallel Agent Teams |
  236. ## Update / Uninstall
  237. ```bash
  238. npx ccg-workflow@latest # Update to latest
  239. npx ccg-workflow doctor # Check health after update
  240. npx ccg-workflow uninstall # Clean uninstall
  241. ```
  242. ## Credits
  243. - [stellarlinkco/myclaude](https://github.com/stellarlinkco/myclaude) — codeagent-wrapper inspiration
  244. - [UfoMiao/zcf](https://github.com/UfoMiao/zcf) — Git tools reference
  245. - [mindfold-ai/Trellis](https://github.com/mindfold-ai/Trellis) — Hook-based workflow state patterns
  246. - [ace-tool](https://linux.do/t/topic/1344562) — MCP code retrieval
  247. ## Contributors
  248. <!-- readme: contributors -start -->
  249. <table>
  250. <tr>
  251. <td align="center"><a href="https://github.com/fengshao1227"><img src="https://avatars.githubusercontent.com/fengshao1227?v=4&s=100" width="100;" alt="fengshao1227"/><br /><sub><b>fengshao1227</b></sub></a></td>
  252. <td align="center"><a href="https://github.com/SXP-Simon"><img src="https://avatars.githubusercontent.com/SXP-Simon?v=4&s=100" width="100;" alt="SXP-Simon"/><br /><sub><b>SXP-Simon</b></sub></a></td>
  253. <td align="center"><a href="https://github.com/RebornQ"><img src="https://avatars.githubusercontent.com/RebornQ?v=4&s=100" width="100;" alt="RebornQ"/><br /><sub><b>RebornQ</b></sub></a></td>
  254. <td align="center"><a href="https://github.com/Sakuranda"><img src="https://avatars.githubusercontent.com/Sakuranda?v=4&s=100" width="100;" alt="Sakuranda"/><br /><sub><b>Sakuranda</b></sub></a></td>
  255. <td align="center"><a href="https://github.com/Mriris"><img src="https://avatars.githubusercontent.com/Mriris?v=4&s=100" width="100;" alt="Mriris"/><br /><sub><b>Mriris</b></sub></a></td>
  256. <td align="center"><a href="https://github.com/23q3"><img src="https://avatars.githubusercontent.com/23q3?v=4&s=100" width="100;" alt="23q3"/><br /><sub><b>23q3</b></sub></a></td>
  257. <td align="center"><a href="https://github.com/MrNine-666"><img src="https://avatars.githubusercontent.com/MrNine-666?v=4&s=100" width="100;" alt="MrNine-666"/><br /><sub><b>MrNine-666</b></sub></a></td>
  258. </tr>
  259. <tr>
  260. <td align="center"><a href="https://github.com/GGzili"><img src="https://avatars.githubusercontent.com/GGzili?v=4&s=100" width="100;" alt="GGzili"/><br /><sub><b>GGzili</b></sub></a></td>
  261. </tr>
  262. </table>
  263. <!-- readme: contributors -end -->
  264. ## Contact
  265. - **X (Twitter)**: [@CCG_Workflow](https://x.com/CCG_Workflow)
  266. - **Email**: [fengshao1227@gmail.com](mailto:fengshao1227@gmail.com)
  267. - **Issues**: [GitHub Issues](https://github.com/fengshao1227/ccg-workflow/issues)
  268. - **Community**: [Linux.do](https://linux.do)
  269. ## Star History
  270. [![Star History Chart](https://api.star-history.com/svg?repos=fengshao1227/ccg-workflow&type=timeline&legend=top-left)](https://www.star-history.com/#fengshao1227/ccg-workflow&type=timeline&legend=top-left)
  271. ## License
  272. MIT
  273. ---
  274. v3.7.4 | [Issues](https://github.com/fengshao1227/ccg-workflow/issues) | [Contributing](./CONTRIBUTING.md)
src/commands/menu.ts · Bundled script · 1,274 lines · 1 finding marked
  1. import ansis from 'ansis'
  2. import inquirer from 'inquirer'
  3. import ora from 'ora'
  4. import { exec, spawn } from 'node:child_process'
  5. import { promisify } from 'node:util'
  6. import { homedir } from 'node:os'
  7. import { fileURLToPath } from 'node:url'
  8. import { dirname, join } from 'pathe'
  9. import fs from 'fs-extra'
  10. import { parse as parseTOML } from 'smol-toml'
  11. import { version } from '../../package.json'
  12. import { configMcp } from './config-mcp'
  13. import { i18n } from '../i18n'
  14. import { configureGeminiCliApi, getSponsor, installCodexMode, promptSponsorMenuKey, removeGeminiCliApi, sponsorInquirerChoices, uninstallCodexMode, uninstallWorkflows } from '../utils/installer'
  15. import { findDshProfiles, installDshPlugin, uninstallDshPlugin } from '../utils/installer-dsh'
  16. import { readCcgConfig, writeCcgConfig } from '../utils/config'
  17. import { init } from './init'
  18. import { update } from './update'
  19. import { manageSkillsMenu } from './skills'
  20. import { doctor } from './doctor'
  21. import { promptOpencodeModel } from '../utils/model-selection'
  22. import { isWindows } from '../utils/platform'
  23. const execAsync = promisify(exec)
  24. // ═══════════════════════════════════════════════════════
  25. // UI Helpers
  26. // ═══════════════════════════════════════════════════════
  27. /**
  28. * Get visual display width of a string (CJK = 2, ASCII = 1)
  29. */
  30. function visWidth(s: string): number {
  31. const stripped = s.replace(/\x1B\[[0-9;]*m/g, '')
  32. let w = 0
  33. for (const ch of stripped) {
  34. const code = ch.codePointAt(0) || 0
  35. // CJK Unified Ideographs + common fullwidth ranges
  36. if (
  37. (code >= 0x2E80 && code <= 0x9FFF)
  38. || (code >= 0xF900 && code <= 0xFAFF)
  39. || (code >= 0xFE30 && code <= 0xFE4F)
  40. || (code >= 0xFF00 && code <= 0xFF60)
  41. || (code >= 0xFFE0 && code <= 0xFFE6)
  42. || (code >= 0x1F300 && code <= 0x1F9FF) // Emojis
  43. || (code >= 0x20000 && code <= 0x2FA1F) // CJK Extension B+
  44. ) {
  45. w += 2
  46. }
  47. else {
  48. w += 1
  49. }
  50. }
  51. return w
  52. }
  53. /**
  54. * Pad a string to a fixed visible width (ANSI + CJK aware)
  55. */
  56. function pad(s: string, w: number): string {
  57. const diff = w - visWidth(s)
  58. return diff > 0 ? s + ' '.repeat(diff) : s
  59. }
  60. const INNER_W = 60
  61. /**
  62. * Center a string (with ANSI) inside a fixed-width area
  63. */
  64. function centerLine(s: string, w: number): string {
  65. const vis = visWidth(s)
  66. const left = Math.max(0, Math.floor((w - vis) / 2))
  67. const right = Math.max(0, w - vis - left)
  68. return ' '.repeat(left) + s + ' '.repeat(right)
  69. }
  70. /**
  71. * Draw a boxed row: ║ <content padded to INNER_W> ║
  72. */
  73. function boxRow(content: string): string {
  74. const vis = visWidth(content)
  75. const gap = Math.max(0, INNER_W - vis)
  76. return ansis.cyan('║') + content + ' '.repeat(gap) + ansis.cyan('║')
  77. }
  78. function drawHeader(statusParts: string[]): void {
  79. const top = ansis.cyan('╔' + '═'.repeat(INNER_W) + '╗')
  80. const bot = ansis.cyan('╚' + '═'.repeat(INNER_W) + '╝')
  81. const empty = boxRow(' '.repeat(INNER_W))
  82. // ASCII Art Logo
  83. const logo = [
  84. ' ██████╗ ██████╗ ██████╗ ',
  85. ' ██╔════╝ ██╔════╝ ██╔════╝ ',
  86. ' ██║ ██║ ██║ ███╗',
  87. ' ██║ ██║ ██║ ██║',
  88. ' ╚██████╗ ╚██████╗ ╚██████╔╝',
  89. ' ╚═════╝ ╚═════╝ ╚═════╝ ',
  90. ]
  91. console.log()
  92. console.log(top)
  93. console.log(empty)
  94. for (const line of logo) {
  95. console.log(boxRow(centerLine(ansis.bold.white(line), INNER_W)))
  96. }
  97. console.log(empty)
  98. console.log(boxRow(centerLine(ansis.gray('Claude + Codex + Gemini'), INNER_W)))
  99. console.log(boxRow(centerLine(ansis.gray('Multi-Model Collaboration'), INNER_W)))
  100. console.log(empty)
  101. if (statusParts.length > 0) {
  102. const statusLine = statusParts.join(ansis.gray(' | '))
  103. console.log(boxRow(centerLine(statusLine, INNER_W)))
  104. console.log(empty)
  105. }
  106. console.log(bot)
  107. console.log()
  108. }
  109. function groupSep(label: string): InstanceType<typeof inquirer.Separator> {
  110. const w = 42
  111. const labelW = visWidth(label)
  112. const remaining = Math.max(0, w - labelW - 2)
  113. const left = Math.floor(remaining / 2)
  114. const right = remaining - left
  115. return new inquirer.Separator(ansis.gray(`${'─'.repeat(left)} ${label} ${'─'.repeat(right)}`))
  116. }
  117. // ═══════════════════════════════════════════════════════
  118. // Main Menu
  119. // ═══════════════════════════════════════════════════════
  120. export async function showMainMenu(): Promise<void> {
  121. while (true) {
  122. // Read config for status display
  123. const config = await readCcgConfig()
  124. const cmdCount = config?.workflows?.installed?.length || 0
  125. const lang = config?.general?.language || 'zh-CN'
  126. const mcpProvider = config?.mcp?.provider || '—'
  127. // Build status parts
  128. const statusParts = [
  129. ansis.green(`v${version}`),
  130. ansis.white(`${cmdCount} commands`),
  131. ansis.yellow(lang),
  132. ]
  133. if (mcpProvider && mcpProvider !== '—' && mcpProvider !== 'skip') {
  134. statusParts.push(ansis.magenta(mcpProvider))
  135. }
  136. drawHeader(statusParts)
  137. const isZh = lang === 'zh-CN'
  138. // Build menu item helper: " N. Label - description"
  139. const item = (key: string, label: string, desc: string) => ({
  140. name: ` ${ansis.green(key + '.')} ${pad(label, 20)} ${ansis.gray('- ' + desc)}`,
  141. value: key,
  142. })
  143. const { action } = await inquirer.prompt([{
  144. type: 'list',
  145. name: 'action',
  146. message: i18n.t('menu:title'),
  147. pageSize: 20,
  148. choices: [
  149. groupSep(isZh ? 'Claude Code' : 'Claude Code'),
  150. item('1', i18n.t('menu:options.init'), isZh ? '安装 CCG 工作流' : 'Install CCG workflows'),
  151. item('2', i18n.t('menu:options.update'), isZh ? '更新到最新版本' : 'Update to latest version'),
  152. item('3', i18n.t('menu:options.configMcp'), isZh ? '代码检索 MCP 工具' : 'Code retrieval MCP tool'),
  153. item('4', i18n.t('menu:options.configApi'), isZh ? '自定义 API 端点' : 'Custom API endpoint'),
  154. item('5', i18n.t('menu:options.configStyle'), isZh ? '选择输出人格' : 'Choose output personality'),
  155. item('6', i18n.t('menu:options.configModel'), isZh ? '前端/后端模型切换' : 'Switch frontend/backend models'),
  156. groupSep(isZh ? '其他工具' : 'Tools'),
  157. item('X', isZh ? 'Codex 模式' : 'Codex Mode', isZh ? '安装 Codex 主导的多模型编排' : 'Install Codex-led multi-model orchestration'),
  158. item('D', isZh ? 'DeepSeek Harness' : 'DeepSeek Harness', isZh ? '把 CCG 角色矩阵装进 dsh' : 'Install the CCG role matrix into dsh'),
  159. item('T', i18n.t('menu:options.tools'), 'ccusage, CCometixLine'),
  160. item('C', i18n.t('menu:options.installClaude'), isZh ? '安装/重装 CLI' : 'Install/reinstall CLI'),
  161. groupSep('CCG'),
  162. item('S', isZh ? 'Skills 管理' : 'Manage Skills', isZh ? '按需安装、更新与移除技能' : 'Select, update and remove skills'),
  163. item('V', isZh ? '环境诊断' : 'Doctor', isZh ? '检查安装模式、模型路由与技能' : 'Check modes, routing and skills'),
  164. item('H', i18n.t('menu:options.help'), isZh ? '查看全部斜杠命令' : 'View all slash commands'),
  165. item('-', i18n.t('menu:options.uninstall'), isZh ? '移除 CCG 配置' : 'Remove CCG config'),
  166. new inquirer.Separator(ansis.gray('─'.repeat(42))),
  167. { name: ` ${ansis.red('Q.')} ${i18n.t('menu:options.exit')}`, value: 'Q' },
  168. ],
  169. }])
  170. switch (action) {
  171. case '1':
  172. await init()
  173. break
  174. case '2':
  175. await update()
  176. break
  177. case '3':
  178. await configMcp()
  179. break
  180. case '4':
  181. await configApi()
  182. break
  183. case '5':
  184. await configOutputStyle()
  185. break
  186. case '6':
  187. await configModelRouting()
  188. break
  189. case 'X':
  190. await handleCodexMode()
  191. break
  192. case 'D':
  193. await handleDshPlugin()
  194. break
  195. case 'T':
  196. await handleTools()
  197. break
  198. case 'C':
  199. await handleInstallClaude()
  200. break
  201. case '-':
  202. await uninstall()
  203. break
  204. case 'H':
  205. showHelp()
  206. break
  207. case 'S':
  208. await manageSkillsMenu()
  209. break
  210. case 'V':
  211. await doctor()
  212. break
  213. case 'Q':
  214. console.log()
  215. console.log(ansis.gray(` ${i18n.t('common:goodbye')}`))
  216. console.log()
  217. return
  218. }
  219. // Pause after action so user can see results
  220. console.log()
  221. await inquirer.prompt([{
  222. type: 'input',
  223. name: 'continue',
  224. message: ansis.gray(i18n.t('common:pressEnterToReturn')),
  225. }])
  226. }
  227. }
  228. // (visWidth and pad are defined in UI Helpers section above)
  229. // ═══════════════════════════════════════════════════════
  230. // Help
  231. // ═══════════════════════════════════════════════════════
  232. function showHelp(): void {
  233. const config = readCcgConfigSync()
  234. const isZh = (config?.general?.language || 'zh-CN') === 'zh-CN'
  235. console.log()
  236. console.log(ansis.cyan.bold(` ${i18n.t('menu:help.title')}`))
  237. console.log()
  238. const col1 = 22 // command column width
  239. const section = (title: string) => console.log(ansis.yellow.bold(` ${title}`))
  240. const cmd = (name: string, desc: string) => console.log(` ${ansis.green(name.padEnd(col1))} ${ansis.gray(desc)}`)
  241. // Core Engine
  242. section(i18n.t('menu:help.sections.engine'))
  243. cmd('/ccg:go', i18n.t('menu:help.descriptions.go'))
  244. console.log()
  245. // OpenSpec Workflows
  246. section(i18n.t('menu:help.sections.opsx'))
  247. cmd('/ccg:spec-init', i18n.t('menu:help.descriptions.specInit'))
  248. cmd('/ccg:spec-research', i18n.t('menu:help.descriptions.specResearch'))
  249. cmd('/ccg:spec-plan', i18n.t('menu:help.descriptions.specPlan'))
  250. cmd('/ccg:spec-impl', i18n.t('menu:help.descriptions.specImpl'))
  251. cmd('/ccg:spec-review', i18n.t('menu:help.descriptions.specReview'))
  252. console.log()
  253. // Git Tools
  254. section(i18n.t('menu:help.sections.gitTools'))
  255. cmd('/ccg:commit', i18n.t('menu:help.descriptions.commit'))
  256. cmd('/ccg:rollback', i18n.t('menu:help.descriptions.rollback'))
  257. cmd('/ccg:clean-branches', i18n.t('menu:help.descriptions.cleanBranches'))
  258. cmd('/ccg:worktree', i18n.t('menu:help.descriptions.worktree'))
  259. console.log()
  260. // Project Management
  261. section(i18n.t('menu:help.sections.projectMgmt'))
  262. cmd('/ccg:init', i18n.t('menu:help.descriptions.init'))
  263. cmd('/ccg:context', i18n.t('menu:help.descriptions.context'))
  264. console.log()
  265. // Quality Gates
  266. section(i18n.t('menu:help.sections.qualityGates'))
  267. cmd('/ccg:verify-security', i18n.t('menu:help.descriptions.verifySecurity'))
  268. cmd('/ccg:verify-quality', i18n.t('menu:help.descriptions.verifyQuality'))
  269. cmd('/ccg:verify-change', i18n.t('menu:help.descriptions.verifyChange'))
  270. cmd('/ccg:verify-module', i18n.t('menu:help.descriptions.verifyModule'))
  271. console.log()
  272. console.log(ansis.gray(` ${i18n.t('menu:help.hint')}`))
  273. console.log()
  274. }
  275. /**
  276. * Synchronous config read for non-async contexts (help display)
  277. */
  278. function readCcgConfigSync(): any {
  279. try {
  280. const configPath = join(homedir(), '.claude', '.ccg', 'config.toml')
  281. if (fs.pathExistsSync(configPath)) {
  282. return parseTOML(fs.readFileSync(configPath, 'utf-8'))
  283. }
  284. }
  285. catch { /* ignore */ }
  286. return null
  287. }
  288. // ═══════════════════════════════════════════════════════
  289. // API Configuration
  290. // ═══════════════════════════════════════════════════════
  291. async function configApi(): Promise<void> {
  292. console.log()
  293. console.log(ansis.cyan.bold(` ${i18n.t('menu:api.title')}`))
  294. console.log()
  295. const settingsPath = join(homedir(), '.claude', 'settings.json')
  296. let settings: Record<string, any> = {}
  297. if (await fs.pathExists(settingsPath)) {
  298. settings = await fs.readJson(settingsPath)
  299. }
  300. // Show current config
  301. const currentUrl = settings.env?.ANTHROPIC_BASE_URL
  302. const currentKey = settings.env?.ANTHROPIC_AUTH_TOKEN || settings.env?.ANTHROPIC_API_KEY
  303. if (currentUrl || currentKey) {
  304. console.log(ansis.gray(` ${i18n.t('menu:api.currentConfig')}`))
  305. if (currentUrl)
  306. console.log(ansis.gray(` URL: ${currentUrl}`))
  307. if (currentKey)
  308. console.log(ansis.gray(` Key: ${currentKey.slice(0, 8)}...${currentKey.slice(-4)}`))
  309. console.log()
  310. }
  311. const { apiProvider } = await inquirer.prompt([{
  312. type: 'list',
  313. name: 'apiProvider',
  314. message: i18n.t('menu:api.providerPrompt'),
  315. choices: [
  316. { name: `${ansis.green('●')} ${i18n.t('menu:api.officialOption')}`, value: 'official' },
  317. { name: `${ansis.cyan('●')} ${i18n.t('menu:api.thirdPartyOption')}`, value: 'thirdparty' },
  318. ...sponsorInquirerChoices(),
  319. { name: `${ansis.magenta('●')} ${i18n.t('init:api.geminiCliOption')}`, value: 'gemini-cli' },
  320. ],
  321. }])
  322. // Gemini CLI gateway lives in ~/.gemini/.env, not Claude Code's
  323. // settings.json — handle it as its own flow and return early so the
  324. // ANTHROPIC_* writing below never runs for this choice.
  325. if (apiProvider === 'gemini-cli') {
  326. const { action } = await inquirer.prompt([{
  327. type: 'list',
  328. name: 'action',
  329. message: i18n.t('init:api.geminiCliActionPrompt'),
  330. choices: [
  331. { name: `${ansis.green('●')} ${i18n.t('init:api.geminiCliConfigureOption')}`, value: 'configure' },
  332. { name: `${ansis.gray('○')} ${i18n.t('init:api.geminiCliRemoveOption')}`, value: 'remove' },
  333. ],
  334. }])
  335. if (action === 'remove') {
  336. const removed = await removeGeminiCliApi()
  337. console.log()
  338. console.log(removed.success
  339. ? ansis.green(` ✓ ${i18n.t('init:api.geminiCliRemoved')}`)
  340. : ansis.yellow(` ! ${removed.message}`))
  341. return
  342. }
  343. console.log(` ${ansis.yellow('!')} ${i18n.t('init:api.geminiCliProtocolHint')}`)
  344. const answers = await inquirer.prompt([
  345. {
  346. type: 'input',
  347. name: 'url',
  348. message: `${i18n.t('init:api.geminiCliUrlPrompt')} ${ansis.gray(`(${i18n.t('menu:api.urlRequired')})`)}`,
  349. validate: (v: string) => v.trim() !== '' || i18n.t('menu:api.enterUrl'),
  350. },
  351. {
  352. type: 'password',
  353. name: 'key',
  354. message: `Gemini API Key ${ansis.gray(`(${i18n.t('menu:api.keyRequired')})`)}`,
  355. mask: '*',
  356. validate: (v: string) => v.trim() !== '' || i18n.t('menu:api.enterKey'),
  357. },
  358. {
  359. type: 'input',
  360. name: 'model',
  361. message: i18n.t('init:api.geminiCliModelPrompt'),
  362. },
  363. ])
  364. const result = await configureGeminiCliApi({
  365. baseUrl: answers.url.trim(),
  366. apiKey: answers.key.trim(),
  367. model: answers.model?.trim() || undefined,
  368. })
  369. console.log()
  370. if (result.success) {
  371. console.log(ansis.green(` ✓ ${i18n.t('init:api.geminiCliSaved')}`))
  372. if (result.rcPath)
  373. console.log(ansis.gray(` ${i18n.t('common:configFile')}: ${result.rcPath}`))
  374. if (result.needsReload)
  375. console.log(ansis.gray(` ${i18n.t('init:api.geminiCliReloadHint')}`))
  376. }
  377. else {
  378. console.log(ansis.yellow(` ! ${result.message}`))
  379. }
  380. return
  381. }
  382. const sponsor = getSponsor(apiProvider)
  383. if (apiProvider === 'official') {
  384. // Clear third-party config, let Claude Code use official auth
  385. if (!settings.env)
  386. settings.env = {}
  387. delete settings.env.ANTHROPIC_BASE_URL
  388. delete settings.env.ANTHROPIC_AUTH_TOKEN
  389. delete settings.env.ANTHROPIC_API_KEY
  390. }
  391. else if (sponsor) {
  392. const key = await promptSponsorMenuKey(sponsor)
  393. if (!settings.env)
  394. settings.env = {}
  395. // No /v1 suffix: Claude Code appends /v1/messages to ANTHROPIC_BASE_URL itself.
  396. settings.env.ANTHROPIC_BASE_URL = sponsor.anthropicBaseUrl
  397. settings.env.ANTHROPIC_AUTH_TOKEN = key
  398. delete settings.env.ANTHROPIC_API_KEY
  399. }
  400. else {
  401. const answers = await inquirer.prompt([
  402. {
  403. type: 'input',
  404. name: 'url',
  405. message: `API URL ${ansis.gray(`(${i18n.t('menu:api.urlRequired')})`)}`,
  406. default: currentUrl || '',
  407. validate: (v: string) => v.trim() !== '' || i18n.t('menu:api.enterUrl'),
  408. },
  409. {
  410. type: 'password',
  411. name: 'key',
  412. message: `API Key ${ansis.gray(`(${i18n.t('menu:api.keyRequired')})`)}`,
  413. mask: '*',
  414. validate: (v: string) => v.trim() !== '' || i18n.t('menu:api.enterKey'),
  415. },
  416. ])
  417. if (!settings.env)
  418. settings.env = {}
  419. settings.env.ANTHROPIC_BASE_URL = answers.url.trim()
  420. settings.env.ANTHROPIC_AUTH_TOKEN = answers.key.trim()
  421. delete settings.env.ANTHROPIC_API_KEY
  422. }
  423. // Default optimization config
  424. settings.env.DISABLE_TELEMETRY = '1'
  425. settings.env.DISABLE_ERROR_REPORTING = '1'
  426. settings.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1'
  427. settings.env.CLAUDE_CODE_ATTRIBUTION_HEADER = '0'
  428. settings.env.MCP_TIMEOUT = '60000'
  429. // codeagent-wrapper permission allowlist
  430. if (!settings.permissions)
  431. settings.permissions = {}
  432. if (!settings.permissions.allow)
  433. settings.permissions.allow = []
  434. const wrapperPerms = [
  435. 'Bash(~/.claude/bin/codeagent-wrapper*)',
  436. 'Bash(*codeagent-wrapper*)',
  437. ]
  438. for (const perm of wrapperPerms) {
  439. if (!settings.permissions.allow.includes(perm))
  440. settings.permissions.allow.push(perm)
  441. }
  442. await fs.ensureDir(join(homedir(), '.claude'))
  443. await fs.writeJson(settingsPath, settings, { spaces: 2 })
  444. console.log()
  445. console.log(ansis.green(` ✓ ${i18n.t('menu:api.saved')}`))
  446. console.log(ansis.gray(` ${i18n.t('common:configFile')}: ${settingsPath}`))
  447. }
  448. // ═══════════════════════════════════════════════════════
  449. // Output Style Configuration
  450. // ═══════════════════════════════════════════════════════
  451. const OUTPUT_STYLES = [
  452. { id: 'default', nameKey: 'menu:style.default', descKey: 'menu:style.defaultDesc' },
  453. { id: 'engineer-professional', nameKey: 'menu:style.engineerPro', descKey: 'menu:style.engineerProDesc' },
  454. { id: 'nekomata-engineer', nameKey: 'menu:style.nekomata', descKey: 'menu:style.nekomataDesc' },
  455. { id: 'laowang-engineer', nameKey: 'menu:style.laowang', descKey: 'menu:style.laowangDesc' },
  456. { id: 'ojousama-engineer', nameKey: 'menu:style.ojousama', descKey: 'menu:style.ojousamaDesc' },
  457. { id: 'abyss-cultivator', nameKey: 'menu:style.abyss', descKey: 'menu:style.abyssDesc' },
  458. { id: 'abyss-concise', nameKey: 'menu:style.abyssConcise', descKey: 'menu:style.abyssConciseDesc' },
  459. { id: 'abyss-command', nameKey: 'menu:style.abyssCommand', descKey: 'menu:style.abyssCommandDesc' },
  460. { id: 'abyss-ritual', nameKey: 'menu:style.abyssRitual', descKey: 'menu:style.abyssRitualDesc' },
  461. ]
  462. // ═══════════════════════════════════════════════════════
  463. // Model Routing Configuration
  464. // ═══════════════════════════════════════════════════════
  465. async function configModelRouting(): Promise<void> {
  466. const config = await readCcgConfig()
  467. const isZh = (config?.general?.language || 'zh-CN') === 'zh-CN'
  468. if (!config) {
  469. console.log(isZh ? '请先运行 ccg init 初始化配置。' : 'Run ccg init before changing routing.')
  470. return
  471. }
  472. console.log()
  473. console.log(ansis.cyan.bold(` ${i18n.t('init:model.title')}`))
  474. console.log()
  475. // Show current routing
  476. const currentFrontend = config?.routing?.frontend?.primary || 'antigravity'
  477. const currentBackend = config?.routing?.backend?.primary || 'codex'
  478. const currentGeminiModel = config?.routing?.geminiModel || 'gemini-3.1-pro-preview'
  479. const currentGrokModel = config?.routing?.grokModel || 'grok-4.5'
  480. const currentKimiModel = config?.routing?.kimiModel || ''
  481. const currentOpencodeModel = config?.routing?.opencodeModel || ''
  482. console.log(ansis.gray(` ${i18n.t('init:model.currentRouting')}:`))
  483. console.log(` ${ansis.cyan('Frontend:')} ${ansis.green(currentFrontend)}`)
  484. console.log(` ${ansis.cyan('Backend:')} ${ansis.blue(currentBackend)}`)
  485. if (currentFrontend === 'gemini' || currentBackend === 'gemini') {
  486. console.log(` ${ansis.cyan('Gemini:')} ${ansis.gray(currentGeminiModel)}`)
  487. }
  488. if (currentFrontend === 'grok' || currentBackend === 'grok') {
  489. console.log(` ${ansis.cyan('Grok:')} ${ansis.gray(currentGrokModel)}`)
  490. }
  491. console.log()
  492. // Frontend model selection
  493. const { selectedFrontend } = await inquirer.prompt([{
  494. type: 'list',
  495. name: 'selectedFrontend',
  496. message: i18n.t('init:model.selectFrontend'),
  497. choices: [
  498. { name: `Antigravity ${ansis.green(`(${i18n.t('init:model.recommended')})`)}`, value: 'antigravity' },
  499. { name: 'Grok', value: 'grok' },
  500. { name: 'Kimi', value: 'kimi' },
  501. { name: 'Codex', value: 'codex' },
  502. { name: 'OpenCode', value: 'opencode' },
  503. { name: `Claude Code ${ansis.cyan(`(${i18n.t('init:model.agentTeams')})`)}`, value: 'claude' },
  504. { name: `Gemini ${ansis.gray(`(${i18n.t('init:model.deprecated')})`)}`, value: 'gemini' },
  505. ],
  506. default: currentFrontend,
  507. }])
  508. // Backend model selection
  509. const { selectedBackend } = await inquirer.prompt([{
  510. type: 'list',
  511. name: 'selectedBackend',
  512. message: i18n.t('init:model.selectBackend'),
  513. choices: [
  514. { name: `Codex ${ansis.green(`(${i18n.t('init:model.recommended')})`)}`, value: 'codex' },
  515. { name: 'Grok', value: 'grok' },
  516. { name: 'Kimi', value: 'kimi' },
  517. { name: 'Antigravity', value: 'antigravity' },
  518. { name: 'OpenCode', value: 'opencode' },
  519. { name: `Claude Code ${ansis.cyan(`(${i18n.t('init:model.agentTeams')})`)}`, value: 'claude' },
  520. { name: `Gemini ${ansis.gray(`(${i18n.t('init:model.deprecated')})`)}`, value: 'gemini' },
  521. ],
  522. default: currentBackend,
  523. }])
  524. // Gemini model name (if gemini is selected for any role)
  525. let geminiModel = currentGeminiModel
  526. if (selectedFrontend === 'gemini' || selectedBackend === 'gemini') {
  527. const { selectedGeminiModel } = await inquirer.prompt([{
  528. type: 'list',
  529. name: 'selectedGeminiModel',
  530. message: i18n.t('init:model.selectGeminiModel'),
  531. choices: [
  532. { name: `gemini-3.1-pro-preview ${ansis.green(`(${i18n.t('init:model.recommended')})`)}`, value: 'gemini-3.1-pro-preview' },
  533. { name: 'gemini-2.5-flash', value: 'gemini-2.5-flash' },
  534. { name: `${i18n.t('init:model.custom')}`, value: 'custom' },
  535. ],
  536. default: currentGeminiModel,
  537. }])
  538. if (selectedGeminiModel === 'custom') {
  539. const { customModel } = await inquirer.prompt([{
  540. type: 'input',
  541. name: 'customModel',
  542. message: i18n.t('init:model.enterCustomModel'),
  543. validate: (v: string) => v.trim() !== '' || i18n.t('init:model.enterCustomModel'),
  544. }])
  545. geminiModel = customModel.trim()
  546. }
  547. else {
  548. geminiModel = selectedGeminiModel
  549. }
  550. }
  551. // Grok model name (if grok is selected for any role)
  552. let grokModel = currentGrokModel
  553. if (selectedFrontend === 'grok' || selectedBackend === 'grok') {
  554. const { selectedGrokModel } = await inquirer.prompt([{
  555. type: 'list',
  556. name: 'selectedGrokModel',
  557. message: i18n.t('init:model.selectGrokModel'),
  558. choices: [
  559. { name: `grok-4.5 ${ansis.green(`(${i18n.t('init:model.recommended')})`)}`, value: 'grok-4.5' },
  560. { name: 'grok-composer-2.5-fast', value: 'grok-composer-2.5-fast' },
  561. { name: `${i18n.t('init:model.custom')}`, value: 'custom' },
  562. ],
  563. default: currentGrokModel,
  564. }])
  565. if (selectedGrokModel === 'custom') {
  566. const { customModel } = await inquirer.prompt([{
  567. type: 'input',
  568. name: 'customModel',
  569. message: i18n.t('init:model.enterCustomModel'),
  570. validate: (v: string) => v.trim() !== '' || i18n.t('init:model.enterCustomModel'),
  571. }])
  572. grokModel = customModel.trim()
  573. }
  574. else {
  575. grokModel = selectedGrokModel
  576. }
  577. }
  578. // Check if anything changed
  579. let opencodeModel = currentOpencodeModel
  580. if (selectedFrontend === 'opencode' || selectedBackend === 'opencode') {
  581. opencodeModel = await promptOpencodeModel(currentOpencodeModel, isZh)
  582. }
  583. if (selectedFrontend === currentFrontend && selectedBackend === currentBackend && geminiModel === currentGeminiModel && grokModel === currentGrokModel && opencodeModel === currentOpencodeModel) {
  584. console.log(ansis.gray(` ${i18n.t('common:configNotModified')}`))
  585. return
  586. }
  587. // Update config.toml
  588. if (config) {
  589. config.routing.frontend = {
  590. models: [selectedFrontend as any],
  591. primary: selectedFrontend as any,
  592. strategy: 'fallback',
  593. }
  594. config.routing.backend = {
  595. models: [selectedBackend as any],
  596. primary: selectedBackend as any,
  597. strategy: 'fallback',
  598. }
  599. config.routing.review = {
  600. models: [...new Set([selectedFrontend, selectedBackend])] as any,
  601. strategy: 'parallel',
  602. }
  603. config.routing.geminiModel = geminiModel
  604. config.routing.grokModel = grokModel
  605. config.routing.kimiModel = currentKimiModel
  606. config.routing.opencodeModel = opencodeModel
  607. await writeCcgConfig(config)
  608. }
  609. console.log()
  610. console.log(ansis.green(` ✓ ${i18n.t('init:model.routingUpdated')}`))
  611. // Reinstall templates with new config
  612. const spinner = ora(i18n.t('init:model.reinstalling')).start()
  613. const previousExitCode = process.exitCode
  614. try {
  615. process.exitCode = 0
  616. await init({ force: true, skipPrompt: true, skipMcp: true })
  617. if (process.exitCode) {
  618. spinner.fail(i18n.t('init:model.reinstallFailed'))
  619. return
  620. }
  621. process.exitCode = previousExitCode
  622. spinner.succeed(i18n.t('init:model.reinstallDone'))
  623. }
  624. catch {
  625. process.exitCode = 1
  626. spinner.fail(i18n.t('init:model.reinstallFailed'))
  627. return
  628. }
  629. console.log(ansis.gray(` ${i18n.t('common:restartToApply')}`))
  630. }
  631. async function configOutputStyle(): Promise<void> {
  632. console.log()
  633. console.log(ansis.cyan.bold(` ${i18n.t('menu:style.title')}`))
  634. console.log()
  635. const settingsPath = join(homedir(), '.claude', 'settings.json')
  636. let settings: Record<string, any> = {}
  637. if (await fs.pathExists(settingsPath)) {
  638. settings = await fs.readJson(settingsPath)
  639. }
  640. const currentStyle = settings.outputStyle || 'default'
  641. console.log(ansis.gray(` ${i18n.t('menu:style.currentStyle')}: ${currentStyle}`))
  642. console.log()
  643. const { style } = await inquirer.prompt([{
  644. type: 'list',
  645. name: 'style',
  646. message: i18n.t('menu:style.selectStyle'),
  647. choices: OUTPUT_STYLES.map(s => ({
  648. name: `${i18n.t(s.nameKey)} ${ansis.gray(`- ${i18n.t(s.descKey)}`)}`,
  649. value: s.id,
  650. })),
  651. default: currentStyle,
  652. }])
  653. if (style === currentStyle) {
  654. console.log(ansis.gray(i18n.t('menu:style.notChanged')))
  655. return
  656. }
  657. // Copy style file if not default
  658. if (style !== 'default') {
  659. const outputStylesDir = join(homedir(), '.claude', 'output-styles')
  660. await fs.ensureDir(outputStylesDir)
  661. const __filename = fileURLToPath(import.meta.url)
  662. const __dirname = dirname(__filename)
  663. let pkgRoot = dirname(dirname(__dirname))
  664. if (!await fs.pathExists(join(pkgRoot, 'templates'))) {
  665. pkgRoot = dirname(pkgRoot)
  666. }
  667. const templatePath = join(pkgRoot, 'templates', 'output-styles', `${style}.md`)
  668. const destPath = join(outputStylesDir, `${style}.md`)
  669. if (await fs.pathExists(templatePath)) {
  670. await fs.copy(templatePath, destPath)
  671. console.log(ansis.green(` ✓ ${i18n.t('menu:style.installed', { style })}`))
  672. }
  673. }
  674. // Update settings.json
  675. if (style === 'default') {
  676. delete settings.outputStyle
  677. }
  678. else {
  679. settings.outputStyle = style
  680. }
  681. await fs.writeJson(settingsPath, settings, { spaces: 2 })
  682. console.log()
  683. console.log(ansis.green(` ✓ ${i18n.t('menu:style.set', { style })}`))
  684. console.log(ansis.gray(` ${i18n.t('common:restartToApply')}`))
  685. }
  686. // ═══════════════════════════════════════════════════════
  687. // Install Claude Code
  688. // ═══════════════════════════════════════════════════════
  689. /**
  690. * Install the CCG role matrix into a DeepSeek Harness profile.
  691. *
  692. * The plugin ships inside this package, so there is nothing to download and no
  693. * second version number: whatever CCG you ran is the plugin you get.
  694. */
  695. async function handleDshPlugin(): Promise<void> {
  696. const isZh = i18n.language === 'zh-CN'
  697. console.log()
  698. console.log(ansis.cyan.bold(isZh ? ' CCG for DeepSeek Harness' : ' CCG for DeepSeek Harness'))
  699. console.log()
  700. console.log(isZh
  701. ? ' 七个角色委派工具,各跑各的模型;任一角色可挂多个模型并排作答,\n 也能被雇成有自己文件的常驻队友。不依赖任何外部 CLI。'
  702. : ' Seven role-pinned delegation tools, each on its own model. Any role can\n answer as a panel of models, or be hired as a live teammate with its own\n files. No external CLI.')
  703. console.log()
  704. const profiles = await findDshProfiles()
  705. if (profiles.length === 0) {
  706. console.log(ansis.yellow(isZh
  707. ? ' 没有找到 DeepSeek Harness 配置档(~/.dsh/profiles/)。'
  708. : ' No DeepSeek Harness profile found (~/.dsh/profiles/).'))
  709. console.log(ansis.gray(isZh
  710. ? ' 先跑一次 `dsh web` 生成配置档,再回来安装。'
  711. : ' Run `dsh web` once to create one, then come back.'))
  712. console.log()
  713. return
  714. }
  715. for (const profile of profiles) {
  716. const mark = profile.installed ? ansis.green('✓') : ansis.gray('○')
  717. const note = profile.installed ? ansis.gray(isZh ? '已安装' : 'installed') : ''
  718. console.log(` ${mark} ${profile.name} ${note}`)
  719. }
  720. console.log()
  721. const { action } = await inquirer.prompt([{
  722. type: 'list',
  723. name: 'action',
  724. message: isZh ? '选择操作' : 'Select action',
  725. choices: [
  726. { name: isZh ? '安装 / 更新到全部配置档' : 'Install / update in every profile', value: 'install' },
  727. { name: isZh ? '选择配置档安装' : 'Pick which profiles', value: 'pick' },
  728. { name: isZh ? '卸载(从全部配置档移除)' : 'Uninstall (remove from every profile)', value: 'uninstall' },
  729. { name: isZh ? '返回' : 'Back', value: 'back' },
  730. ],
  731. }])
  732. if (action === 'back') return
  733. let chosen: string[] | undefined
  734. if (action === 'pick') {
  735. const { picked } = await inquirer.prompt([{
  736. type: 'checkbox',
  737. name: 'picked',
  738. message: isZh ? '装到哪些配置档' : 'Install into which profiles',
  739. choices: profiles.map(profile => ({ name: profile.name, value: profile.name, checked: profile.installed })),
  740. }])
  741. if (!picked || picked.length === 0) return
  742. chosen = picked
  743. }
  744. const uninstalling = action === 'uninstall'
  745. const spinner = ora(uninstalling
  746. ? (isZh ? '移除 dsh-ccg...' : 'Removing dsh-ccg...')
  747. : (isZh ? '安装 dsh-ccg...' : 'Installing dsh-ccg...')).start()
  748. const result = uninstalling
  749. ? await uninstallDshPlugin()
  750. : await installDshPlugin({ profiles: chosen })
  751. if (result.success) {
  752. spinner.succeed(uninstalling
  753. ? (isZh ? `已移除:${result.profiles.join(', ') || '(没有配置档装过)'}` : `Removed from: ${result.profiles.join(', ') || '(no profile had it)'}`)
  754. : (isZh ? `已安装到:${result.profiles.join(', ')}` : `Installed into: ${result.profiles.join(', ')}`))
  755. if (!uninstalling) {
  756. console.log()
  757. console.log(ansis.gray(isZh
  758. ? ' 重启 dsh 生效,然后在 设置 › 内置插件 › CCG 角色矩阵 里设好两个模型档位。'
  759. : ' Restart dsh to load it, then set the two model tiers in Settings › Built-in plugins › CCG.'))
  760. }
  761. }
  762. else {
  763. spinner.fail(isZh ? '失败' : 'Failed')
  764. if (result.message) console.log(ansis.red(` ${result.message}`))
  765. }
  766. for (const warning of result.warnings) console.log(ansis.yellow(` ! ${warning}`))
  767. console.log()
  768. }
  769. async function handleCodexMode(): Promise<void> {
  770. const isZh = i18n.language === 'zh-CN'
  771. console.log()
  772. console.log(ansis.cyan.bold(isZh ? ' Codex 多模型编排模式' : ' Codex Multi-Model Orchestration Mode'))
  773. console.log()
  774. const { action } = await inquirer.prompt([{
  775. type: 'list',
  776. name: 'action',
  777. message: isZh ? '选择操作' : 'Select action',
  778. choices: [
  779. { name: isZh ? '安装 / 更新 Codex 模式' : 'Install / Update Codex Mode', value: 'install' },
  780. { name: isZh ? '卸载 Codex 模式(只删 CCG 文件,保留用户配置)' : 'Uninstall Codex Mode (CCG files only, preserves user config)', value: 'uninstall' },
  781. { name: isZh ? '返回' : 'Back', value: 'back' },
  782. ],
  783. }])
  784. if (action === 'back') return
  785. if (action === 'uninstall') {
  786. const spinner = ora(isZh ? '卸载 Codex 模式...' : 'Uninstalling Codex mode...').start()
  787. const result = await uninstallCodexMode()
  788. if (result.success) {
  789. spinner.succeed(isZh ? 'Codex 模式已卸载' : 'Codex mode uninstalled')
  790. if (result.removed.length > 0) {
  791. console.log()
  792. for (const f of result.removed) {
  793. console.log(` ${ansis.red('✗')} ${f}`)
  794. }
  795. }
  796. if (result.skipped.length > 0) {
  797. console.log()
  798. for (const f of result.skipped) {
  799. console.log(` ${ansis.gray('○')} ${f}`)
  800. }
  801. }
  802. }
  803. else {
  804. spinner.fail(isZh ? '卸载失败' : 'Uninstall failed')
  805. }
  806. return
  807. }
  808. // Install
  809. console.log(isZh
  810. ? ' 安装 CCG Codex 模式到 ~/.codex/,让 Codex CLI 作为主导者编排多模型。'
  811. : ' Install CCG Codex mode to ~/.codex/, enabling Codex CLI as lead orchestrator.',
  812. )
  813. console.log()
  814. console.log(isZh ? ' 将安装:' : ' Will install:')
  815. console.log(' ~/.codex/AGENTS.md — orchestration instructions')
  816. console.log(' ~/.codex/config.toml — multi-agent + timeout config')
  817. console.log(' ~/.codex/hooks.json + hooks/ — adaptive guardrail hook')
  818. console.log(' ~/.codex/agents/ccg-*.toml — sub-agent definitions')
  819. console.log()
  820. const { confirm } = await inquirer.prompt([{
  821. type: 'confirm',
  822. name: 'confirm',
  823. message: isZh ? '确认安装?' : 'Confirm install?',
  824. default: true,
  825. }])
  826. if (!confirm) return
  827. const spinner = ora(isZh ? '安装 Codex 模式...' : 'Installing Codex mode...').start()
  828. const result = await installCodexMode()
  829. if (result.success) {
  830. spinner.succeed(isZh ? 'Codex 模式安装完成' : 'Codex mode installed')
  831. console.log()
  832. console.log(ansis.green(result.message))
  833. console.log()
  834. console.log(ansis.yellow(isZh
  835. ? ' 使用方法: 在项目目录运行 codex,AGENTS.md 会自动生效'
  836. : ' Usage: run codex in your project directory, AGENTS.md takes effect automatically',
  837. ))
  838. }
  839. else {
  840. spinner.fail(result.message)
  841. }
  842. }
  843. // ═══════════════════════════════════════════════════════
  844. async function handleInstallClaude(): Promise<void> {
  845. console.log()
  846. console.log(ansis.cyan.bold(` ${i18n.t('menu:claude.title')}`))
  847. console.log()
  848. // Check if already installed
  849. let isInstalled = false
  850. try {
  851. await execAsync('claude --version', { timeout: 5000 })
  852. isInstalled = true
  853. }
  854. catch {
  855. isInstalled = false
  856. }
  857. if (isInstalled) {
  858. console.log(ansis.yellow(` ⚠ ${i18n.t('menu:claude.alreadyInstalled')}`))
  859. const { confirm } = await inquirer.prompt([{
  860. type: 'confirm',
  861. name: 'confirm',
  862. message: i18n.t('menu:claude.reinstallPrompt'),
  863. default: false,
  864. }])
  865. if (!confirm) {
  866. console.log(ansis.gray(` ${i18n.t('common:cancelled')}`))
  867. return
  868. }
  869. // Uninstall
  870. console.log()
  871. console.log(ansis.yellow(` ⏳ ${i18n.t('menu:claude.uninstalling')}`))
  872. try {
  873. const uninstallCmd = isWindows() ? 'npm uninstall -g @anthropic-ai/claude-code' : 'sudo npm uninstall -g @anthropic-ai/claude-code'
  874. await execAsync(uninstallCmd, { timeout: 60000 })
  875. console.log(ansis.green(` ✓ ${i18n.t('menu:claude.uninstallSuccess')}`))
  876. }
  877. catch (e) {
  878. console.log(ansis.red(` ✗ ${i18n.t('menu:claude.uninstallFailed', { error: String(e) })}`))
  879. return
  880. }
  881. }
  882. // Select installation method
  883. const isMac = process.platform === 'darwin'
  884. const isLinux = process.platform === 'linux'
  885. const { method } = await inquirer.prompt([{
  886. type: 'list',
  887. name: 'method',
  888. message: i18n.t('menu:claude.selectMethod'),
  889. choices: [
  890. { name: `npm ${ansis.green('(⭐)')} ${ansis.gray('- npm install -g')}`, value: 'npm' },
  891. ...((isMac || isLinux) ? [{ name: `homebrew ${ansis.gray('- brew install')}`, value: 'homebrew' }] : []),
  892. ...((isMac || isLinux) ? [{ name: `curl ${ansis.gray('- official script')}`, value: 'curl' }] : []),
  893. ...(isWindows() ? [
  894. { name: `powershell ${ansis.gray('- Windows official')}`, value: 'powershell' },
  895. { name: `cmd ${ansis.gray('- Command Prompt')}`, value: 'cmd' },
  896. ] : []),
  897. new inquirer.Separator(),
  898. { name: `${ansis.gray(i18n.t('common:cancel'))}`, value: 'cancel' },
  899. ],
  900. }])
  901. if (method === 'cancel')
  902. return
  903. console.log()
  904. console.log(ansis.yellow(` ⏳ ${i18n.t('menu:claude.installing')}`))
  905. try {
  906. if (method === 'npm') {
  907. const installCmd = isWindows() ? 'npm install -g @anthropic-ai/claude-code' : 'sudo npm install -g @anthropic-ai/claude-code'
  908. await execAsync(installCmd, { timeout: 300000 })
  909. }
  910. else if (method === 'homebrew') {
  911. await execAsync('brew install --cask claude-code', { timeout: 300000 })
  912. }
  913. else if (method === 'curl') {
  914. await execAsync('curl -fsSL https://claude.ai/install.sh | bash', { timeout: 300000 })
  915. }
  916. else if (method === 'powershell') {
  917. await execAsync('powershell -Command "irm https://claude.ai/install.ps1 | iex"', { timeout: 300000 })
  918. }
  919. else if (method === 'cmd') {
  920. await execAsync('cmd /c "curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd"', { timeout: 300000 })
    • Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 1,029 on GitHub
  921. }
  922. console.log(ansis.green(` ✓ ${i18n.t('menu:claude.installSuccess')}`))
  923. console.log()
  924. console.log(ansis.cyan(` 💡 ${i18n.t('menu:claude.runHint')}`))
  925. }
  926. catch (e) {
  927. console.log(ansis.red(` ✗ ${i18n.t('menu:claude.installFailed', { error: String(e) })}`))
  928. }
  929. }
  930. // ═══════════════════════════════════════════════════════
  931. // Uninstall
  932. // ═══════════════════════════════════════════════════════
  933. /**
  934. * Check if CCG is installed globally via npm
  935. */
  936. async function checkIfGlobalInstall(): Promise<boolean> {
  937. try {
  938. const { stdout } = await execAsync('npm list -g ccg-workflow --depth=0', { timeout: 5000 })
  939. return stdout.includes('ccg-workflow@')
  940. }
  941. catch {
  942. return false
  943. }
  944. }
  945. async function uninstall(): Promise<void> {
  946. console.log()
  947. // Check if installed globally via npm
  948. const isGlobalInstall = await checkIfGlobalInstall()
  949. if (isGlobalInstall) {
  950. console.log(ansis.yellow(` ⚠️ ${i18n.t('menu:uninstall.globalDetected')}`))
  951. console.log()
  952. console.log(` ${i18n.t('menu:uninstall.twoSteps')}`)
  953. console.log(` ${ansis.cyan(`1. ${i18n.t('menu:uninstall.step1')}`)} ${ansis.gray(`(${i18n.t('menu:uninstall.step1Hint')})`)}`)
  954. console.log(` ${ansis.cyan(`2. ${i18n.t('menu:uninstall.step2')}`)} ${ansis.gray(`(${i18n.t('menu:uninstall.step2Hint')})`)}`)
  955. console.log()
  956. }
  957. // Confirm uninstall
  958. const { confirm } = await inquirer.prompt([{
  959. type: 'confirm',
  960. name: 'confirm',
  961. message: isGlobalInstall ? i18n.t('menu:uninstall.continuePrompt') : i18n.t('menu:uninstall.confirm'),
  962. default: false,
  963. }])
  964. if (!confirm) {
  965. console.log(ansis.gray(` ${i18n.t('menu:uninstall.cancelled')}`))
  966. return
  967. }
  968. console.log()
  969. console.log(ansis.yellow(` ${i18n.t('menu:uninstall.uninstalling')}`))
  970. // Uninstall workflows
  971. const installDir = join(homedir(), '.claude')
  972. const result = await uninstallWorkflows(installDir)
  973. if (result.success) {
  974. console.log(ansis.green(` ✅ ${i18n.t('menu:uninstall.success')}`))
  975. if (result.removedCommands.length > 0) {
  976. console.log()
  977. console.log(ansis.cyan(` ${i18n.t('menu:uninstall.removedCommands')}`))
  978. for (const cmd of result.removedCommands) {
  979. console.log(` ${ansis.gray('•')} /ccg:${cmd}`)
  980. }
  981. }
  982. if (result.removedAgents.length > 0) {
  983. console.log()
  984. console.log(ansis.cyan(` ${i18n.t('menu:uninstall.removedAgents')}`))
  985. for (const agent of result.removedAgents) {
  986. console.log(` ${ansis.gray('•')} ${agent}`)
  987. }
  988. }
  989. if (result.removedSkills.length > 0) {
  990. console.log()
  991. console.log(ansis.cyan(` ${i18n.t('menu:uninstall.removedSkills')}`))
  992. console.log(` ${ansis.gray('•')} multi-model-collaboration`)
  993. }
  994. if (result.removedBin) {
  995. console.log()
  996. console.log(ansis.cyan(` ${i18n.t('menu:uninstall.removedBin')}`))
  997. console.log(` ${ansis.gray('•')} codeagent-wrapper`)
  998. }
  999. // If globally installed, show instructions to uninstall npm package
  1000. if (isGlobalInstall) {
  1001. console.log()
  1002. console.log(ansis.yellow.bold(` 🔸 ${i18n.t('menu:uninstall.lastStep')}`))
  1003. console.log()
  1004. console.log(` ${i18n.t('menu:uninstall.runInNewTerminal')}`)
  1005. console.log()
  1006. console.log(ansis.cyan.bold(' npm uninstall -g ccg-workflow'))
  1007. console.log()
  1008. console.log(ansis.gray(` (${i18n.t('menu:uninstall.afterDone')})`))
  1009. }
  1010. }
  1011. else {
  1012. console.log(ansis.red(` ${i18n.t('menu:uninstall.failed')}`))
  1013. for (const error of result.errors) {
  1014. console.log(ansis.red(` ${error}`))
  1015. }
  1016. }
  1017. console.log()
  1018. }
  1019. // ═══════════════════════════════════════════════════════
  1020. // Tools
  1021. // ═══════════════════════════════════════════════════════
  1022. async function handleTools(): Promise<void> {
  1023. console.log()
  1024. const { tool } = await inquirer.prompt([{
  1025. type: 'list',
  1026. name: 'tool',
  1027. message: i18n.t('menu:tools.title'),
  1028. choices: [
  1029. { name: `${ansis.green('📊')} ccusage ${ansis.gray(`${i18n.t('menu:tools.ccusage')}`)}`, value: 'ccusage' },
  1030. { name: `${ansis.blue('📟')} CCometixLine ${ansis.gray(`${i18n.t('menu:tools.ccline')}`)}`, value: 'ccline' },
  1031. new inquirer.Separator(),
  1032. { name: `${ansis.gray(`← ${i18n.t('common:back')}`)}`, value: 'cancel' },
  1033. ],
  1034. }])
  1035. if (tool === 'cancel')
  1036. return
  1037. if (tool === 'ccusage') {
  1038. await runCcusage()
  1039. }
  1040. else if (tool === 'ccline') {
  1041. await handleCCometixLine()
  1042. }
  1043. }
  1044. async function runCcusage(): Promise<void> {
  1045. console.log()
  1046. console.log(ansis.cyan(` 📊 ${i18n.t('menu:tools.runningCcusage')}`))
  1047. console.log(ansis.gray(' $ npx ccusage@latest'))
  1048. console.log()
  1049. return new Promise((resolve) => {
  1050. const child = spawn('npx', ['ccusage@latest'], {
  1051. stdio: 'inherit',
  1052. shell: true,
  1053. })
  1054. child.on('close', () => resolve())
  1055. child.on('error', () => resolve())
  1056. })
  1057. }
  1058. async function handleCCometixLine(): Promise<void> {
  1059. console.log()
  1060. const { action } = await inquirer.prompt([{
  1061. type: 'list',
  1062. name: 'action',
  1063. message: i18n.t('menu:tools.cclineAction'),
  1064. choices: [
  1065. { name: `${ansis.green('➜')} ${i18n.t('menu:tools.cclineInstall')}`, value: 'install' },
  1066. { name: `${ansis.red('✕')} ${i18n.t('menu:tools.cclineUninstall')}`, value: 'uninstall' },
  1067. new inquirer.Separator(),
  1068. { name: `${ansis.gray(`← ${i18n.t('common:back')}`)}`, value: 'cancel' },
  1069. ],
  1070. }])
  1071. if (action === 'cancel')
  1072. return
  1073. if (action === 'install') {
  1074. await installCCometixLine()
  1075. }
  1076. else if (action === 'uninstall') {
  1077. await uninstallCCometixLine()
  1078. }
  1079. }
  1080. async function installCCometixLine(): Promise<void> {
  1081. console.log()
  1082. console.log(ansis.yellow(` ⏳ ${i18n.t('menu:tools.cclineInstalling')}`))
  1083. try {
  1084. const installCmd = isWindows() ? 'npm install -g @cometix/ccline' : 'sudo npm install -g @cometix/ccline'
  1085. await execAsync(installCmd, { timeout: 120000 })
  1086. console.log(ansis.green(` ✓ ${i18n.t('menu:tools.cclineInstallSuccess')}`))
  1087. const settingsPath = join(homedir(), '.claude', 'settings.json')
  1088. let settings: Record<string, any> = {}
  1089. if (await fs.pathExists(settingsPath)) {
  1090. settings = await fs.readJson(settingsPath)
  1091. }
  1092. settings.statusLine = {
  1093. type: 'command',
  1094. command: isWindows()
  1095. ? '~/.claude/ccline/ccline.exe'
  1096. : '~/.claude/ccline/ccline',
  1097. padding: 0,
  1098. }
  1099. await fs.ensureDir(join(homedir(), '.claude'))
  1100. await fs.writeJson(settingsPath, settings, { spaces: 2 })
  1101. console.log(ansis.green(` ✓ ${i18n.t('menu:tools.cclineConfigured')}`))
  1102. console.log()
  1103. console.log(ansis.cyan(` 💡 ${i18n.t('common:restartToApply')}`))
  1104. }
  1105. catch (error) {
  1106. console.log(ansis.red(` ✗ ${i18n.t('menu:tools.cclineInstallFailed', { error: String(error) })}`))
  1107. }
  1108. }
  1109. async function uninstallCCometixLine(): Promise<void> {
  1110. console.log()
  1111. console.log(ansis.yellow(` ⏳ ${i18n.t('menu:tools.cclineUninstalling')}`))
  1112. try {
  1113. const settingsPath = join(homedir(), '.claude', 'settings.json')
  1114. if (await fs.pathExists(settingsPath)) {
  1115. const settings = await fs.readJson(settingsPath)
  1116. delete settings.statusLine
  1117. await fs.writeJson(settingsPath, settings, { spaces: 2 })
  1118. console.log(ansis.green(` ✓ ${i18n.t('menu:tools.cclineConfigRemoved')}`))
  1119. }
  1120. const uninstallCmd = isWindows() ? 'npm uninstall -g @cometix/ccline' : 'sudo npm uninstall -g @cometix/ccline'
  1121. await execAsync(uninstallCmd, { timeout: 60000 })
  1122. console.log(ansis.green(` ✓ ${i18n.t('menu:tools.cclineUninstalled')}`))
  1123. }
  1124. catch (error) {
  1125. console.log(ansis.red(` ✗ ${i18n.t('menu:tools.cclineUninstallFailed', { error: String(error) })}`))
  1126. }
  1127. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.