Files
hapi/cli/src/modules/common/skills.ts
T
f10fbc7496 feat(cli): add GitHub Copilot CLI agent support via ACP (#1245)
* feat(cli): add GitHub Copilot CLI agent support via ACP

Wrap `copilot --acp --stdio` for remote sessions and spawn the native TUI locally, with full hub/web integration for spawn, resume, and permissions.

Fixes tiann/hapi#362

Co-Authored-By: HAPI <noreply@hapi.run>
Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(copilot): agent modes, models, slash/file UX, local session sync

Add Interactive/Plan/Autopilot (fleet is slash-only), subscription-aware
model discovery, web StatusBar/permission UX, @ file mentions, and fix
local Safe Yolo plus session-id locator for handoff/resume.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: re-trigger Codex PR review after auth outage

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: retry Codex PR review

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): preserve agent mode on resume and apply via ACP set_mode

Resume was dropping copilotAgentMode so Plan/Autopilot reset to interactive.
Also switch local/remote mode application to --mode / session set_mode instead of slash prompts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): wake remote loop when agent mode changes

Empty isolated queue tick lets setMode apply without inventing a user prompt.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): confirm mode changes before persisting

Await Copilot mode changes and expose discovered models so session state reflects backend acceptance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): guard mode discovery and slash updates

Keep model probes within runner roots and preserve active sessions when mode switching is unavailable or rejected.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): preserve resume and auto semantics

Deduplicate Copilot resume rows, apply Auto explicitly, and fail closed on denied permissions.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): close permission and model discovery gaps

Keep write-capable commands pending in read-only mode, extend model probe RPCs, and preserve explicit model validation before session creation.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): persist runtime model and agent mode

Fallback to ACP model options when direct model switching is unavailable and retain Copilot agent mode across hub restarts.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): normalize composer auto selection

Use the null session sentinel for Copilot Auto so the composer selects and resets default models consistently.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(copilot): reject local permission mode changes

* style(copilot): remove trailing blank line

* fix(copilot): secure local config handoffs

* fix(copilot): reject local agent mode slashes

* fix(copilot): reject mode changes during turns

* fix(copilot): consume rejected slash updates

* fix(copilot): preserve thinking across slash handling

* fix(copilot): stabilize async config changes

* fix(copilot): roll back rejected startup model

* fix(copilot): preserve cancellation and file mentions

* fix(copilot): hide local permission controls

* fix(deps): support clean workspace installs

* test(copilot): account for spawn mode argument

* fix(copilot): attribute usage to active model

---------

Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 08:19:12 +08:00

366 lines
12 KiB
TypeScript

import { access, open, readdir, readFile, stat } from 'fs/promises';
import { basename, dirname, join, resolve } from 'path';
import { homedir } from 'os';
import { parse as parseYaml } from 'yaml';
export interface SkillSummary {
name: string;
description?: string;
}
export interface ResolvedSkill extends SkillSummary {
body: string;
}
export const MAX_SKILL_FILE_BYTES = 128 * 1024;
export interface ListSkillsRequest {
flavor?: string;
}
export interface ListSkillsResponse {
success: boolean;
skills?: SkillSummary[];
error?: string;
}
type InstalledPlugin = {
installPath?: string;
installedAt?: string;
lastUpdated?: string;
};
type InstalledPluginsFile = {
plugins?: Record<string, InstalledPlugin[]>;
};
type DiscoveredSkill = ResolvedSkill & {
fileSize: number;
};
function getHomeDirectory(): string {
return process.env.HOME ?? process.env.USERPROFILE ?? homedir();
}
function normalizeFlavor(flavor?: string): string {
return (flavor ?? 'claude').trim().toLowerCase();
}
function getAgentConfigDir(flavor?: string): string {
const normalizedFlavor = normalizeFlavor(flavor);
switch (normalizedFlavor) {
case 'claude':
return process.env.CLAUDE_CONFIG_DIR || join(getHomeDirectory(), '.claude');
case 'codex':
return process.env.CODEX_HOME || join(getHomeDirectory(), '.codex');
case 'grok':
return process.env.GROK_HOME || join(getHomeDirectory(), '.grok');
default:
return join(getHomeDirectory(), `.${normalizedFlavor}`);
}
}
function getUserSkillsRoots(flavor?: string): string[] {
const home = getHomeDirectory();
const roots = [join(home, '.agents', 'skills')];
switch (normalizeFlavor(flavor)) {
case 'claude':
roots.push(join(getAgentConfigDir(flavor), 'skills'));
break;
case 'codex':
roots.push(join(getAgentConfigDir(flavor), 'skills'));
break;
case 'grok':
roots.push(join(getAgentConfigDir(flavor), 'skills'));
break;
case 'copilot':
roots.push(join(getAgentConfigDir(flavor), 'skills'));
break;
}
return roots;
}
function getAdminSkillsRoot(): string {
return join('/etc', 'codex', 'skills');
}
function getProjectSkillsRoots(directory: string, flavor?: string): string[] {
const roots = [join(directory, '.agents', 'skills')];
switch (normalizeFlavor(flavor)) {
case 'claude':
roots.push(join(directory, '.claude', 'skills'));
break;
case 'codex':
roots.push(join(directory, '.codex', 'skills'));
break;
case 'grok':
roots.push(join(directory, '.grok', 'skills'));
break;
case 'copilot':
roots.push(join(directory, '.copilot', 'skills'));
roots.push(join(directory, '.github', 'skills'));
break;
}
return roots;
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path);
return true;
} catch {
return false;
}
}
async function isDirectory(path: string): Promise<boolean> {
return await stat(path).then((info) => info.isDirectory()).catch(() => false);
}
async function listProjectSkillsRoots(workingDirectory?: string, flavor?: string): Promise<string[]> {
if (!workingDirectory) {
return [];
}
const resolvedWorkingDirectory = resolve(workingDirectory);
const directories = [resolvedWorkingDirectory];
let currentDirectory = resolvedWorkingDirectory;
while (true) {
if (await pathExists(join(currentDirectory, '.git'))) {
return directories.flatMap((directory) => getProjectSkillsRoots(directory, flavor));
}
const parentDirectory = dirname(currentDirectory);
if (parentDirectory === currentDirectory) {
return getProjectSkillsRoots(resolvedWorkingDirectory, flavor);
}
currentDirectory = parentDirectory;
directories.push(currentDirectory);
}
}
function parseFrontmatter(fileContent: string): { frontmatter?: Record<string, unknown>; body: string } {
const match = fileContent.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
if (!match) {
return { body: fileContent.trim() };
}
const yamlContent = match[1];
const body = match[2].trim();
try {
const parsed = parseYaml(yamlContent) as Record<string, unknown> | null;
return { frontmatter: parsed ?? undefined, body };
} catch {
return { body: fileContent.trim() };
}
}
function extractSkillSummary(skillDir: string, fileContent: string): SkillSummary | null {
const parsed = parseFrontmatter(fileContent);
const nameFromFrontmatter = typeof parsed.frontmatter?.name === 'string' ? parsed.frontmatter.name.trim() : '';
const name = nameFromFrontmatter || basename(skillDir);
if (!name) {
return null;
}
const description = typeof parsed.frontmatter?.description === 'string'
? parsed.frontmatter.description.trim()
: undefined;
return { name, description };
}
async function listTopLevelSkillDirs(skillsRoot: string, options: { includeCodexSystem?: boolean } = {}): Promise<string[]> {
try {
const entries = await readdir(skillsRoot);
const result: string[] = [];
for (const entry of entries) {
const entryPath = join(skillsRoot, entry);
if (!await isDirectory(entryPath)) {
continue;
}
if (entry.startsWith('.')) {
if (options.includeCodexSystem && entry === '.system') {
const systemEntries = await readdir(entryPath).catch(() => []);
for (const systemEntry of systemEntries) {
const systemEntryPath = join(entryPath, systemEntry);
if (!systemEntry.startsWith('.') && await isDirectory(systemEntryPath)) {
result.push(systemEntryPath);
}
}
}
continue;
}
result.push(entryPath);
}
return result;
} catch {
return [];
}
}
async function readSkillFile(filePath: string): Promise<{ content: string; fileSize: number } | null> {
try {
const file = await open(filePath, 'r');
try {
const info = await file.stat();
if (!info.isFile()) {
return null;
}
const bytesToRead = Math.min(info.size, MAX_SKILL_FILE_BYTES + 1);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = await file.read(buffer, 0, bytesToRead, 0);
return {
content: buffer.subarray(0, bytesRead).toString('utf-8'),
fileSize: info.size
};
} finally {
await file.close();
}
} catch {
return null;
}
}
async function readSkillsFromDirs(skillDirs: string[]): Promise<DiscoveredSkill[]> {
const skills = await Promise.all(skillDirs.map(async (dir): Promise<DiscoveredSkill | null> => {
const filePath = join(dir, 'SKILL.md');
const skillFile = await readSkillFile(filePath);
if (!skillFile) {
return null;
}
const summary = extractSkillSummary(dir, skillFile.content);
if (!summary) {
return null;
}
return {
...summary,
body: parseFrontmatter(skillFile.content).body,
fileSize: skillFile.fileSize
};
}));
return skills.filter((skill): skill is DiscoveredSkill => skill !== null);
}
function shouldIncludeCodexSystem(root: string, flavor: string): boolean {
if (flavor !== 'codex') {
return false;
}
return root.endsWith(join('.codex', 'skills'))
|| root === join(getAgentConfigDir('codex'), 'skills');
}
async function listPluginCacheSkillsRoots(flavor?: string): Promise<string[]> {
const installedPath = join(getAgentConfigDir(flavor), 'plugins', 'installed_plugins.json');
let installed: InstalledPluginsFile;
try {
installed = JSON.parse(await readFile(installedPath, 'utf-8')) as InstalledPluginsFile;
} catch {
return [];
}
const getInstallTime = (installation: InstalledPlugin): number => {
const lastUpdated = Date.parse(installation.lastUpdated ?? '');
if (Number.isFinite(lastUpdated)) return lastUpdated;
const installedAt = Date.parse(installation.installedAt ?? '');
return Number.isFinite(installedAt) ? installedAt : 0;
};
return Object.values(installed.plugins ?? {})
.filter((installations): installations is InstalledPlugin[] => Array.isArray(installations))
.map((installations) => [...installations]
.sort((a, b) => getInstallTime(b) - getInstallTime(a))[0]?.installPath)
.filter((installPath): installPath is string => typeof installPath === 'string' && installPath.length > 0)
.map((installPath) => join(installPath, 'skills'));
}
async function discoverSkills(workingDirectory?: string, options: { flavor?: string } = {}): Promise<DiscoveredSkill[]> {
const flavor = normalizeFlavor(options.flavor);
const projectRoots = await listProjectSkillsRoots(workingDirectory, flavor);
const userRoots = getUserSkillsRoots(flavor);
const pluginRoots = await listPluginCacheSkillsRoots(flavor);
const adminRoot = getAdminSkillsRoot();
const includeAdminRoots = flavor === 'codex';
const [projectSkillDirs, userSkillDirs, pluginSkillDirs, adminSkillDirs] = await Promise.all([
Promise.all(projectRoots.map(async (root) => await listTopLevelSkillDirs(root, { includeCodexSystem: shouldIncludeCodexSystem(root, flavor) }))).then((dirs) => dirs.flat()),
Promise.all(userRoots.map(async (root) => await listTopLevelSkillDirs(root, { includeCodexSystem: shouldIncludeCodexSystem(root, flavor) }))).then((dirs) => dirs.flat()),
Promise.all(pluginRoots.map(async (root) => await listTopLevelSkillDirs(root, { includeCodexSystem: false }))).then((dirs) => dirs.flat()),
includeAdminRoots ? listTopLevelSkillDirs(adminRoot, { includeCodexSystem: true }) : [],
]);
const [projectSkills, userSkills, pluginSkills, adminSkills] = await Promise.all([
readSkillsFromDirs(projectSkillDirs),
readSkillsFromDirs(userSkillDirs),
readSkillsFromDirs(pluginSkillDirs),
readSkillsFromDirs(adminSkillDirs),
]);
const dedupedSkills = new Map<string, DiscoveredSkill>();
for (const skill of [
...projectSkills,
...userSkills,
...pluginSkills,
...adminSkills,
]) {
if (!dedupedSkills.has(skill.name)) {
dedupedSkills.set(skill.name, skill);
}
}
return [...dedupedSkills.values()].sort((a, b) => a.name.localeCompare(b.name));
}
export async function listSkills(workingDirectory?: string, options: { flavor?: string } = {}): Promise<SkillSummary[]> {
const skills = await discoverSkills(workingDirectory, options);
return skills.map(({ name, description }) => ({ name, description }));
}
function validateSkillName(name: string): string {
const trimmed = name.trim();
if (
!trimmed
|| trimmed.length > 128
|| trimmed === '.'
|| trimmed === '..'
|| trimmed.includes('/')
|| trimmed.includes('\\')
|| trimmed.includes('\0')
) {
throw new Error('Invalid skill name');
}
return trimmed;
}
export async function resolveSkill(
name: string,
workingDirectory?: string,
options: { flavor?: string } = {}
): Promise<ResolvedSkill | null> {
const skillName = validateSkillName(name);
const skills = await discoverSkills(workingDirectory, options);
const skill = skills.find((candidate) => candidate.name === skillName);
if (!skill) {
return null;
}
if (skill.fileSize > MAX_SKILL_FILE_BYTES) {
throw new Error(`Skill is too large to load (maximum ${MAX_SKILL_FILE_BYTES} bytes)`);
}
return {
name: skill.name,
description: skill.description,
body: skill.body
};
}